Example usage for java.net URLConnection getContent

List of usage examples for java.net URLConnection getContent

Introduction

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

Prototype

public Object getContent() throws IOException 

Source Link

Document

Retrieves the contents of this URL connection.

Usage

From source file:de.quadrillenschule.azocamsyncd.astromode.SmartPhoneWrapper.java

public static SmartPhoneStatus update(PhotoSerie ps) throws IOException {
    URL url;/*  w w w  .  java2 s.  c om*/
    String retval;
    try {
        url = new URL(PROTOCOL + "://" + LAST_WORKING_IP + ":" + PORT + "/"
                + WebService.WebCommands.updateTriggered + "/?" + WebService.WebParameters.jobid + "="
                + ps.getId() + "&" + WebService.WebParameters.receivedImages + "=" + ps.getReceived());
        lastStatus = SmartPhoneStatus.TRYING;
        URLConnection uc = url.openConnection();
        uc.setConnectTimeout(3000);
        StringWriter sw = new StringWriter();
        IOUtils.copy((InputStream) uc.getContent(), System.out);

    } catch (MalformedURLException ex) {
        Logger.getLogger(SmartPhoneWrapper.class.getName()).log(Level.SEVERE, null, ex);

        return SmartPhoneStatus.ERROR;

    }

    lastStatus = SmartPhoneStatus.CONNECTED;
    return SmartPhoneStatus.CONNECTED;
}

From source file:de.quadrillenschule.azocamsyncd.astromode.SmartPhoneWrapper.java

public static String getFromSmartPhone(WebService.WebCommands command, boolean doCheck) throws IOException {
    String retval;/*from www  . ja v a 2s.  c  om*/
    SmartPhoneStatus status = SmartPhoneStatus.TRYING;

    lastStatus = SmartPhoneStatus.TRYING;
    URL url;
    try {
        url = new URL(PROTOCOL + "://" + LAST_WORKING_IP + ":" + PORT + "/" + command.name());
        System.out.println("Trying " + url.toString());
        URLConnection uc = url.openConnection();
        uc.setConnectTimeout(3000);
        StringWriter sw = new StringWriter();
        IOUtils.copy((InputStream) uc.getContent(), sw);
        retval = sw.toString();
        status = SmartPhoneStatus.CONNECTED;

        lastStatus = SmartPhoneStatus.CONNECTED;
    } catch (MalformedURLException ex) {
        Logger.getLogger(SmartPhoneWrapper.class.getName()).log(Level.SEVERE, null, ex);
        status = SmartPhoneStatus.ERROR;
        retval = SmartPhoneStatus.ERROR.name();

        lastStatus = SmartPhoneStatus.ERROR;
    }

    return retval;
}

From source file:org.opensha.commons.util.FileUtils.java

/**
 *
 * @param url : URL of file to be read/*  w w  w. ja  v  a  2  s  .  c  o m*/
 * @return : arrayList containing the lines in file
 * @throws FileNotFoundException
 * @throws IOException
 */
public static ArrayList<String> loadFile(URL url) throws IOException {
    if (D)
        System.out.println("url=" + url);
    URLConnection uc = url.openConnection();
    return loadStream((InputStream) uc.getContent());
}

From source file:org.opensha.commons.util.FileUtils.java

/**
 * return a object read from the URL/*from ww w.j  a va 2 s. c om*/
 * @param url
 * @return
 */
public static Object loadObjectFromURL(URL url) {
    try {
        URLConnection uc = url.openConnection();
        ObjectInputStream tis = new ObjectInputStream((InputStream) uc.getContent());
        Object obj = tis.readObject();
        tis.close();
        return obj;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.openhab.binding.fems.FEMSCore.java

/**
 * Initialize FEMS/FEMSmonitor system/*from  www.j  a va  2s.c  o m*/
 */
private static void init() {
    int returnCode = 0;
    try {
        log.info("FEMS Initialization");

        // start IO Agent
        Constants.IO_AGENT.start();

        // init LCD display
        Constants.IO_AGENT.setLcdText(true, "FEMS Selbsttest");

        // Init runtime variables
        Runtime rt = Runtime.getRuntime();
        Process proc;
        InitStatus initStatus = new InitStatus();

        try {
            // check for valid ip address
            InetAddress ip = Tools.getIPaddress();
            if (ip == null) {
                try {
                    proc = rt.exec("/sbin/dhclient eth0");
                    proc.waitFor();
                    ip = Tools.getIPaddress(); /* try again */
                    if (ip == null) { /* still no IP */
                        throw new IPException();
                    }
                } catch (IOException | InterruptedException e) {
                    throw new IPException(e.getMessage());
                }
            }
            log.info("IP: " + ip.getHostAddress());
            initStatus.setIp(true);
            Constants.IO_AGENT.setLcdText(initStatus + " IP ok      ");
            Constants.IO_AGENT.handleCommand(Constants.UserLED_1, OnOffType.ON);

            // check time
            if (Tools.isDateValid()) { /* date is valid, so we check internet access only */
                log.info("Date ok: " + Constants.LONG_DATE_FORMAT.format(new Date()));
                try {
                    URL url = new URL("https://fenecon.de");
                    URLConnection con = url.openConnection();
                    con.setConnectTimeout(5000);
                    con.getContent();
                } catch (IOException e) {
                    throw new InternetException(e.getMessage());
                }
            } else {
                log.info("Date not ok: " + Constants.LONG_DATE_FORMAT.format(new Date()));
                try {
                    proc = rt.exec(
                            "/usr/sbin/ntpdate -b -u fenecon.de 0.pool.ntp.org 1.pool.ntp.org 2.pool.ntp.org 3.pool.ntp.org");
                    proc.waitFor();
                    if (!Tools.isDateValid()) {
                        // try one more time
                        proc = rt.exec(
                                "/usr/sbin/ntpdate -b -u fenecon.de 0.pool.ntp.org 1.pool.ntp.org 2.pool.ntp.org 3.pool.ntp.org");
                        proc.waitFor();
                        if (!Tools.isDateValid()) {
                            throw new InternetException(
                                    "Wrong Date: " + Constants.LONG_DATE_FORMAT.format(new Date()));
                        }
                    }
                    log.info("Date now ok: " + Constants.LONG_DATE_FORMAT.format(new Date()));
                } catch (IOException | InterruptedException e) {
                    throw new InternetException(e.getMessage());
                }
            }
            log.info("Internet access is available");
            initStatus.setInternet(true);
            Constants.IO_AGENT.setLcdText(initStatus + " Internet ok");
            Constants.IO_AGENT.handleCommand(Constants.UserLED_2, OnOffType.ON);

            // test modbus
            if (isModbusWorking(log, ess)) {
                log.info("Modbus is ok");
                initStatus.setModbus(true);
                Constants.IO_AGENT.setLcdText(initStatus + " RS485 ok   ");
                Constants.IO_AGENT.handleCommand(Constants.UserLED_3, OnOffType.ON);
            } else {
                if (debug) { // if we are in debug mode: ignore RS485-errors
                    log.info("Ignore RS485-Error");
                } else {
                    throw new RS485Exception();
                }
            }

            // Exit message
            log.info("Finished without error");
            Constants.IO_AGENT.setLcdText(initStatus + "  erfolgreich");

            // announce systemd finished
            log.info("Announce systemd: ready");
            try {
                proc = rt.exec("/bin/systemd-notify --ready");
                proc.waitFor();
            } catch (IOException | InterruptedException e) {
                log.error(e.getMessage());
            }
        } catch (FEMSException e) {
            log.error(e.getMessage());
            log.error("Finished with error");
            Constants.IO_AGENT.setLcdText(initStatus + " " + e.getMessage());
            returnCode = 1;
        }

        // Check if Yaler is active
        if (FEMSYaler.getFEMSYaler().isActive()) {
            log.info("Yaler is activated");
        } else {
            log.info("Yaler is deactivated");
        }

        // Send message
        if (apikey == null) {
            log.error("Apikey is not available");
        } else {
            // start Agents
            Constants.ONLINE_MONITORING_AGENT.setApikey(apikey);
            Constants.ONLINE_MONITORING_AGENT.start();
            Constants.ONLINE_MONITORING_CACHE_AGENT.setApikey(apikey);
            Constants.ONLINE_MONITORING_CACHE_AGENT.start();

            Constants.ONLINE_MONITORING_AGENT.sendSystemMessage(log.getLog());
        }

        // start system update
        log.info("Start system update");
        try {
            proc = rt.exec("/usr/bin/fems-autoupdate");
            proc.waitFor();
        } catch (IOException | InterruptedException e) {
            log.error(e.getMessage());
        }

        Constants.IO_AGENT.handleCommand(Constants.UserLED_4, OnOffType.ON);

    } catch (Throwable e) { // Catch everything else
        returnCode = 2;
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        log.error("Critical error: " + sw.toString());
        e.printStackTrace();
        Constants.ONLINE_MONITORING_AGENT.sendSystemMessage(log.getLog()); // try to send log
    }

    try {
        Thread.sleep(2000); // give the agents some time to try sending
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    // Stop agents
    Constants.ONLINE_MONITORING_AGENT.interrupt();
    try {
        Constants.ONLINE_MONITORING_AGENT.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    Constants.ONLINE_MONITORING_CACHE_AGENT.interrupt();
    try {
        Constants.ONLINE_MONITORING_CACHE_AGENT.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    Constants.IO_AGENT.interrupt();
    try {
        Constants.IO_AGENT.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    // Exit
    System.exit(returnCode);
}

From source file:org.apache.synapse.config.Util.java

/**
 * Get an object from a given URL. Will first fetch the content from the
 * URL and depending on the content-type, a suitable XMLToObjectMapper
 * (if available) would be used to transform this content into an Object.
 * If a suitable XMLToObjectMapper cannot be found, the content would be
 * treated as XML and an OMNode would be returned
 * @param url the URL to the resource//from w  w  w .  j ava 2s .  c  o  m
 * @return an Object created from the given URL
 */
public static Object getObject(URL url) {
    try {
        URLConnection urlc = url.openConnection();
        XMLToObjectMapper xmlToObject = getXmlToObjectMapper(urlc.getContentType());

        try {
            XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(urlc.getInputStream());
            StAXOMBuilder builder = new StAXOMBuilder(parser);
            OMElement omElem = builder.getDocumentElement();

            // detach from URL connection and keep in memory
            // TODO remove this 
            omElem.build();

            if (xmlToObject != null) {
                return xmlToObject.getObjectFromOMNode(omElem);
            } else {
                return omElem;
            }

        } catch (XMLStreamException e) {
            log.warn("Content at URL : " + url + " is non XML..");
            return urlc.getContent();
        }

    } catch (IOException e) {
        handleException("Error connecting to URL : " + url, e);
    }
    return null;
}

From source file:CookieAccessor.java

/**
 * Get cookies for a url from cookie store
 *///w ww  .j a v a  2s .co m
public void getCookieUsingCookieHandler() {
    try {
        // instantiate CookieManager; make sure to set CookiePolicy
        CookieManager manager = new CookieManager();
        manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
        CookieHandler.setDefault(manager);

        // get content from URLConnection; cookies are set by web site
        URL url = new URL("http://host.example.com");
        URLConnection connection = url.openConnection();
        connection.getContent();

        // get cookies from underlying CookieStore
        CookieStore cookieJar = manager.getCookieStore();
        List<HttpCookie> cookies = cookieJar.getCookies();
        for (HttpCookie cookie : cookies) {
            System.out.println("CookieHandler retrieved cookie: " + cookie);
        }
    } catch (Exception e) {
        System.out.println("Unable to get cookie using CookieHandler");
        e.printStackTrace();
    }
}

From source file:org.uclv.darkaiv.md.extractor.GrobidExtractor.java

/**
 *
 * @return true if Grobid.server.url is reachable
 * @throws IOException/*from w  ww . j a  va 2s.c  o  m*/
 */
public boolean existConnection() throws IOException {

    boolean isConn;

    File file = new File("./config/grobid_service/");
    URL[] urls = { file.toURI().toURL() };
    ClassLoader loader = new URLClassLoader(urls);
    ResourceBundle resources = ResourceBundle.getBundle("grobid", Locale.getDefault(), loader);

    String host = resources.getString("grobid.server.url");

    int port = 8080;

    final URL url = new URL(host);
    final URLConnection conn = url.openConnection();
    if (conn != null) {
        try {
            conn.getContent();
            isConn = true;
        } catch (Exception e) {
            isConn = false;
        }
    } else {
        isConn = false;
    }

    return isConn;
}

From source file:org.vlir.darkaiv.md_extractor.GrobidExtractor.java

/**
 *
 * @return true if Grobid.server.url is reachable
 * @throws IOException/* w ww  .  j ava2 s . c  o  m*/
 */
public boolean existConnection() throws IOException {

    boolean isConn;

    //        File file = new File("./config/grobid_service/");
    File file = new File(".");
    System.out.println("Base path");
    System.out.println(file.getAbsolutePath());
    //         In next version it should be implemented using spring, so... it should not be necesary
    URL[] urls = { file.toURI().toURL() };
    ClassLoader loader = new URLClassLoader(urls);
    ResourceBundle resources = ResourceBundle.getBundle("grobid", Locale.getDefault(), loader);

    final URL url = new URL(host);
    final URLConnection conn = url.openConnection();
    if (conn != null) {
        try {
            conn.getContent();
            isConn = true;
        } catch (Exception e) {
            isConn = false;
        }
    } else {
        isConn = false;
    }

    return isConn;
}

From source file:org.rhq.cassandra.schema.UpdateFolder.java

/**
 * Loads the initial set of update files based on the input folder.
 *
 * @return list of update files// ww w .j av a2s .co  m
 * @throws Exception
 */
private List<UpdateFile> loadUpdateFiles() throws Exception {
    List<UpdateFile> files = new ArrayList<UpdateFile>();
    InputStream stream = null;

    try {
        URL resourceFolderURL = this.getClass().getClassLoader().getResource(folder);

        if (resourceFolderURL.getProtocol().equals("file")) {
            stream = this.getClass().getClassLoader().getResourceAsStream(folder);
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream));

            String updateFile;
            while ((updateFile = reader.readLine()) != null) {
                files.add(new UpdateFile(folder + "/" + updateFile));
            }
        } else if (resourceFolderURL.getProtocol().equals("jar")) {
            URL jarURL = this.getClass().getClassLoader().getResources(folder).nextElement();
            JarURLConnection jarURLCon = (JarURLConnection) (jarURL.openConnection());
            JarFile jarFile = jarURLCon.getJarFile();
            Enumeration<JarEntry> entries = jarFile.entries();
            while (entries.hasMoreElements()) {
                String entry = entries.nextElement().getName();
                if (entry.startsWith(folder) && !entry.equals(folder) && !entry.equals(folder + "/")) {
                    files.add(new UpdateFile(entry));
                }
            }
        } else if (resourceFolderURL.getProtocol().equals("vfs")) {
            URLConnection conn = resourceFolderURL.openConnection();
            VirtualFile virtualFolder = (VirtualFile) conn.getContent();
            for (VirtualFile virtualChild : virtualFolder.getChildren()) {
                if (!virtualChild.isDirectory()) {
                    files.add(new UpdateFile(virtualChild.getPathNameRelativeTo(virtualFolder.getParent())));
                }
            }
        } else {
            // In the event we get another protocol that we do not recognize, throw an
            // exception instead of failing silently.
            throw new RuntimeException(
                    "The URL protocol [" + resourceFolderURL.getProtocol() + "] is not " + "supported");
        }

        Collections.sort(files, new Comparator<UpdateFile>() {
            @Override
            public int compare(UpdateFile o1, UpdateFile o2) {
                return o1.compareTo(o2);
            }
        });
    } catch (Exception e) {
        log.error("Error reading the list of update files.", e);
        throw e;
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (Exception e) {
                log.error("Error closing the stream with the list of update files.", e);
                throw e;
            }
        }
    }

    return files;
}