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.intel.iotkitlib.LibHttp.HttpPostTask.java

private CloudResponse doWork(HttpClient httpClient, String url) {
    try {/*  w w w .ja  va  2 s . c  o m*/
        HttpContext localContext = new BasicHttpContext();
        HttpPost httpPost = new HttpPost(url);

        if (httpBody != null) {
            //setting HTTP body in entity
            StringEntity bodyEntity = new StringEntity(httpBody, "UTF-8");
            httpPost.setEntity(bodyEntity);
        }

        //adding headers one by one
        for (NameValuePair nvp : headerList) {
            httpPost.addHeader(nvp.getName(), nvp.getValue());
        }

        if (debug) {
            Log.e(TAG, "URI is : " + httpPost.getURI());
            Header[] headers = httpPost.getAllHeaders();
            for (int i = 0; i < headers.length; i++) {
                Log.e(TAG, "Header " + i + " is :" + headers[i].getName() + ":" + headers[i].getValue());
            }
            if (httpBody != null) {
                BufferedReader reader123 = new BufferedReader(
                        new InputStreamReader(httpPost.getEntity().getContent(), HTTP.UTF_8));
                StringBuilder builder123 = new StringBuilder();
                for (String line = null; (line = reader123.readLine()) != null;) {
                    builder123.append(line).append("\n");
                }
                Log.e(TAG, "Body is :" + builder123.toString());
            }
        }

        HttpResponse response = httpClient.execute(httpPost, localContext);
        if (response != null && response.getStatusLine() != null) {
            if (debug)
                Log.d(TAG, "response: " + response.getStatusLine().getStatusCode());
        }
        HttpEntity responseEntity = response != null ? response.getEntity() : null;
        StringBuilder builder = new StringBuilder();
        if (responseEntity != null) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(responseEntity.getContent(), HTTP.UTF_8));
            for (String line = null; (line = reader.readLine()) != null;) {
                builder.append(line).append("\n");
            }
            if (debug)
                Log.d(TAG, "Response received is :" + builder.toString());
        }

        CloudResponse cloudResponse = new CloudResponse();
        if (response != null) {
            cloudResponse.code = response.getStatusLine().getStatusCode();
        }
        cloudResponse.response = builder.toString();
        return cloudResponse;
    } catch (java.net.ConnectException cEx) {
        Log.e(TAG, cEx.getMessage());
        return null;
    } catch (Exception e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
        return null;
    }
}

From source file:com.intel.iotkitlib.LibHttp.HttpPutTask.java

private CloudResponse doWork(HttpClient httpClient, String url) {
    try {/*from   ww  w .j a  v a  2 s  .  c o  m*/
        HttpContext localContext = new BasicHttpContext();
        HttpPut httpPut = new HttpPut(url);

        if (httpBody != null) {
            //setting HTTP body in entity
            StringEntity bodyEntity = new StringEntity(httpBody, "UTF-8");
            httpPut.setEntity(bodyEntity);
        }

        //adding headers one by one
        for (NameValuePair nvp : headerList) {
            httpPut.addHeader(nvp.getName(), nvp.getValue());
        }

        if (debug) {
            Log.e(TAG, "URI is : " + httpPut.getURI());
            Header[] headers = httpPut.getAllHeaders();
            for (int i = 0; i < headers.length; i++) {
                Log.e(TAG, "Header " + i + " is :" + headers[i].getName() + ":" + headers[i].getValue());
            }
            if (httpBody != null) {
                BufferedReader reader123 = new BufferedReader(
                        new InputStreamReader(httpPut.getEntity().getContent(), HTTP.UTF_8));
                StringBuilder builder123 = new StringBuilder();
                for (String line = null; (line = reader123.readLine()) != null;) {
                    builder123.append(line).append("\n");
                }
                Log.e(TAG, "Body is :" + builder123.toString());
            }
        }

        HttpResponse response = httpClient.execute(httpPut, localContext);
        if (response != null && response.getStatusLine() != null) {
            if (debug)
                Log.d(TAG, "response: " + response.getStatusLine().getStatusCode());
        }

        HttpEntity responseEntity = response != null ? response.getEntity() : null;
        StringBuilder builder = new StringBuilder();
        if (responseEntity != null) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(responseEntity.getContent(), HTTP.UTF_8));
            for (String line = null; (line = reader.readLine()) != null;) {
                builder.append(line).append("\n");
            }
            if (debug)
                Log.d(TAG, "Response received is :" + builder.toString());
        }

        CloudResponse cloudResponse = new CloudResponse();
        if (response != null) {
            cloudResponse.code = response.getStatusLine().getStatusCode();
        }
        cloudResponse.response = builder.toString();
        return cloudResponse;
    } catch (java.net.ConnectException cEx) {
        Log.e(TAG, cEx.getMessage());
        return null;
    } catch (Exception e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
        return null;
    }
}

From source file:com.intel.iotkitlib.http.HttpPostTask.java

public CloudResponse doSync(final String url) {
    HttpClient httpClient = new DefaultHttpClient();
    try {/*from   www  .  ja v a2s  .co m*/
        HttpContext localContext = new BasicHttpContext();
        HttpPost httpPost = new HttpPost(url);

        if (httpBody != null) {
            //setting HTTP body in entity
            StringEntity bodyEntity = new StringEntity(httpBody, "UTF-8");
            httpPost.setEntity(bodyEntity);
        }

        //adding headers one by one
        for (NameValuePair nvp : headerList) {
            httpPost.addHeader(nvp.getName(), nvp.getValue());
        }

        if (debug) {
            Log.e(TAG, "URI is : " + httpPost.getURI());
            Header[] headers = httpPost.getAllHeaders();
            for (int i = 0; i < headers.length; i++) {
                Log.e(TAG, "Header " + i + " is :" + headers[i].getName() + ":" + headers[i].getValue());
            }
            if (httpBody != null) {
                BufferedReader reader123 = new BufferedReader(
                        new InputStreamReader(httpPost.getEntity().getContent(), HTTP.UTF_8));
                StringBuilder builder123 = new StringBuilder();
                for (String line = null; (line = reader123.readLine()) != null;) {
                    builder123.append(line).append("\n");
                }
                Log.e(TAG, "Body is :" + builder123.toString());
            }
        }

        HttpResponse response = httpClient.execute(httpPost, localContext);
        if (response != null && response.getStatusLine() != null) {
            if (debug)
                Log.d(TAG, "response: " + response.getStatusLine().getStatusCode());
        }
        HttpEntity responseEntity = response != null ? response.getEntity() : null;
        StringBuilder builder = new StringBuilder();
        if (responseEntity != null) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(responseEntity.getContent(), HTTP.UTF_8));
            for (String line = null; (line = reader.readLine()) != null;) {
                builder.append(line).append("\n");
            }
            if (debug)
                Log.d(TAG, "Response received is :" + builder.toString());
        }

        CloudResponse cloudResponse = new CloudResponse();
        if (response != null) {
            cloudResponse.code = response.getStatusLine().getStatusCode();
        }
        cloudResponse.response = builder.toString();
        return cloudResponse;
    } catch (java.net.ConnectException cEx) {
        Log.e(TAG, cEx.getMessage());
        return new CloudResponse(false, cEx.getMessage());
    } catch (Exception e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
        return new CloudResponse(false, e.getMessage());
    }
}

From source file:uk.dsxt.voting.common.registries.RegistriesServerWeb.java

private <T> T execute(String name, String url, Class<T> clazz) {
    try {// w w  w .  j a v  a2 s  .c  o m
        while (!Thread.currentThread().isInterrupted()) {
            try {
                String answer = httpHelper.request(url, RequestType.GET);
                T value = mapper.readValue(answer, clazz);
                if (value != null)
                    return value;
                log.error("{} failed. value is null. url={}", name, url);
            } catch (InternalLogicException e) {
                log.error("{} failed. Logic exception. url={}. Reason: {}", name, url, e.getMessage());
            } catch (ConnectException connEx) {
                log.error("{} failed. Couldn't establish connection. url={}. Reason: {}", name, url,
                        connEx.getMessage());
            } catch (Exception ex) {
                log.error(String.format("%s failed. url=%s", name, url), ex);
            }
            Thread.sleep(1000);
        }
    } catch (InterruptedException e) {
        log.error("{} failed. InterruptedException. url={}", name, url);
    }
    return null;
}

From source file:com.intel.iotkitlib.http.HttpPutTask.java

public CloudResponse doSync(final String url) {
    HttpClient httpClient = new DefaultHttpClient();
    try {//  ww  w  .j a va2s .c  o  m
        HttpContext localContext = new BasicHttpContext();
        HttpPut httpPut = new HttpPut(url);

        if (httpBody != null) {
            //setting HTTP body in entity
            StringEntity bodyEntity = new StringEntity(httpBody, "UTF-8");
            httpPut.setEntity(bodyEntity);
        }

        //adding headers one by one
        for (NameValuePair nvp : headerList) {
            httpPut.addHeader(nvp.getName(), nvp.getValue());
        }

        if (debug) {
            Log.e(TAG, "URI is : " + httpPut.getURI());
            Header[] headers = httpPut.getAllHeaders();
            for (int i = 0; i < headers.length; i++) {
                Log.e(TAG, "Header " + i + " is :" + headers[i].getName() + ":" + headers[i].getValue());
            }
            if (httpBody != null) {
                BufferedReader reader123 = new BufferedReader(
                        new InputStreamReader(httpPut.getEntity().getContent(), HTTP.UTF_8));
                StringBuilder builder123 = new StringBuilder();
                for (String line = null; (line = reader123.readLine()) != null;) {
                    builder123.append(line).append("\n");
                }
                Log.e(TAG, "Body is :" + builder123.toString());
            }
        }

        HttpResponse response = httpClient.execute(httpPut, localContext);
        if (response != null && response.getStatusLine() != null) {
            if (debug)
                Log.d(TAG, "response: " + response.getStatusLine().getStatusCode());
        }

        HttpEntity responseEntity = response != null ? response.getEntity() : null;
        StringBuilder builder = new StringBuilder();
        if (responseEntity != null) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(responseEntity.getContent(), HTTP.UTF_8));
            for (String line = null; (line = reader.readLine()) != null;) {
                builder.append(line).append("\n");
            }
            if (debug)
                Log.d(TAG, "Response received is :" + builder.toString());
        }

        CloudResponse cloudResponse = new CloudResponse();
        if (response != null) {
            cloudResponse.code = response.getStatusLine().getStatusCode();
        }
        cloudResponse.response = builder.toString();
        return cloudResponse;
    } catch (java.net.ConnectException cEx) {
        Log.e(TAG, cEx.getMessage());
        return new CloudResponse(false, cEx.getMessage());
    } catch (Exception e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
        return new CloudResponse(false, e.getMessage());
    }
}

From source file:ubic.gemma.core.loader.protein.biomart.BioMartEnsemblNcbiFetcherTest.java

@Test
public void testGetEnsemblNcibidata() {

    try {//from w ww .  j a  v a 2 s.  c o m
        File ratBiomartFile = biomartEnsemblNcbiFetcher.fetchFileForProteinQuery("rnorvegicus");
        assertNotNull(ratBiomartFile);
        assertTrue(ratBiomartFile.canRead());

    } catch (ConnectException e) {
        BioMartEnsemblNcbiFetcherTest.log.warn("Connection error, skipping test");
    } catch (IOException e) {
        if (e.getMessage().startsWith("Error from BioMart")) {
            BioMartEnsemblNcbiFetcherTest.log.warn(e.getMessage());
        }
    }

}

From source file:uk.trainwatch.util.config.impl.HttpConfiguration.java

private synchronized void loadConfiguration() {
    if (configuration == null) {
        // Don't write uri as is as we may expose security details
        LOG.log(Level.INFO,/*  w  ww.ja v a 2s  . com*/
                () -> "Retrieving config " + uri.getScheme() + "://" + uri.getHost() + uri.getPath());

        try (CloseableHttpClient client = HttpClients.createDefault()) {
            int retry = 0;
            do {
                try {
                    if (retry > 0) {
                        LOG.log(Level.INFO, "Sleeping {0}ms attempt {1}/{2}",
                                new Object[] { RETRY_DELAY, retry, MAX_RETRY });
                        Thread.sleep(RETRY_DELAY);
                    }
                    HttpGet get = new HttpGet(uri);
                    get.setHeader("User-Agent", "Area51 Configuration/1.0");

                    try (CloseableHttpResponse response = client.execute(get)) {
                        switch (response.getStatusLine().getStatusCode()) {
                        case 200:
                        case 304:
                            try (InputStream is = response.getEntity().getContent()) {
                                try (JsonReader r = Json.createReader(new InputStreamReader(is))) {
                                    configuration = new MapConfiguration(
                                            MapBuilder.fromJsonObject(r.readObject()).build());
                                    return;
                                }
                            }

                        default:
                            LOG.log(Level.WARNING, () -> "Error " + uri.getScheme() + "://" + uri.getHost()
                                    + uri.getPath() + " " + response.getStatusLine().getStatusCode());
                        }
                    }
                } catch (ConnectException ex) {
                    if (retry < MAX_RETRY) {
                        LOG.log(Level.WARNING, () -> "Failed " + ex.getMessage());
                    } else {
                        throw ex;
                    }
                } catch (InterruptedException ex) {
                    LOG.log(Level.SEVERE, null, ex);
                }

                retry++;
            } while (retry < MAX_RETRY);
        } catch (IOException ex) {
            throw new UncheckedIOException(ex);
        }

        configuration = EmptyConfiguration.INSTANCE;
    }
}

From source file:com.cws.esolutions.core.utils.NetworkUtils.java

/**
 * Creates an HTTP connection to a provided website and returns the data back
 * to the requestor./*  w w w. ja  v  a 2 s.c o m*/
 *
 * @param hostName - The fully qualified URL for the host desired. MUST be
 *     prefixed with http/https:// as necessary
 * @param methodType - GET or POST, depending on what is necessary
 * @return A object containing the response data
 * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing
 */
public static final synchronized Object executeHttpConnection(final URL hostName, final String methodType)
        throws UtilityException {
    final String methodName = NetworkUtils.CNAME
            + "#executeHttpConnection(final URL hostName, final String methodType) throws UtilityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", hostName);
        DEBUGGER.debug("Value: {}", methodType);
    }

    RequestConfig requestConfig = null;
    CloseableHttpClient httpClient = null;
    CredentialsProvider credsProvider = null;
    CloseableHttpResponse httpResponse = null;

    final HttpClientParams httpParams = new HttpClientParams();
    final HTTPConfig httpConfig = appBean.getConfigData().getHttpConfig();
    final ProxyConfig proxyConfig = appBean.getConfigData().getProxyConfig();

    if (DEBUG) {
        DEBUGGER.debug("HttpClient: {}", httpClient);
        DEBUGGER.debug("HttpClientParams: {}", httpParams);
        DEBUGGER.debug("HTTPConfig: {}", httpConfig);
        DEBUGGER.debug("ProxyConfig: {}", proxyConfig);
    }
    try {
        final URI requestURI = new URIBuilder().setScheme(hostName.getProtocol()).setHost(hostName.getHost())
                .setPort(hostName.getPort()).build();

        if (StringUtils.isNotEmpty(httpConfig.getTrustStoreFile())) {
            System.setProperty("javax.net.ssl.trustStoreType",
                    (StringUtils.isNotEmpty(httpConfig.getTrustStoreType()) ? httpConfig.getTrustStoreType()
                            : "jks"));
            System.setProperty("javax.net.ssl.trustStore", httpConfig.getTrustStoreFile());
            System.setProperty("javax.net.ssl.trustStorePassword",
                    PasswordUtils.decryptText(httpConfig.getTrustStorePass(), httpConfig.getTrustStoreSalt(),
                            secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(),
                            secBean.getConfigData().getSecurityConfig().getIterations(),
                            secBean.getConfigData().getSecurityConfig().getKeyBits(),
                            secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(),
                            secBean.getConfigData().getSecurityConfig().getEncryptionInstance(),
                            appBean.getConfigData().getSystemConfig().getEncoding()));
        }

        if (StringUtils.isNotEmpty(httpConfig.getKeyStoreFile())) {
            System.setProperty("javax.net.ssl.keyStoreType",
                    (StringUtils.isNotEmpty(httpConfig.getKeyStoreType()) ? httpConfig.getKeyStoreType()
                            : "jks"));
            System.setProperty("javax.net.ssl.keyStore", httpConfig.getKeyStoreFile());
            System.setProperty("javax.net.ssl.keyStorePassword",
                    PasswordUtils.decryptText(httpConfig.getKeyStorePass(), httpConfig.getKeyStoreSalt(),
                            secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(),
                            secBean.getConfigData().getSecurityConfig().getIterations(),
                            secBean.getConfigData().getSecurityConfig().getKeyBits(),
                            secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(),
                            secBean.getConfigData().getSecurityConfig().getEncryptionInstance(),
                            appBean.getConfigData().getSystemConfig().getEncoding()));
        }

        if (proxyConfig.isProxyServiceRequired()) {
            if (DEBUG) {
                DEBUGGER.debug("ProxyConfig: {}", proxyConfig);
            }

            if (StringUtils.isEmpty(proxyConfig.getProxyServerName())) {
                throw new UtilityException(
                        "Configuration states proxy usage is required, but no proxy is configured.");
            }

            if (proxyConfig.isProxyAuthRequired()) {
                List<String> authList = new ArrayList<String>();
                authList.add(AuthPolicy.BASIC);
                authList.add(AuthPolicy.DIGEST);
                authList.add(AuthPolicy.NTLM);

                if (DEBUG) {
                    DEBUGGER.debug("authList: {}", authList);
                }

                requestConfig = RequestConfig.custom()
                        .setConnectionRequestTimeout(
                                (int) TimeUnit.SECONDS.toMillis(httpConfig.getConnTimeout()))
                        .setConnectTimeout((int) TimeUnit.SECONDS.toMillis(httpConfig.getConnTimeout()))
                        .setContentCompressionEnabled(Boolean.TRUE)
                        .setProxy(new HttpHost(proxyConfig.getProxyServerName(),
                                proxyConfig.getProxyServerPort()))
                        .setProxyPreferredAuthSchemes(authList).build();

                if (DEBUG) {
                    DEBUGGER.debug("requestConfig: {}", requestConfig);
                }

                String proxyPwd = PasswordUtils.decryptText(proxyConfig.getProxyPassword(),
                        proxyConfig.getProxyPwdSalt(),
                        secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(),
                        secBean.getConfigData().getSecurityConfig().getIterations(),
                        secBean.getConfigData().getSecurityConfig().getKeyBits(),
                        secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(),
                        secBean.getConfigData().getSecurityConfig().getEncryptionInstance(),
                        appBean.getConfigData().getSystemConfig().getEncoding());

                if (DEBUG) {
                    DEBUGGER.debug("proxyPwd: {}", proxyPwd);
                }

                if (StringUtils.equals(NetworkUtils.PROXY_AUTH_TYPE_BASIC, proxyConfig.getProxyAuthType())) {
                    credsProvider = new SystemDefaultCredentialsProvider();
                    credsProvider.setCredentials(
                            new AuthScope(proxyConfig.getProxyServerName(), proxyConfig.getProxyServerPort()),
                            new UsernamePasswordCredentials(proxyConfig.getProxyUserId(), proxyPwd));
                } else if (StringUtils.equals(NetworkUtils.PROXY_AUTH_TYPE_NTLM,
                        proxyConfig.getProxyAuthType())) {
                    credsProvider = new SystemDefaultCredentialsProvider();
                    credsProvider.setCredentials(
                            new AuthScope(proxyConfig.getProxyServerName(), proxyConfig.getProxyServerPort()),
                            new NTCredentials(proxyConfig.getProxyUserId(), proxyPwd,
                                    InetAddress.getLocalHost().getHostName(),
                                    proxyConfig.getProxyAuthDomain()));
                }

                if (DEBUG) {
                    DEBUGGER.debug("httpClient: {}", httpClient);
                }
            }
        }

        synchronized (new Object()) {
            httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();

            if (StringUtils.equalsIgnoreCase(methodType, "POST")) {
                HttpPost httpMethod = new HttpPost(requestURI);
                httpMethod.setConfig(requestConfig);

                httpResponse = httpClient.execute(httpMethod);
            } else {
                HttpGet httpMethod = new HttpGet(requestURI);
                httpMethod.setConfig(requestConfig);

                httpResponse = httpClient.execute(httpMethod);
            }

            int responseCode = httpResponse.getStatusLine().getStatusCode();

            if (DEBUG) {
                DEBUGGER.debug("responseCode: {}", responseCode);
            }

            if (responseCode != 200) {
                ERROR_RECORDER.error("HTTP Response Code received NOT 200: " + responseCode);

                throw new UtilityException("HTTP Response Code received NOT 200: " + responseCode);
            }

            return httpResponse.getEntity().toString();
        }
    } catch (ConnectException cx) {
        throw new UtilityException(cx.getMessage(), cx);
    } catch (UnknownHostException ux) {
        throw new UtilityException(ux.getMessage(), ux);
    } catch (SocketException sx) {
        throw new UtilityException(sx.getMessage(), sx);
    } catch (IOException iox) {
        throw new UtilityException(iox.getMessage(), iox);
    } catch (URISyntaxException usx) {
        throw new UtilityException(usx.getMessage(), usx);
    } finally {
        if (httpResponse != null) {
            try {
                httpResponse.close();
            } catch (IOException iox) {
            } // dont do anything with it
        }
    }
}

From source file:org.oryxeditor.server.ExportServlet.java

protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    res.setContentType("text/html");
    try {// ww  w  .java  2s  .  co m
        if (config == null) {
            config = new PropertiesConfiguration("pnengine.properties");
        }
    } catch (ConfigurationException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    String postVariable = config.getString("pnengine.post_variable");
    String engineURL = config.getString("pnengine.url") + "/petrinets";
    String engineURL_host = config.getString("pnengine.url");
    String modelURL = config.getString("pnengine.default_model_url");
    //      String formURL = null;
    //      String bindingsURL = null;

    String rdf = req.getParameter("data");
    String diagramTitle = req.getParameter("title");

    DocumentBuilder builder;
    BPMNDiagram diagram;
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        builder = factory.newDocumentBuilder();
        Document document = builder.parse(new ByteArrayInputStream(rdf.getBytes()));
        BPMNRDFImporter importer = new BPMNRDFImporter(document);
        diagram = (BPMNDiagram) importer.loadBPMN();

        String basefilename = String.valueOf(System.currentTimeMillis());
        String tmpPNMLFile = this.getServletContext().getRealPath("/") + "tmp" + File.separator + basefilename
                + ".pnml";
        BufferedWriter out1 = new BufferedWriter(new FileWriter(tmpPNMLFile));

        // URL only for testing purposes...
        ExecConverter converter = new ExecConverter(diagram, modelURL,
                this.getServletContext().getRealPath("/"));
        converter.setBaseFileName(
                this.getServletContext().getRealPath("/") + "tmp" + File.separator + basefilename);
        PetriNet net = converter.convert();
        ExecPetriNet execnet = (ExecPetriNet) net;
        Document pnmlDoc = builder.newDocument();

        ExecPNPNMLExporter exp = new ExecPNPNMLExporter();
        execnet.setName(diagramTitle);
        exp.savePetriNet(pnmlDoc, execnet);

        OutputFormat format = new OutputFormat(pnmlDoc);
        XMLSerializer serial = new XMLSerializer(out1, format);
        serial.asDOMSerializer();
        serial.serialize(pnmlDoc.getDocumentElement());
        out1.close();

        StringWriter stringOut = new StringWriter();
        XMLSerializer serial2 = new XMLSerializer(stringOut, format);
        serial2.asDOMSerializer();

        serial2.serialize(pnmlDoc.getDocumentElement());

        URL url_engine = new URL(engineURL);
        HttpURLConnection connection_engine = (HttpURLConnection) url_engine.openConnection();
        connection_engine.setRequestMethod("POST");
        String encoding = new String(Base64.encodeBase64(("testuser:" + ":").getBytes()));
        ;
        connection_engine.setRequestProperty("Authorization", "Basic " + encoding);

        connection_engine.setUseCaches(false);
        connection_engine.setDoInput(true);
        connection_engine.setDoOutput(true);

        String escaped_content = postVariable + "=" + URLEncoder.encode(stringOut.toString(), "UTF-8");

        connection_engine.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection_engine.setRequestProperty("Accept",
                "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");

        // connection_engine.setRequestProperty("Content-Length",
        // ""+escaped_content.getBytes().length);
        String errorMessage = null;
        try {
            connection_engine.getOutputStream().write(escaped_content.getBytes());
            connection_engine.connect();
        } catch (ConnectException e) {
            errorMessage = e.getMessage();
        }

        // output link address
        res.getWriter().print("tmp/" + basefilename + ".pnml" + "\">View PNML</a><br/><br/>");
        if (errorMessage == null && connection_engine.getResponseCode() == 200) {
            res.getWriter().println("Deployment to Engine <a href=\"" + engineURL_host
                    + "/worklist\" target=\"_blank\">" + engineURL_host + "</a><br/><b>successful</b>!");
        } else {
            res.getWriter().println("Deployment to Engine <a href=\"" + engineURL + "\" target=\"_blank\">"
                    + engineURL + "</a><br/><b>failed</b> with message: \n" + errorMessage + "!");
        }

    } catch (ParserConfigurationException e1) {
        res.getWriter().println(e1.getMessage());
    } catch (SAXException e1) {
        res.getWriter().println(e1.getMessage());
    }

}

From source file:com.meidusa.venus.io.network.VenusBIOConnectionFactory.java

public VenusBIOConnection makeObject() throws Exception {
    Socket socket = new Socket();
    InetSocketAddress address = null;
    if (host == null) {
        address = new InetSocketAddress(port);
    } else {/*from  w w w.j a  v  a2 s.c  om*/
        address = new InetSocketAddress(host, port);
    }

    socket.setSendBufferSize(sendBufferSize * 1024);
    socket.setReceiveBufferSize(receiveBufferSize * 1024);
    socket.setTcpNoDelay(tcpNoDelay);
    socket.setKeepAlive(keepAlive);
    try {
        if (soTimeout > 0) {
            socket.setSoTimeout(soTimeout);
        }
        if (coTimeout > 0) {
            socket.connect(address, coTimeout);
        } else {
            socket.connect(address);
        }
    } catch (ConnectException e) {
        throw new ConnectException(e.getMessage() + " " + address.getHostName() + ":" + address.getPort());
    }

    VenusBIOConnection conn = new VenusBIOConnection(socket, TimeUtil.currentTimeMillis());
    byte[] bts = conn.read();
    HandshakePacket handshakePacket = new HandshakePacket();
    handshakePacket.init(bts);

    AuthenPacket authen = getAuthenticator().createAuthenPacket(handshakePacket);
    conn.write(authen.toByteArray());
    bts = conn.read();
    int type = AbstractServicePacket.getType(bts);
    if (type == PacketConstant.PACKET_TYPE_OK) {
        if (authenticatorLogger.isInfoEnabled()) {
            authenticatorLogger.info("authenticated by server=" + host + ":" + port + " success");
        }
    } else if (type == PacketConstant.PACKET_TYPE_ERROR) {
        ErrorPacket error = new ErrorPacket();
        error.init(bts);
        if (authenticatorLogger.isInfoEnabled()) {
            authenticatorLogger.info("authenticated by server=" + host + ":" + port + " error={code="
                    + error.errorCode + ",message=" + error.message + "}");
        }
        throw new AuthenticationException(error.message, error.errorCode);
    }

    return conn;
}