Search in sources :

Example 91 with BindException

use of java.net.BindException in project jmeter by apache.

the class ProxyControlGui method startProxy.

private void startProxy() {
    ValueReplacer replacer = GuiPackage.getInstance().getReplacer();
    modifyTestElement(model);
    TreeNodeWrapper treeNodeWrapper = (TreeNodeWrapper) targetNodesModel.getSelectedItem();
    if (JMeterUtils.getResString("use_recording_controller").equals(treeNodeWrapper.getLabel())) {
        JMeterTreeNode targetNode = model.findTargetControllerNode();
        if (targetNode == null || !(targetNode.getTestElement() instanceof RecordingController)) {
            JOptionPane.showMessageDialog(this, // $NON-NLS-1$
            JMeterUtils.getResString("proxy_cl_wrong_target_cl"), // $NON-NLS-1$
            JMeterUtils.getResString("error_title"), JOptionPane.ERROR_MESSAGE);
            return;
        }
    }
    // Proxy can take some while to start up; show a waiting cursor
    Cursor cursor = getCursor();
    setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    // TODO somehow show progress
    try {
        replacer.replaceValues(model);
        model.startProxy();
        start.setEnabled(false);
        stop.setEnabled(true);
        restart.setEnabled(false);
        if (ProxyControl.isDynamicMode()) {
            String[] details = model.getCertificateDetails();
            StringBuilder sb = new StringBuilder();
            sb.append("<html>");
            // $NON-NLS-1$
            sb.append(JMeterUtils.getResString("proxy_daemon_msg_rootca_cert")).append("&nbsp;<b>").append(KeyToolUtils.ROOT_CACERT_CRT_PFX).append("</b>&nbsp;").append(JMeterUtils.getResString("proxy_daemon_msg_created_in_bin"));
            // $NON-NLS-1$
            sb.append("<br>").append(JMeterUtils.getResString("proxy_daemon_msg_install_as_in_doc"));
            sb.append("<br><b>").append(MessageFormat.format(JMeterUtils.getResString("proxy_daemon_msg_check_expiration"), // $NON-NLS-1$
            new Object[] { ProxyControl.CERT_VALIDITY })).append("</b><br>");
            sb.append("<br>").append(JMeterUtils.getResString("proxy_daemon_msg_check_details")).append(// $NON-NLS-1$
            "<ul>");
            for (String detail : details) {
                sb.append("<li>").append(detail).append("</li>");
            }
            sb.append("</ul>").append("</html>");
            JOptionPane.showMessageDialog(this, sb.toString(), // $NON-NLS-1$
            JMeterUtils.getResString("proxy_daemon_msg_rootca_cert") + SPACE + KeyToolUtils.ROOT_CACERT_CRT_PFX + SPACE + // $NON-NLS-1$
            JMeterUtils.getResString("proxy_daemon_msg_created_in_bin"), JOptionPane.INFORMATION_MESSAGE);
        }
    } catch (InvalidVariableException e) {
        JOptionPane.showMessageDialog(this, // $NON-NLS-1$ $NON-NLS-2$
        JMeterUtils.getResString("invalid_variables") + ": " + e.getMessage(), // $NON-NLS-1$
        JMeterUtils.getResString("error_title"), JOptionPane.ERROR_MESSAGE);
    } catch (BindException e) {
        JOptionPane.showMessageDialog(this, // $NON-NLS-1$ $NON-NLS-2$
        JMeterUtils.getResString("proxy_daemon_bind_error") + ": " + e.getMessage(), // $NON-NLS-1$
        JMeterUtils.getResString("error_title"), JOptionPane.ERROR_MESSAGE);
    } catch (IOException e) {
        JOptionPane.showMessageDialog(this, // $NON-NLS-1$ $NON-NLS-2$
        JMeterUtils.getResString("proxy_daemon_error") + ": " + e.getMessage(), // $NON-NLS-1$
        JMeterUtils.getResString("error_title"), JOptionPane.ERROR_MESSAGE);
    } finally {
        setCursor(cursor);
    }
}
Also used : InvalidVariableException(org.apache.jmeter.functions.InvalidVariableException) TreeNodeWrapper(org.apache.jmeter.control.gui.TreeNodeWrapper) JMeterTreeNode(org.apache.jmeter.gui.tree.JMeterTreeNode) BindException(java.net.BindException) IOException(java.io.IOException) ValueReplacer(org.apache.jmeter.engine.util.ValueReplacer) Cursor(java.awt.Cursor) RecordingController(org.apache.jmeter.protocol.http.control.RecordingController)

Example 92 with BindException

use of java.net.BindException in project karaf by apache.

the class ConnectorServerFactory method init.

public void init() throws Exception {
    if (this.server == null) {
        throw new IllegalArgumentException("server must be set");
    }
    JMXServiceURL url = new JMXServiceURL(this.serviceUrl);
    setupKarafRMIServerSocketFactory();
    if (isClientAuth()) {
        this.secured = true;
    }
    if (this.secured) {
        this.setupSsl();
    }
    if (!AuthenticatorType.PASSWORD.equals(this.authenticatorType)) {
        this.environment.remove("jmx.remote.authenticator");
    }
    MBeanInvocationHandler handler = new MBeanInvocationHandler(server, guard);
    MBeanServer guardedServer = (MBeanServer) Proxy.newProxyInstance(server.getClass().getClassLoader(), new Class[] { MBeanServer.class }, handler);
    this.connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, this.environment, guardedServer);
    if (this.objectName != null) {
        this.server.registerMBean(this.connectorServer, this.objectName);
    }
    try {
        if (this.threaded) {
            Thread connectorThread = new Thread(() -> {
                try {
                    Thread.currentThread().setContextClassLoader(ConnectorServerFactory.class.getClassLoader());
                    connectorServer.start();
                } catch (IOException ex) {
                    if (ex.getCause() instanceof BindException) {
                        // we want just the port message
                        int endIndex = ex.getMessage().indexOf("nested exception is");
                        // check to make sure we do not get an index out of range
                        if (endIndex > ex.getMessage().length() || endIndex < 0) {
                            endIndex = ex.getMessage().length();
                        }
                        throw new RuntimeException("\n" + ex.getMessage().substring(0, endIndex) + "\nYou may have started two containers.  If you need to start a second container or the default ports are already in use " + "update the config file etc/org.apache.karaf.management.cfg and change the Registry Port and Server Port to unused ports");
                    }
                    throw new RuntimeException("Could not start JMX connector server", ex);
                }
            });
            connectorThread.setName("JMX Connector Thread [" + this.serviceUrl + "]");
            connectorThread.setDaemon(this.daemon);
            connectorThread.start();
        } else {
            this.connectorServer.start();
        }
    } catch (Exception ex) {
        doUnregister(this.objectName);
        throw ex;
    }
}
Also used : JMXServiceURL(javax.management.remote.JMXServiceURL) MBeanInvocationHandler(org.apache.karaf.management.internal.MBeanInvocationHandler) JMXConnectorServerFactory(javax.management.remote.JMXConnectorServerFactory) BindException(java.net.BindException) IOException(java.io.IOException) IOException(java.io.IOException) BindException(java.net.BindException) GeneralSecurityException(java.security.GeneralSecurityException) JMException(javax.management.JMException) MBeanServer(javax.management.MBeanServer)

Example 93 with BindException

use of java.net.BindException in project logging-log4j2 by apache.

the class ThrowableProxyTest method testLogStackTraceWithClassThatWillCauseSecurityException.

@Test
public void testLogStackTraceWithClassThatWillCauseSecurityException() throws IOException {
    final SecurityManager sm = System.getSecurityManager();
    try {
        System.setSecurityManager(new SecurityManager() {

            @Override
            public void checkPermission(Permission perm) {
                if (perm instanceof RuntimePermission) {
                    // deny access to the class to trigger the security exception
                    if ("accessClassInPackage.sun.nio.ch".equals(perm.getName())) {
                        throw new SecurityException(perm.toString());
                    }
                }
            }
        });
        ServerSocketChannel.open().socket().bind(new InetSocketAddress("localhost", 9300));
        ServerSocketChannel.open().socket().bind(new InetSocketAddress("localhost", 9300));
        fail("expected a java.net.BindException");
    } catch (final BindException e) {
        new ThrowableProxy(e);
    } finally {
        // restore the security manager
        System.setSecurityManager(sm);
    }
}
Also used : InetSocketAddress(java.net.InetSocketAddress) Permission(java.security.Permission) BindException(java.net.BindException) Test(org.junit.Test)

Example 94 with BindException

use of java.net.BindException in project jmeter by apache.

the class HTTPJavaImpl method sample.

/**
     * Samples the URL passed in and stores the result in
     * <code>HTTPSampleResult</code>, following redirects and downloading
     * page resources as appropriate.
     * <p>
     * When getting a redirect target, redirects are not followed and resources
     * are not downloaded. The caller will take care of this.
     *
     * @param url
     *            URL to sample
     * @param method
     *            HTTP method: GET, POST,...
     * @param areFollowingRedirect
     *            whether we're getting a redirect target
     * @param frameDepth
     *            Depth of this target in the frame structure. Used only to
     *            prevent infinite recursion.
     * @return results of the sampling
     */
@Override
protected HTTPSampleResult sample(URL url, String method, boolean areFollowingRedirect, int frameDepth) {
    HttpURLConnection conn = null;
    String urlStr = url.toString();
    if (log.isDebugEnabled()) {
        log.debug("Start : sample {}, method {}, followingRedirect {}, depth {}", urlStr, method, areFollowingRedirect, frameDepth);
    }
    HTTPSampleResult res = new HTTPSampleResult();
    res.setSampleLabel(urlStr);
    res.setURL(url);
    res.setHTTPMethod(method);
    // Count the retries as well in the time
    res.sampleStart();
    // Check cache for an entry with an Expires header in the future
    final CacheManager cacheManager = getCacheManager();
    if (cacheManager != null && HTTPConstants.GET.equalsIgnoreCase(method)) {
        if (cacheManager.inCache(url)) {
            return updateSampleResultForResourceInCache(res);
        }
    }
    try {
        // Sampling proper - establish the connection and read the response:
        // Repeatedly try to connect:
        int retry = -1;
        // Start with -1 so tries at least once, and retries at most MAX_CONN_RETRIES times
        for (; retry < MAX_CONN_RETRIES; retry++) {
            try {
                conn = setupConnection(url, method, res);
                // Attempt the connection:
                savedConn = conn;
                conn.connect();
                break;
            } catch (BindException e) {
                if (retry >= MAX_CONN_RETRIES) {
                    log.error("Can't connect after {} retries, message: {}", retry, e.toString());
                    throw e;
                }
                log.debug("Bind exception, try again");
                if (conn != null) {
                    // we don't want interrupt to try disconnection again
                    savedConn = null;
                    conn.disconnect();
                }
                setUseKeepAlive(false);
            } catch (IOException e) {
                log.debug("Connection failed, giving up");
                throw e;
            }
        }
        if (retry > MAX_CONN_RETRIES) {
            // This should never happen, but...
            throw new BindException();
        }
        // Nice, we've got a connection. Finish sending the request:
        if (method.equals(HTTPConstants.POST)) {
            String postBody = sendPostData(conn);
            res.setQueryString(postBody);
        } else if (method.equals(HTTPConstants.PUT)) {
            String putBody = sendPutData(conn);
            res.setQueryString(putBody);
        }
        // Request sent. Now get the response:
        byte[] responseData = readResponse(conn, res);
        res.sampleEnd();
        // Done with the sampling proper.
        // Now collect the results into the HTTPSampleResult:
        res.setResponseData(responseData);
        int errorLevel = conn.getResponseCode();
        String respMsg = conn.getResponseMessage();
        String hdr = conn.getHeaderField(0);
        if (hdr == null) {
            // $NON-NLS-1$
            hdr = "(null)";
        }
        if (errorLevel == -1) {
            // Bug 38902 - sometimes -1 seems to be returned unnecessarily
            if (respMsg != null) {
                // Bug 41902 - NPE
                try {
                    errorLevel = Integer.parseInt(respMsg.substring(0, 3));
                    log.warn("ResponseCode==-1; parsed {} as {}", respMsg, errorLevel);
                } catch (NumberFormatException e) {
                    log.warn("ResponseCode==-1; could not parse {} hdr: {}", respMsg, hdr);
                }
            } else {
                // for result
                respMsg = hdr;
                log.warn("ResponseCode==-1 & null ResponseMessage. Header(0)= {} ", hdr);
            }
        }
        if (errorLevel == -1) {
            // $NON-NLS-1$
            res.setResponseCode("(null)");
        } else {
            res.setResponseCode(Integer.toString(errorLevel));
        }
        res.setSuccessful(isSuccessCode(errorLevel));
        if (respMsg == null) {
            // has been seen in a redirect
            // use header (if possible) if no message found
            respMsg = hdr;
        }
        res.setResponseMessage(respMsg);
        String ct = conn.getContentType();
        if (ct != null) {
            // e.g. text/html; charset=ISO-8859-1
            res.setContentType(ct);
            res.setEncodingAndType(ct);
        }
        String responseHeaders = getResponseHeaders(conn);
        res.setResponseHeaders(responseHeaders);
        if (res.isRedirect()) {
            res.setRedirectLocation(conn.getHeaderField(HTTPConstants.HEADER_LOCATION));
        }
        // record headers size to allow HTTPSampleResult.getBytes() with different options
        res.setHeadersSize(// $NON-NLS-1$ $NON-NLS-2$
        responseHeaders.replaceAll("\n", "\r\n").length() + // add 2 for a '\r\n' at end of headers (before data) 
        2);
        if (log.isDebugEnabled()) {
            log.debug("Response headersSize={}, bodySize={}, Total=", res.getHeadersSize(), res.getBodySizeAsLong(), res.getHeadersSize() + res.getBodySizeAsLong());
        }
        // If we redirected automatically, the URL may have changed
        if (getAutoRedirects()) {
            res.setURL(conn.getURL());
        }
        // Store any cookies received in the cookie manager:
        saveConnectionCookies(conn, url, getCookieManager());
        // Save cache information
        if (cacheManager != null) {
            cacheManager.saveDetails(conn, res);
        }
        res = resultProcessing(areFollowingRedirect, frameDepth, res);
        log.debug("End : sample");
        return res;
    } catch (IOException e) {
        res.sampleEnd();
        // we don't want interrupt to try disconnection again
        savedConn = null;
        // We don't want to continue using this connection, even if KeepAlive is set
        if (conn != null) {
            // May not exist
            conn.disconnect();
        }
        // Don't process again
        conn = null;
        return errorResult(e, res);
    } finally {
        // calling disconnect doesn't close the connection immediately,
        // but indicates we're through with it. The JVM should close
        // it when necessary.
        // we don't want interrupt to try disconnection again
        savedConn = null;
        // Disconnect unless using KeepAlive
        disconnect(conn);
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) CacheManager(org.apache.jmeter.protocol.http.control.CacheManager) BindException(java.net.BindException) IOException(java.io.IOException)

Example 95 with BindException

use of java.net.BindException in project aries by apache.

the class TransactionControlRunningTest method testRequiredNoRollbackException.

@Test
public void testRequiredNoRollbackException() {
    AtomicReference<TransactionStatus> finalStatus = new AtomicReference<>();
    Exception userEx = new BindException("Bang!");
    try {
        txControl.build().noRollbackFor(BindException.class).required(() -> {
            assertTrue(txControl.activeTransaction());
            txControl.getCurrentContext().postCompletion(finalStatus::set);
            throw userEx;
        });
        fail("Should not be reached");
    } catch (ScopedWorkException swe) {
        assertSame(userEx, swe.getCause());
    }
    assertEquals(COMMITTED, finalStatus.get());
}
Also used : ScopedWorkException(org.osgi.service.transaction.control.ScopedWorkException) TransactionStatus(org.osgi.service.transaction.control.TransactionStatus) BindException(java.net.BindException) AtomicReference(java.util.concurrent.atomic.AtomicReference) ScopedWorkException(org.osgi.service.transaction.control.ScopedWorkException) BindException(java.net.BindException) Test(org.junit.Test)

Aggregations

BindException (java.net.BindException)104 IOException (java.io.IOException)34 InetSocketAddress (java.net.InetSocketAddress)25 ServerSocket (java.net.ServerSocket)22 Test (org.junit.Test)22 File (java.io.File)12 SocketException (java.net.SocketException)10 Configuration (org.apache.hadoop.conf.Configuration)10 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)6 InterruptedIOException (java.io.InterruptedIOException)5 MiniDFSNNTopology (org.apache.hadoop.hdfs.MiniDFSNNTopology)5 InetAddress (java.net.InetAddress)4 UnknownHostException (java.net.UnknownHostException)4 RemoteException (java.rmi.RemoteException)4 NIOServerCnxnFactory (org.apache.zookeeper.server.NIOServerCnxnFactory)4 ZooKeeperServer (org.apache.zookeeper.server.ZooKeeperServer)4 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)3 Socket (java.net.Socket)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3