Example usage for java.net ConnectException printStackTrace

List of usage examples for java.net ConnectException printStackTrace

Introduction

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

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:org.kepler.actor.rest.RESTService.java

/**
 * File & regular parameters are passed as two separate lists and they are
 * treated little differently. If flPairList is not null or empty then this
 * method uses Part Object else no./*w  w w.j  a  va  2 s.  co m*/
 *
 * @param pmPairList
 *            List of the name and value parameters that user has provided
 * @param flPairList
 *            List of the name and value (full file path)of file parameters.
 *            It is essentially a list of files that user wishes to attach.
 * @return the results after executing the Post service.
 */
public String executePostMethod(List<NameValuePair> pmPairList, List<NameValuePair> flPairList,
        String serSiteURL) throws IllegalActionException {

    if (_debugging) {
        _debug("I AM IN POST METHOD");
    }

    //log.debug("I AM IN POST METHOD");
    String postAddress = serSiteURL;

    HttpClient client = new HttpClient();
    MultipartPostMethod method = new MultipartPostMethod(postAddress);
    List<NameValuePair> fullNameValueList = getCombinedPairList(pmPairList);
    if (flPairList != null && flPairList.size() > 0) {
        fullNameValueList.addAll(flPairList);
        int totalSize = fullNameValueList.size();
        Part[] parts = new Part[totalSize];

        try {

            for (int i = 0; i < parts.length; i++) {

                String nm = fullNameValueList.get(i).getName();
                String vl = fullNameValueList.get(i).getValue();

                if (i > totalSize - flPairList.size() - 1) {
                    System.out.println("FILE NAME: " + nm);
                    File file = getFileObject(vl);
                    // System.out.println("FILE NAME: " + file.getName());
                    parts[i] = new FilePart(nm, file);
                    method.addPart(parts[i]);
                    System.out.println("PARTS: " + i + " " + parts[i].getName());
                    System.out.println("file Name: " + vl);

                } else {

                    System.out.println("PARAMETER NAME: " + nm);
                    System.out.println("PARAMETER Value: " + vl);
                    parts[i] = new StringPart(nm, vl);
                    method.addPart(parts[i]);

                }
                if (_debugging) {
                    _debug("Value of i: " + i);
                }

            }

        } catch (FileNotFoundException fnfe) {
            if (_debugging) {
                _debug("File Not Exception: " + fnfe.getMessage());
            }
            fnfe.printStackTrace();
            throw new IllegalActionException(this, fnfe, "File Not Found: " + fnfe.getMessage());
        }
    } else {
        for (NameValuePair nmPair : fullNameValueList) {
            method.addParameter(nmPair.getName(), nmPair.getValue());
        }
    }

    InputStream rstream = null;
    StringBuilder results = new StringBuilder();
    try {

        messageBldr = new StringBuilder();
        messageBldr.append("In excutePostMethod, communicating with service: ").append(serSiteURL)
                .append("   STATUS Code: ");

        int statusCode = client.executeMethod(method);
        messageBldr.append(statusCode);

        log.debug("DEBUG: " + messageBldr.toString());
        System.out.println(messageBldr.toString());

        // if(statusCode == 201){
        // System.out.println("Succuess -- " + statusCode +
        // ServiceUtils.ANEMPTYSPACE + method.getResponseBodyAsString());
        // }else{
        // System.out.println("Failure -- " + statusCode +
        // ServiceUtils.ANEMPTYSPACE + method.getResponseBodyAsString());
        // }
        rstream = method.getResponseBodyAsStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(rstream));

        log.debug("BEFORE WHILE LOOP");
        String s;
        while ((s = br.readLine()) != null) {
            results.append(s).append(ServiceUtils.LINESEP);
        }

    } catch (HttpException e) {
        if (_debugging) {
            _debug("Fatal protocol violation: " + e.getMessage());
        }
        e.printStackTrace();
        return "Protocol Violation";
    } catch (ConnectException conExp) {
        if (_debugging) {
            _debug("Perhaps service '" + serSiteURL + "' is not reachable: " + conExp.getMessage());
        }
        conExp.printStackTrace();
        throw new IllegalActionException(this, conExp,
                "Perhaps service '" + serSiteURL + "' is not reachable: " + conExp.getMessage());
    } catch (IOException ioe) {
        if (_debugging) {
            _debug("Fatal transport error: " + ioe.getMessage());
        }
        // System.err.println("Fatal transport error: " + e.getMessage());
        ioe.printStackTrace();
        throw new IllegalActionException(this, ioe, "IOException: Perhaps could not"
                + " connect to the service '" + serSiteURL + "'. " + ioe.getMessage());
    } catch (Exception e) {
        if (_debugging) {
            _debug("Error: " + e.getMessage());
        }
        // System.err.println("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
        throw new IllegalActionException(this, e, "Error: " + e.getMessage());
    } finally {
        // Release the connection.
        method.releaseConnection();
        client = null;
        // close InputStream;
        if (rstream != null)
            try {
                rstream.close();
            } catch (IOException e) {
                e.printStackTrace();
                throw new IllegalActionException(this, e, "InputStream Close Exception: " + e.getMessage());
            }
    }
    return results.toString();
}

From source file:org.camera.service.CAMERARESTService.java

/**
 *  /*from  ww w .  j a va 2 s.c o  m*/
 * @param pmPairList List of the name and value parameters that user has provided
 * through paramInputPort. However in  method this list is combined with
 * the user configured ports and the combined list name value pair parameters are
 * added to the service URL separated by ampersand.
 * @param nvPairList List of the name and value parameters that user has provided
 * @return the results after executing the Get service.
 */
public String executeGetMethod(List<NameValuePair> nvPairList, String serSiteURL)
        throws IllegalActionException {

    if (_debugging) {
        _debug("I AM IN GET METHOD");
    }

    HttpClient client = new HttpClient();

    StringBuilder results = new StringBuilder();
    results.append(serSiteURL);
    //Files cannot be attached with GET
    List<NameValuePair> fullPairList = nvPairList;// getCombinedPairList(nvPairList);

    if (fullPairList.size() > 0) {

        results.append("?");

        int pairListSize = fullPairList.size();
        for (int j = 0; j < pairListSize; j++) {
            NameValuePair nvPair = fullPairList.get(j);
            results.append(nvPair.getName()).append(ServiceUtils.EQUALDELIMITER).append(nvPair.getValue());
            if (j < pairListSize - 1) {
                results.append("&");
            }

        }
    }
    if (_debugging) {
        _debug("RESULTS :" + results.toString());
    }

    // Create a method instance.
    GetMethod method = new GetMethod(results.toString());
    InputStream rstream = null;
    StringBuilder resultsForDisplay = new StringBuilder();

    try {

        messageBldr = new StringBuilder();
        messageBldr.append("In excutePostMethod, communicating with service: ").append(serSiteURL)
                .append("   STATUS Code: ");

        int statusCode = client.executeMethod(method);
        messageBldr.append(statusCode);

        log.debug("DEBUG: " + messageBldr.toString());
        System.out.println(messageBldr.toString());

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

        String s;
        while ((s = br.readLine()) != null) {
            resultsForDisplay.append(s).append(ServiceUtils.LINESEP);
        }

    } catch (HttpException httpe) {
        if (_debugging) {
            _debug("Fatal protocol violation: " + httpe.getMessage());
        }
        httpe.printStackTrace();
        //            return "Protocol Violation";
        throw new IllegalActionException("Fatal protocol violation: " + httpe.getMessage());
    } catch (ConnectException conExp) {
        if (_debugging) {
            _debug("Perhaps service not reachable: " + conExp.getMessage());
        }
        conExp.printStackTrace();
        throw new IllegalActionException("Perhaps service not reachable: " + conExp.getMessage());
    } catch (IOException ioe) {
        if (_debugging) {
            _debug("Fatal transport error: " + ioe.getMessage());
        }
        ioe.printStackTrace();
        //            return "IOException: fatal transport error";
        throw new IllegalActionException("Fatal transport error: " + ioe.getMessage());
    } catch (Exception e) {
        if (_debugging) {
            _debug("Unknown error: " + e.getMessage());
        }
        e.printStackTrace();
        //            return "Exception: Unknown type error";
        throw new IllegalActionException("Error: " + e.getMessage());
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    return resultsForDisplay.toString();

}

From source file:org.camera.service.CAMERARESTService.java

/**
 * File & regular parameters are passed as two separate lists and they are treated
 * little differently. If flPairList is not null or empty then this method uses Part
 * Object else no./*  w  ww .  ja  va2s. co  m*/
 * @param pmPairList List of the name and value parameters that user has provided
 * @param flPairList List of the name and value (full file path)of file parameters.
 *          It is essentially a list of files that user wishes to attach.
 * @return  the results after executing the Post service.
 */
public String executePostMethod(List<NameValuePair> pmPairList, List<NameValuePair> flPairList,
        String serSiteURL) throws IllegalActionException {

    if (_debugging) {
        _debug("I AM IN POST METHOD");
    }

    log.debug("I AM IN POST METHOD");
    String postAddress = serSiteURL;

    HttpClient client = new HttpClient();
    MultipartPostMethod method = new MultipartPostMethod(postAddress);
    List<NameValuePair> fullNameValueList = pmPairList;
    if (flPairList != null && flPairList.size() > 0) {
        fullNameValueList.addAll(flPairList);
        int totalSize = fullNameValueList.size();
        Part[] parts = new Part[totalSize];

        try {

            for (int i = 0; i < parts.length; i++) {

                String nm = fullNameValueList.get(i).getName();
                String vl = fullNameValueList.get(i).getValue();

                if (i > totalSize - flPairList.size() - 1) {
                    System.out.println("FILE NAME: " + nm);
                    File file = getFileObject(vl);
                    System.out.println("FILE NAME: " + file.getName());
                    parts[i] = new FilePart(nm, file);
                    method.addPart(parts[i]);
                    System.out.println("PARTS: " + i + " " + parts[i].getName());
                    System.out.println("file Name: " + vl);

                } else {

                    System.out.println("PARAMETER NAME: " + nm);
                    System.out.println("PARAMETER Value: " + vl);
                    parts[i] = new StringPart(nm, vl);
                    method.addPart(parts[i]);

                }
                if (_debugging) {
                    _debug("Value of i: " + i);
                }

            }

        } catch (FileNotFoundException fnfe) {
            if (_debugging) {
                _debug("File Not Found Exception: " + fnfe.getMessage());
            }
            fnfe.printStackTrace();
            throw new IllegalActionException("File Not Found: " + fnfe.getMessage());
        }
    } else {
        for (NameValuePair nmPair : fullNameValueList) {
            method.addParameter(nmPair.getName(), nmPair.getValue());
            System.out.println("Name: " + nmPair.getName() + "  Value:" + nmPair.getValue());
        }
    }

    InputStream rstream = null;
    StringBuilder results = new StringBuilder();
    try {

        messageBldr = new StringBuilder();
        messageBldr.append("In excutePostMethod, communicating with service: ").append(serSiteURL)
                .append("   STATUS Code: ");

        int statusCode = client.executeMethod(method);
        messageBldr.append(statusCode);

        log.debug("DEBUG: " + messageBldr.toString());
        System.out.println(messageBldr.toString());

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

        log.debug("BEFORE WHILE LOOP");
        String s;
        while ((s = br.readLine()) != null) {
            results.append(s).append(ServiceUtils.LINESEP);
        }

    } catch (HttpException httpe) {
        if (_debugging) {
            _debug("Fatal protocol violation: " + httpe.getMessage());
        }
        httpe.printStackTrace();
        //            return "Protocol Violation";
        throw new IllegalActionException("Fatal protocol violation: " + httpe.getMessage());
    } catch (ConnectException conExp) {
        if (_debugging) {
            _debug("Perhaps service not reachable: " + conExp.getMessage());
        }

        conExp.printStackTrace();
        throw new IllegalActionException("Perhaps service not reachable: " + conExp.getMessage());
        //         return "Perhaps service not reachable";
    } catch (IOException ioe) {
        if (_debugging) {
            _debug("Fatal transport error: " + ioe.getMessage());
        }

        ioe.printStackTrace();
        //            return "IOException: Perhaps could not connect to the service.";
        throw new IllegalActionException("Fatal transport error: " + ioe.getMessage());
    } catch (Exception e) {
        if (_debugging) {
            _debug("Unknown error: " + e.getMessage());
        }
        e.printStackTrace();
        //            return "Exception: Unknown type error";
        throw new IllegalActionException("Error: " + e.getMessage());
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return results.toString();
}

From source file:edu.isi.misd.tagfiler.client.JakartaClient.java

/**
 * Execute a HttpUriRequest//from   w  w  w  . jav a 2  s. c  om
 * 
 * @param request
 *            the request to be executed
 * @param cookie
 *            the cookie to be set in the request
 * @return the HTTP Response
 */
private ClientURLResponse execute(HttpUriRequest request, String cookie) {
    setCookie(cookie, request);
    request.setHeader("X-Machine-Generated", "true");
    ClientURLResponse response = null;
    int count = 0;
    while (true) {
        try {
            response = new JakartaClientResponse(httpclient.execute(request));
            break;
        } catch (ConnectException e) {
            // Can not connect and send the request
            // Retry maximum 10 times
            synchronized (this) {
                if (connectException == null || !connectException.equals(e.getMessage())) {
                    System.err.println("ConnectException");
                    e.printStackTrace();
                    connectException = e.getMessage();
                }
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            synchronized (this) {
                if (clientProtocolException == null || !clientProtocolException.equals(e.getMessage())) {
                    System.err.println("ClientProtocolException");
                    e.printStackTrace();
                    clientProtocolException = e.getMessage();
                }
            }
        } catch (IOException e) {
            // The request was sent, but no response; connection might have been broken
            synchronized (this) {
                if (ioException == null || !ioException.equals(e.getMessage())) {
                    System.err.println("IOException");
                    e.printStackTrace();
                    ioException = e.getMessage();
                }
            }
        }
        if (++count > retries) {
            break;
        } else {
            // just in case
            if (response != null) {
                response.release();
            }
            // sleep before retrying
            int delay = (int) Math.ceil((0.75 + Math.random() * 0.5) * Math.pow(10, count) * 0.00001);
            System.out.println("Retry delay: " + delay + " ms.");
            try {
                Thread.sleep(delay);
            } catch (InterruptedException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
    }

    return response;
}

From source file:org.ejbca.core.protocol.cmp.CmpTestCase.java

/**
 * /*from www.  j av  a 2 s .co m*/
 * @param message
 * @param type set to 5 when sending a PKI request, 3 when sending a PKIConf
 * @return
 * @throws IOException
 * @throws NoSuchProviderException
 */
protected byte[] sendCmpTcp(byte[] message, int type) throws IOException, NoSuchProviderException {
    final String host = getProperty("tcpCmpProxyIP", this.CMP_HOST);
    final int port = getProperty("tcpCmpProxyPort", PORT_NUMBER);
    try {
        final Socket socket = new Socket(host, port);

        final byte[] msg = createTcpMessage(message);
        try {
            final BufferedOutputStream os = new BufferedOutputStream(socket.getOutputStream());
            os.write(msg);
            os.flush();

            DataInputStream dis = new DataInputStream(socket.getInputStream());

            // Read the length, 32 bits
            final int len = dis.readInt();
            log.info("Got a message claiming to be of length: " + len);
            // Read the version, 8 bits. Version should be 10 (protocol draft nr
            // 5)
            final int ver = dis.readByte();
            log.info("Got a message with version: " + ver);
            assertEquals(ver, 10);

            // Read flags, 8 bits for version 10
            final byte flags = dis.readByte();
            log.info("Got a message with flags (1 means close): " + flags);
            // Check if the client wants us to close the connection (LSB is 1 in
            // that case according to spec)

            // Read message type, 8 bits
            final int msgType = dis.readByte();
            log.info("Got a message of type: " + msgType);
            assertEquals(msgType, type);

            // Read message
            final ByteArrayOutputStream baos = new ByteArrayOutputStream(3072);
            while (dis.available() > 0) {
                baos.write(dis.read());
            }

            log.info("Read " + baos.size() + " bytes");
            final byte[] respBytes = baos.toByteArray();
            assertNotNull(respBytes);
            assertTrue(respBytes.length > 0);
            return respBytes;
        } finally {
            socket.close();
        }
    } catch (ConnectException e) {
        assertTrue("This test requires a CMP TCP listener to be configured on " + host + ":" + port
                + ". Edit conf/cmptcp.properties and redeploy.", false);
    } catch (EOFException e) {
        assertTrue("Response was malformed.", false);
    } catch (Exception e) {
        e.printStackTrace();
        assertTrue(false);
    }
    return null;
}

From source file:com.topsec.tsm.sim.sysconfig.web.SystemConfigController.java

@RequestMapping("/superiorConfigRegist")
@ResponseBody/*from w w w  . j a v  a 2s .c  o  m*/
public Object superiorConfigRegist(SID sid, HttpServletRequest request) throws Exception {
    Result result = new Result(true, "??");
    String operator = request.getParameter("operator");
    String registIp = request.getParameter("registIp");
    String registName = request.getParameter("registName");
    String param = "";
    if (registIp.equals(IpAddress.getLocalIp().toString())) {
        result = new Result(false, "???");
        return result;
    }
    if (StringUtils.containsAny(registName, "<>'*?:/|\"\\")) {
        return result.buildError("?????");
    }
    Node parentNode = nodeMgrFacade.getParentNode();
    Node KernelNode = nodeMgrFacade.getKernelAuditor(false);
    try {
        if ("regist".equals(operator)) {
            if (parentNode != null) {
                return result.buildError("??");
            } else {
                //??
                param = "<Register>" + "<Ip>" + IpAddress.getLocalIp() + "</Ip>" + //?IP
                        "<Alias>" + registName + "</Alias>" + "<NodeId>" + KernelNode.getNodeId() + "</NodeId>"
                        + "<Type>register</Type>" + "</Register>";
            }
        } else if ("delete".equals(operator)) {
            if (parentNode == null) {
                return result.buildError("??");
            }
            param = "<Register>" + "<Ip>" + IpAddress.getLocalIp() + "</Ip>" + "<Type>delete</Type>"
                    + "</Register>";
        } else if ("update".equals(operator)) {
            if (parentNode == null) {
                return result.buildError("??");
            }
            try {
                nodeMgrFacade.delNode(parentNode);
                param = "<Register>" + "<Ip>" + IpAddress.getLocalIp() + "</Ip>" + "<Type>delete</Type>"
                        + "</Register>";
                String url = "https://" + parentNode.getIp() + "/resteasy/node/register";
                Map<String, String> cookies = new HashMap<String, String>();
                cookies.put("sessionid", RestUtil.getSessionId(registIp));
                String returnInfo = HttpUtil.doPostWithSSLByString(url, param, cookies, "UTF-8");
                if (StringUtils.isNotBlank(returnInfo)) {
                    log.info("?IP:" + parentNode.getIp());
                }
            } catch (ConnectException e) {
                log.warn("{}????", parentNode.getIp());
            }

            //?
            //            registNode(registIp, registName,KernelNode);
            param = "<Register>" + "<Ip>" + IpAddress.getLocalIp() + "</Ip>" + //?IP
                    "<Alias>" + registName + "</Alias>" + "<NodeId>" + KernelNode.getNodeId() + "</NodeId>"
                    + "<Type>register</Type>" + "</Register>";
        }
        String url = "https://" + registIp + "/resteasy/node/register";
        Map<String, String> cookies = new HashMap<String, String>();
        cookies.put("sessionid", RestUtil.getSessionId(registIp));
        String returnInfo = HttpUtil.doPostWithSSLByString(url, param, cookies, "UTF-8");
        if (StringUtils.isNotBlank(returnInfo)) {
            Document document = DocumentHelper.parseText(returnInfo);
            Element root = document.getRootElement();
            String successResponse = root.attribute("success").getValue();
            if ("false".equals(successResponse)) {
                Element elementMessage = root.element("Message");
                result.buildError(elementMessage.getText());
                return result;
            }
            if ("regist".equals(operator)) {
                //
                registNode(registIp, registName, KernelNode);
                log.info("?IP:" + registIp);
                result = new Result(true, "?");
                result.setResult(KernelNode.getResourceId());
            } else if ("update".equals(operator)) {
                registNode(registIp, registName, KernelNode);
                log.info("??IP:" + registIp);
                result = new Result(true, "??");
                result.setResult(KernelNode.getResourceId());
            } else {
                //
                nodeMgrFacade.delNode(parentNode);
                log.info("?IP:" + parentNode.getIp());
                result = new Result(true, "?");
            }
        } else {
            result.buildError("?");
        }
    } catch (Exception e) {
        e.printStackTrace();
        result.buildError("?");
    }
    return result;
}