Example usage for java.net ConnectException getMessage

List of usage examples for java.net ConnectException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.phonytive.astive.server.AstiveServer.java

public static void main(String[] args) throws Exception {
    astivedSP = getServiceProperties(ASTIVED_PROPERTIES, "astived");
    adminDaemonSP = getServiceProperties(ADMIN_DAEMON_PROPERTIES, "admin thread");
    telnedSP = getServiceProperties(TELNED_PROPERTIES, "telned");

    ArrayList<ServiceProperties> serviceProperties = new ArrayList();
    serviceProperties.add(astivedSP);// ww  w.j  av  a 2 s  .co  m

    if (!adminDaemonSP.isDisabled()) {
        serviceProperties.add(adminDaemonSP);
    }

    if (!telnedSP.isDisabled()) {
        serviceProperties.add(telnedSP);
    }

    if ((args.length == 0) || args[0].equals("-h") || args[0].equals("--help")) {
        printUsage();
        System.exit(1);
    }

    // Create a Parser
    CommandLineParser parser = new BasicParser();

    Options start = new Options();
    start.addOption("h", "help", false, AppLocale.getI18n("cli.option.printUsage"));
    start.addOption("v", "version", false, "Prints the Astive Server version and exits.");
    start.addOption("d", "debug", false, AppLocale.getI18n("cli.option.debug"));
    start.addOption("q", "quiet", false, AppLocale.getI18n("cli.option.daemonMode"));
    start.addOption(OptionBuilder.hasArg(true).withArgName("host").withLongOpt("admin-bind")
            .withDescription("" + AppLocale.getI18n("cli.option.bind", new Object[] { "admin" })).create());
    start.addOption(OptionBuilder.hasArg(true).withArgName("port").withLongOpt("admin-port")
            .withDescription("" + AppLocale.getI18n("cli.option.port", new Object[] { "admin" })).create());
    start.addOption(OptionBuilder.hasArg(true).withArgName("port").withLongOpt("astived-port")
            .withDescription("" + AppLocale.getI18n("cli.option.port", new Object[] { "astived" })).create());

    start.addOption(OptionBuilder.hasArg(true).withArgName("host").withLongOpt("astived-host")
            .withDescription("" + AppLocale.getI18n("cli.option.bind", new Object[] { "astived" })).create());
    start.addOption(OptionBuilder.hasArg(true).withArgName("port").withLongOpt("telned-port")
            .withDescription("" + AppLocale.getI18n("cli.option.port", new Object[] { "telned" })).create());

    start.addOption(OptionBuilder.hasArg(true).withArgName("host").withLongOpt("telned-host")
            .withDescription("" + AppLocale.getI18n("cli.option.host", new Object[] { "telned" })).create());

    Options stop = new Options();
    stop.addOption(OptionBuilder.withLongOpt("--help")
            .withDescription("" + AppLocale.getI18n("cli.option.printUsage")).create());

    stop.addOption("h", "host", false,
            AppLocale.getI18n("cli.option.stop.host", new Object[] { DEFAULT_AGI_SERVER_BIND_ADDR }));

    stop.addOption("p", "port", false,
            AppLocale.getI18n("cli.option.stop.port", new Object[] { DEFAULT_AGI_SERVER_PORT }));

    Options deploy = new Options();
    deploy.addOption("h", "help", false, AppLocale.getI18n("cli.option.printUsage"));

    Options undeploy = new Options();
    undeploy.addOption("h", "help", false, AppLocale.getI18n("cli.option.printUsage"));

    if (args.length == 0) {
        printUsage();
        System.exit(1);
    } else if (!isCommand(args[0])) {
        printUnavailableCmd(args[0]);
        System.exit(1);
    }

    AdminCommand cmd = AdminCommand.get(args[0]);

    if (cmd.equals(AdminCommand.DEPLOY) && ((args.length < 2) || !isFileJar(args[1]))) {
        logger.error(AppLocale.getI18n("cli.invalid.app"));
        printUsage(AdminCommand.DEPLOY, deploy);
        System.exit(1);
    }

    if (cmd.equals(AdminCommand.UNDEPLOY) && ((args.length < 2) || !isFileJar(args[1]))) {
        printUsage(AdminCommand.UNDEPLOY, undeploy);
        System.exit(1);
    }

    // Parse the program arguments
    try {
        if (cmd.equals(AdminCommand.START)) {
            CommandLine commandLine = parser.parse(start, args);

            if (commandLine.hasOption('h')) {
                printUsage(cmd, start);
                System.exit(0);
            }

            if (commandLine.hasOption('v')) {
                // Them start the server without noise
            }

            if (commandLine.hasOption("astived-bind")) {
                astivedSP.setBindAddr(InetAddress.getByName(commandLine.getOptionValue("astived-port")));
            }

            if (commandLine.hasOption("astived-port")) {
                astivedSP.setPort(Integer.parseInt(commandLine.getOptionValue("astived-port")));
            }

            if (commandLine.hasOption("admin-bind")) {
                adminDaemonSP.setBindAddr(InetAddress.getByName(commandLine.getOptionValue("admin-bind")));
            }

            if (commandLine.hasOption("admin-port")) {
                adminDaemonSP.setPort(Integer.parseInt(commandLine.getOptionValue("admin-port")));
            }

            if (commandLine.hasOption("telned-bind")) {
                telnedSP.setBindAddr(InetAddress.getByName(commandLine.getOptionValue("telned-bind")));
            }

            if (commandLine.hasOption("telned-port")) {
                adminDaemonSP.setPort(Integer.parseInt(commandLine.getOptionValue("telned-port")));
            }

            if (!NetUtil.available(astivedSP.getPort())) {
                out.println(AppLocale.getI18n("cantStartFastAgiServerSocket",
                        new Object[] { astivedSP.getBindAddr().getHostAddress(), astivedSP.getPort() }));
                System.exit(-1);
            }

            if (!NetUtil.available(adminDaemonSP.getPort())) {
                adminDaemonSP.setUnableToOpen(true);
            }

            if (!NetUtil.available(telnedSP.getPort())) {
                telnedSP.setUnableToOpen(true);
            }

            InitOutput.printInit(serviceProperties);

            AstiveServer server = new AstiveServer(astivedSP.getPort(), astivedSP.getBacklog(),
                    astivedSP.getBindAddr());
            server.start();
        }

        if (!cmd.equals(AdminCommand.START) && adminDaemonSP.isDisabled()) {
            logger.info("unableToAccessAdminDaemon");
        }

        if (cmd.equals(AdminCommand.STOP)) {
            CommandLine commandLine = parser.parse(stop, args);

            if (commandLine.hasOption("--help")) {
                printUsage(cmd, stop);
                System.exit(0);
            }

            if (commandLine.hasOption('h')) {
                if (commandLine.getOptionValue('h') == null) {
                    printUsage(cmd, stop);
                    System.exit(0);
                }

                astivedSP.setBindAddr(InetAddress.getByName(commandLine.getOptionValue('h')));
            }

            if (commandLine.hasOption('p')) {
                if (commandLine.getOptionValue('p') == null) {
                    printUsage(cmd, stop);
                    System.exit(0);
                }

                astivedSP.setPort(Integer.parseInt(commandLine.getOptionValue('p')));
            }

            AdminDaemonClient adClient = new AdminDaemonClient(adminDaemonSP.getBindAddr(),
                    adminDaemonSP.getPort());
            adClient.stop();
        }

        // TODO: This needs to be researched before a full implementation.
        // for now is only possible to do deployments into the local server.
        if (cmd.equals(AdminCommand.DEPLOY)) {
            AdminDaemonClient adClient = new AdminDaemonClient(adminDaemonSP.getBindAddr(),
                    adminDaemonSP.getPort());
            adClient.deploy(args[1]);
        }

        if (cmd.equals(AdminCommand.UNDEPLOY)) {
            AdminDaemonClient adClient = new AdminDaemonClient(adminDaemonSP.getBindAddr(),
                    adminDaemonSP.getPort());
            adClient.undeploy(args[1]);
        }
    } catch (java.net.ConnectException ex) {
        logger.info("serverNotRunning");
    } catch (Exception ex) {
        logger.error(AppLocale.getI18n("unexpectedError", new Object[] { ex.getMessage() }));
    }
}

From source file:com.fonoster.astive.server.AstiveServer.java

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

    DOMConfigurator.configure(AbstractAstiveServer.ASTIVE_HOME + "/conf/log4j.xml");

    astivedSP = getServiceProperties(ASTIVED_PROPERTIES, "astived");
    adminDaemonSP = getServiceProperties(ADMIN_DAEMON_PROPERTIES, "admin thread");
    telnedSP = getServiceProperties(TELNED_PROPERTIES, "telned");

    ArrayList<ServiceProperties> serviceProperties = new ArrayList();
    serviceProperties.add(astivedSP);//  w  w w  .j  ava2s  . c  o  m

    // Adding security measure
    AstPolicy ap = AstPolicy.getInstance();
    ap.addPermissions(astivedSP);
    ap.addPermissions(adminDaemonSP);
    ap.addPermissions(telnedSP);

    if (!adminDaemonSP.isDisabled()) {
        serviceProperties.add(adminDaemonSP);
    }

    if (!telnedSP.isDisabled()) {
        serviceProperties.add(telnedSP);
    }

    if ((args.length == 0) || args[0].equals("-h") || args[0].equals("--help")) {
        printUsage();
        System.exit(1);
    }

    // Create a Parser
    CommandLineParser parser = new BasicParser();

    Options start = new Options();

    start.addOption("h", "help", false, AppLocale.getI18n("optionHelp"));
    start.addOption("v", "version", false, AppLocale.getI18n("optionVersion"));
    start.addOption("d", "debug", false, AppLocale.getI18n("optionDebug"));
    start.addOption("q", "quiet", false, AppLocale.getI18n("optionQuiet"));

    start.addOption(OptionBuilder.hasArg(true).withArgName("host").withLongOpt("admin-bind")
            .withDescription(AppLocale.getI18n("optionBind", new Object[] { "admin" })).create());

    start.addOption(OptionBuilder.hasArg(true).withArgName("port").withLongOpt("admin-port")
            .withDescription(AppLocale.getI18n("optionPort", new Object[] { "admin" })).create());

    start.addOption(OptionBuilder.hasArg(true).withArgName("port").withLongOpt("astived-port")
            .withDescription(AppLocale.getI18n("optionPort", new Object[] { "astived" })).create());

    start.addOption(OptionBuilder.hasArg(true).withArgName("host").withLongOpt("astived-host")
            .withDescription(AppLocale.getI18n("optionBind", new Object[] { "astived" })).create());

    start.addOption(OptionBuilder.hasArg(true).withArgName("port").withLongOpt("telned-port")
            .withDescription(AppLocale.getI18n("optionPort", new Object[] { "telned" })).create());

    start.addOption(OptionBuilder.hasArg(true).withArgName("host").withLongOpt("telned-host")
            .withDescription(AppLocale.getI18n("optionBind", new Object[] { "telned" })).create());

    Options stop = new Options();
    stop.addOption(OptionBuilder.hasArg(true).withArgName("host").withLongOpt("host")
            .withDescription(AppLocale.getI18n("optionHelp")).create());

    stop.addOption("h", "host", false,
            AppLocale.getI18n("optionStopHost", new Object[] { DEFAULT_AGI_SERVER_BIND_ADDR }));

    stop.addOption("p", "port", false,
            AppLocale.getI18n("optionStopPort", new Object[] { DEFAULT_AGI_SERVER_PORT }));

    Options deploy = new Options();
    deploy.addOption("h", "help", false, AppLocale.getI18n("optionHelp"));

    Options undeploy = new Options();
    undeploy.addOption("h", "help", false, AppLocale.getI18n("optionHelp"));

    if (args.length == 0) {
        printUsage();
        System.exit(1);
    } else if (!isCommand(args[0])) {
        printUnavailableCmd(args[0]);
        System.exit(1);
    }

    AdminCommand cmd = AdminCommand.get(args[0]);

    // Parse the program arguments
    try {
        if (cmd.equals(AdminCommand.START)) {

            CommandLine commandLine = parser.parse(start, args);

            Logger root = LogManager.getRootLogger();
            Enumeration allLoggers = root.getLoggerRepository().getCurrentLoggers();

            if (commandLine.hasOption('q')) {
                root.setLevel(Level.ERROR);
                while (allLoggers.hasMoreElements()) {
                    Category tmpLogger = (Category) allLoggers.nextElement();
                    tmpLogger.setLevel(Level.ERROR);
                }
            } else if (commandLine.hasOption('d')) {
                root.setLevel(Level.DEBUG);
                while (allLoggers.hasMoreElements()) {
                    Category tmpLogger = (Category) allLoggers.nextElement();
                    tmpLogger.setLevel(Level.DEBUG);
                }
            } else {
                root.setLevel(Level.INFO);
                while (allLoggers.hasMoreElements()) {
                    Category tmpLogger = (Category) allLoggers.nextElement();
                    tmpLogger.setLevel(Level.INFO);
                }
            }

            if (commandLine.hasOption('h')) {
                printUsage(cmd, start);
                System.exit(0);
            }

            if (commandLine.hasOption('v')) {
                out.println(AppLocale.getI18n("astivedVersion",
                        new String[] { Version.VERSION, Version.BUILD_TIME }));
                System.exit(0);
            }

            if (commandLine.hasOption("astived-bind")) {
                astivedSP.setBindAddr(InetAddress.getByName(commandLine.getOptionValue("astived-port")));
            }

            if (commandLine.hasOption("astived-port")) {
                astivedSP.setPort(Integer.parseInt(commandLine.getOptionValue("astived-port")));
            }

            if (commandLine.hasOption("admin-bind")) {
                adminDaemonSP.setBindAddr(InetAddress.getByName(commandLine.getOptionValue("admin-bind")));
            }

            if (commandLine.hasOption("admin-port")) {
                adminDaemonSP.setPort(Integer.parseInt(commandLine.getOptionValue("admin-port")));
            }

            if (commandLine.hasOption("telned-bind")) {
                telnedSP.setBindAddr(InetAddress.getByName(commandLine.getOptionValue("telned-bind")));
            }

            if (commandLine.hasOption("telned-port")) {
                telnedSP.setPort(Integer.parseInt(commandLine.getOptionValue("telned-port")));
            }

            if (!NetUtil.isPortAvailable(astivedSP.getPort())) {
                out.println(AppLocale.getI18n("errorCantStartFastAgiServerSocket",
                        new Object[] { astivedSP.getBindAddr().getHostAddress(), astivedSP.getPort() }));
                System.exit(-1);
            }

            if (!NetUtil.isPortAvailable(adminDaemonSP.getPort())) {
                adminDaemonSP.setUnableToOpen(true);
            }

            if (!NetUtil.isPortAvailable(telnedSP.getPort())) {
                telnedSP.setUnableToOpen(true);
            }

            new InitOutput().printInit(serviceProperties);

            AstiveServer server = new AstiveServer(astivedSP.getPort(), astivedSP.getBacklog(),
                    astivedSP.getBindAddr());
            server.start();
        }

        if (!cmd.equals(AdminCommand.START) && adminDaemonSP.isDisabled()) {
            LOG.warn("errorUnableToAccessAdminDaemon");
        }

        if (cmd.equals(AdminCommand.STOP)) {
            CommandLine commandLine = parser.parse(stop, args);

            if (commandLine.hasOption("--help")) {
                printUsage(cmd, stop);
                System.exit(0);
            }

            if (commandLine.hasOption('h')) {
                if (commandLine.getOptionValue('h') == null) {
                    printUsage(cmd, stop);
                    System.exit(0);
                }

                astivedSP.setBindAddr(InetAddress.getByName(commandLine.getOptionValue('h')));
            }

            if (commandLine.hasOption('p')) {
                if (commandLine.getOptionValue('p') == null) {
                    printUsage(cmd, stop);
                    System.exit(0);
                }

                astivedSP.setPort(Integer.parseInt(commandLine.getOptionValue('p')));
            }

            AdminDaemonClient adClient = new AdminDaemonClient(adminDaemonSP.getBindAddr(),
                    adminDaemonSP.getPort());
            adClient.stop();
        }

        // TODO: This needs to be researched before a full implementation.
        // for now is only possible to do deployments into a local server.
        if (cmd.equals(AdminCommand.DEPLOY)) {
            CommandLine commandLine = parser.parse(deploy, args);

            if (args.length < 2) {
                printUsage(cmd, deploy);
                System.exit(1);
            } else if (commandLine.hasOption('h')) {
                printUsage(cmd, deploy);
                System.exit(0);
            }

            AdminDaemonClient adClient = new AdminDaemonClient(adminDaemonSP.getBindAddr(),
                    adminDaemonSP.getPort());
            adClient.deploy(args[1]);
        }

        if (cmd.equals(AdminCommand.UNDEPLOY)) {

            CommandLine commandLine = parser.parse(undeploy, args);

            if (args.length < 2) {
                printUsage(cmd, undeploy);
                System.exit(1);
            } else if (commandLine.hasOption('h')) {
                printUsage(cmd, undeploy);
                System.exit(0);
            }

            AdminDaemonClient adClient = new AdminDaemonClient(adminDaemonSP.getBindAddr(),
                    adminDaemonSP.getPort());
            adClient.undeploy(args[1]);
        }
    } catch (java.net.ConnectException ex) {
        LOG.error(AppLocale.getI18n("errorServerNotRunning"));
    } catch (Exception ex) {
        LOG.error(AppLocale.getI18n("errorUnexpectedFailure", new Object[] { ex.getMessage() }));
    }
}

From source file:org.jboss.as.jbossws.jbpapp10625.DuplicateServicesGeneratedWsdlIT.java

public static String readFromUrlToString(final URL url, String encoding)
        throws UnsupportedEncodingException, IOException {
    InputStream stream = null;/* ww w.j  a  v a2 s  .  c o m*/
    InputStreamReader inputStream = null;
    URLConnection connection = null;
    try {
        connection = url.openConnection();
        stream = connection.getInputStream();
        inputStream = new InputStreamReader(stream, encoding);
        return IOUtils.toString(inputStream);
    } catch (ConnectException e) {
        throw new IllegalStateException("Can not read from " + url.toString() + " " + e.getMessage(), e);
    } catch (IOException e) {
        throw new IllegalStateException("Error reading from " + url.toString() + " " + e.getMessage(), e);
    } finally {
        IOUtils.close(connection); //has to be closed first, otherwise the connection is pooled and reused !!!!
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(stream);
    }
}

From source file:cz.muni.fi.pa165.creatures.rest.client.services.utils.CRUDServiceHelper.java

/**
 * Helper methods which executes an HTTP {@code method} and writes the
 * output to the standard output (e.g. console). Return codes of the HTTP
 * responses are present so we can verify what happened at the server side.
 *
 * @param method method to send to the server side
 *//*from  w w w .jav a2s.  co m*/
public static void send(HttpMethodBase method) {
    HttpClient httpClient = new HttpClient();
    try {

        int result = httpClient.executeMethod(method);
        System.out.println(RESPONSE_STATUS_CODE + result);
        ResponseCode response = ResponseCode.fromInt(result);
        if (response != ResponseCode.NOT_FOUND && response != ResponseCode.SERVER_ERROR
                && response != ResponseCode.FORBIDDEN) {
            System.out.println(RESPONSE_HEADER);

            Header[] headers = method.getResponseHeaders();
            for (Header h : headers) {
                System.out.println(h.toString());
            }

            InputStreamReader isr = new InputStreamReader(method.getResponseBodyAsStream());
            BufferedReader br = new BufferedReader(isr);

            String line;

            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        }
    } catch (ConnectException ex) {
        logger.log(Level.WARNING, CONNECTION_EXCEPTION_MSG);
    } catch (IOException ex) {
        logger.log(Level.INFO, ex.getMessage());
    } finally {
        method.releaseConnection();
    }
}

From source file:edu.harvard.i2b2.fhir.I2b2Util.java

@Deprecated
public static String getAllDataPDO(String i2b2User, String i2b2Token, String i2b2Url, String I2b2Domain,
        String project, String patientId, List<String> items) throws FhirCoreException {
    try {//from   w w w.ja va 2  s .c o m
        logger.trace("got params:" + i2b2User + "-" + i2b2Token + "-" + i2b2Url + "-" + I2b2Domain + "-"
                + project + "-" + patientId + "-" + items);
        String requestXml = IOUtils.toString(
                I2b2Util.class.getResourceAsStream("/i2b2query/i2b2RequestEmptyFilterForAPatient.xml"));

        String panelXml = "";
        int count = 0;
        for (String item : items) {
            count++;
            String singlePanelXml = IOUtils
                    .toString(I2b2Util.class.getResourceAsStream("/i2b2query/panel.xml"));

            item = StringEscapeUtils.escapeJava(item);
            singlePanelXml = replaceXMLString(singlePanelXml, "//panel/item/item_key", item);
            singlePanelXml = replaceXMLString(singlePanelXml, "//panel/panel_number", Integer.toString(count));
            panelXml += singlePanelXml;
            logger.trace("singlePanelXml:" + singlePanelXml);
        }
        //panelXml=StringEscapeUtils.unescapeXml(panelXml);

        requestXml = requestXml.replaceAll("PANEL", panelXml);

        requestXml = I2b2Util.insertI2b2ParametersInXml(requestXml, i2b2User, i2b2Token, i2b2Url, I2b2Domain,
                project);

        if (patientId != null)
            requestXml = requestXml.replaceAll("PATIENTID", patientId);

        String responseXml = WebServiceCall.run(i2b2Url + "/services/QueryToolService/pdorequest", requestXml);
        logger.trace("got response:" + responseXml);
        logger.trace("" + XQueryUtil.getStringSequence("//observation", responseXml).size());
        return responseXml;
    } catch (java.net.ConnectException e) {
        logger.error(e.getMessage(), e);
        throw new FhirCoreException(e);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
    return null;
}

From source file:org.glite.authz.common.http.JettyAdminServiceCLI.java

/**
 * Executes the service command. Also checks to ensure the HTTP return code was 200.
 * /*from w  w  w.j av a 2  s . co  m*/
 * @param host host to which to connect
 * @param port port to which to connect
 * @param command command sent to the admin service
 * @param password admin command password, may be null
 */
private static void executeCommand(String host, int port, String command, String password) {
    HttpClientBuilder clientBuilder = new HttpClientBuilder();
    HttpClient httpClient = clientBuilder.buildClient();

    GetMethod getMethod = new GetMethod("http://" + host + ":" + port + "/" + command);
    if (password != null) {
        getMethod.setQueryString(new NameValuePair[] {
                new NameValuePair(PasswordProtectFilter.PASSWORD_PARAM_NAME, password), });
    }

    try {
        httpClient.executeMethod(getMethod);
        String response = Strings.safeTrimOrNullString(getMethod.getResponseBodyAsString());
        if (response != null) {
            System.out.println(response);
        }
    } catch (ConnectException e) {
        exit("Unable to connect to " + host + ":" + port + ", perhaps the service is not running", RC_CTX);
    } catch (IOException e) {
        exit("Error executing service command:\n" + e.getMessage(), RC_CTX);
    }

    int statusCode = getMethod.getStatusCode();
    if (statusCode == HttpStatus.SC_OK) {
        return;
    } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
        exit("you are not authorized to execute admin commands; invalid password", RC_UNAUTHORIZED);
    } else {
        exit("Service returned unexpected HTTP status code; " + statusCode, RC_UNKNOWN);
    }
}

From source file:org.apache.zeppelin.interpreter.remote.RemoteInterpreterUtils.java

public static boolean checkIfRemoteEndpointAccessible(String host, int port) {
    try {//from www  .j a v  a2  s  . c  o m
        Socket discover = new Socket();
        discover.setSoTimeout(1000);
        discover.connect(new InetSocketAddress(host, port), 1000);
        discover.close();
        return true;
    } catch (ConnectException cne) {
        // end point is not accessible
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Remote endpoint '" + host + ":" + port + "' is not accessible "
                    + "(might be initializing): " + cne.getMessage());
        }
        return false;
    } catch (IOException ioe) {
        // end point is not accessible
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Remote endpoint '" + host + ":" + port + "' is not accessible "
                    + "(might be initializing): " + ioe.getMessage());
        }
        return false;
    }
}

From source file:org.sipfoundry.openfire.vcard.provider.RestInterface.java

public static String sendRequest(String method, Element vcardElement) throws ConnectException {
    try {/* w w w .  j  a  va 2s .c  o  m*/
        logger.debug("call REST URL " + REST_CALL_URL_CONTACT_INFO);
        URL serverURL = new URL(REST_CALL_URL_CONTACT_INFO);
        HttpURLConnection conn = (HttpURLConnection) serverURL.openConnection();
        conn.setReadTimeout(READ_TIMEOUT);

        conn.setDoOutput(true);
        conn.setRequestMethod(method);

        if (vcardElement != null) {
            conn.setDoInput(true);
            conn.setRequestProperty("Content-type", "text/xml");
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            String vcardXml = RestInterface.buildXMLContactInfo(vcardElement);
            String contactXml = RestInterface.sendRequest(SipXVCardProvider.QUERY_METHOD, null);
            if (contactXml != null) {
                vcardXml = refillMissingContactInfo(vcardXml, contactXml);
            }

            wr.write(vcardXml);

            wr.flush();
            wr.close();
        }

        conn.connect();

        logger.debug(
                "response code " + conn.getResponseCode() + " response message " + conn.getResponseMessage());

        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder resp = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            resp.append(line);
        }
        rd.close();

        if (conn.getResponseCode() >= 200 && conn.getResponseCode() < 300) {
            return resp.toString();
        } else {
            logger.error("Response code " + conn.getResponseCode() + ":" + conn.getResponseMessage() + " "
                    + resp.toString());
            return null;
        }
    }

    catch (ConnectException ex) {
        logger.error("In sendRequest ConnectException " + ex.getMessage());
        throw ex;
    }

    catch (IOException ex) {
        logger.error("In sendRequest IOException " + ex.getMessage());
        return null;
    }

    catch (Exception ex) {
        logger.error("Exception " + ex.getMessage());
        return null;
    }
}

From source file:org.bibsonomy.util.WebUtils.java

/**
 * Reads from a URL and writes the content into a string.
 * //from   w w w.  j  a va 2 s .co m
 * @param inputURL the URL of the content.
 * @param cookie a cookie which should be included in the header of the request send to the server
 * @return String which holds the page content.
 * @throws IOException 
 * 
 * @Deprecated
 */
public static String getContentAsString(final URL inputURL, final String cookie) throws IOException {
    try {
        final HttpURLConnection urlConn = (HttpURLConnection) inputURL.openConnection();
        urlConn.setAllowUserInteraction(false);
        urlConn.setDoInput(true);
        urlConn.setDoOutput(false);
        urlConn.setUseCaches(false);

        /*
         * set user agent (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html) since some 
         * pages require it to download content.
         */
        urlConn.setRequestProperty(USER_AGENT_HEADER_NAME, USER_AGENT_PROPERTY_VALUE);
        if (cookie != null) {
            urlConn.setRequestProperty(COOKIE_HEADER_NAME, cookie);
        }
        urlConn.connect();

        /*
         * extract character encoding from header
         */
        final String charSet = getCharset(urlConn);

        /*
         * FIXME: check content type header to ensure that we only read textual 
         * content (and not a PDF, radio stream or DVD image ...)
         */

        /*
         * write content into string buffer
         */
        final StringBuilder out = inputStreamToStringBuilder(urlConn.getInputStream(), charSet);

        urlConn.disconnect();

        return out.toString();
    } catch (final ConnectException cex) {
        log.debug("Could not get content for URL " + inputURL.toString() + " : " + cex.getMessage());
        throw new IOException(cex);
    } catch (final IOException ioe) {
        log.debug("Could not get content for URL " + inputURL.toString() + " : " + ioe.getMessage());
        throw ioe;
    }
}

From source file:org.apache.camel.component.http4.HttpNoConnectionTest.java

@Test
public void httpConnectionNotOk() throws Exception {
    String url = "http4://" + getHostName() + ":" + getPort() + "/search";
    // stop server so there are no connection
    localServer.stop();//from www.j a v a 2 s .com
    localServer.awaitTermination(1000);

    Exchange reply = template.request(url, null);
    Exception e = reply.getException();
    assertNotNull("Should have thrown an exception", e);
    ConnectException cause = assertIsInstanceOf(ConnectException.class, e);
    assertTrue(cause.getMessage().contains("refused"));
}