Example usage for java.net InetSocketAddress getHostName

List of usage examples for java.net InetSocketAddress getHostName

Introduction

In this page you can find the example usage for java.net InetSocketAddress getHostName.

Prototype

public final String getHostName() 

Source Link

Document

Gets the hostname .

Usage

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 {/*w  w  w.ja v  a  2  s . com*/
        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;
}

From source file:org.apache.hadoop.corona.ClusterManager.java

/**
 * Construct ClusterManager given {@link CoronaConf}
 *
 * @param conf the configuration for the ClusterManager
 * @param recoverFromDisk true if we are restarting after going down while
 *                        in Safe Mode/*  w  ww. j a v  a2  s  .  c om*/
 * @throws IOException
 */
public ClusterManager(CoronaConf conf, boolean recoverFromDisk) throws IOException {
    this.conf = conf;
    HostsFileReader hostsReader = new HostsFileReader(conf.getHostsFile(), conf.getExcludesFile());
    initLegalTypes();
    metrics = new ClusterManagerMetrics(getTypes());

    if (recoverFromDisk) {
        recoverClusterManagerFromDisk(hostsReader);
    } else {
        File stateFile = new File(conf.getCMStateFile());
        if (stateFile.exists()) {
            throw new IOException("State file " + stateFile.getAbsolutePath()
                    + " exists, but recoverFromDisk is not set, delete the state file first");
        }
        LOG.info("Starting Cluster Manager with clean state");
        startTime = clock.getTime();
        lastRestartTime = startTime;
        nodeManager = new NodeManager(this, hostsReader);
        nodeManager.setConf(conf);
        sessionManager = new SessionManager(this);
        sessionNotifier = new SessionNotifier(sessionManager, this, metrics);
    }
    sessionManager.setConf(conf);
    sessionNotifier.setConf(conf);

    sessionHistoryManager = new SessionHistoryManager();
    sessionHistoryManager.setConf(conf);

    scheduler = new Scheduler(nodeManager, sessionManager, sessionNotifier, getTypes(), metrics, conf);
    scheduler.start();
    metrics.registerUpdater(scheduler, sessionNotifier);

    InetSocketAddress infoSocAddr = NetUtils.createSocketAddr(conf.getClusterManagerHttpAddress());
    infoServer = new HttpServer("cm", infoSocAddr.getHostName(), infoSocAddr.getPort(),
            infoSocAddr.getPort() == 0, conf);
    infoServer.setAttribute("cm", this);
    infoServer.start();

    hostName = infoSocAddr.getHostName();

    // We have not completely restored the nodeManager, sessionManager and the
    // sessionNotifier
    if (recoverFromDisk) {
        nodeManager.restoreAfterSafeModeRestart();
        sessionManager.restoreAfterSafeModeRestart();
        sessionNotifier.restoreAfterSafeModeRestart();
    }

    nodeRestarter = new CoronaNodeRestarter(conf, nodeManager);
    nodeRestarter.start();

    setSafeMode(false);
}

From source file:org.apache.hadoop.mapred.buffer.Manager.java

public void open() throws IOException {
    Configuration conf = tracker.conf();
    int maxMaps = conf.getInt("mapred.tasktracker.map.tasks.maximum", 2);
    int maxReduces = conf.getInt("mapred.tasktracker.reduce.tasks.maximum", 1);

    InetSocketAddress serverAddress = getServerAddress(conf);
    this.server = RPC.getServer(this, serverAddress.getHostName(), serverAddress.getPort(),
            maxMaps + maxReduces, false, conf);
    this.server.start();

    this.requestTransfer.setPriority(Thread.MAX_PRIORITY);
    this.requestTransfer.start();

    /** The server socket and selector registration */
    InetSocketAddress controlAddress = getControlAddress(conf);
    this.controlPort = controlAddress.getPort();
    this.channel = ServerSocketChannel.open();
    this.channel.socket().bind(controlAddress);

    this.acceptor = new Thread() {
        @Override/*from  w ww. ja  v a 2s.  c  o  m*/
        public void run() {
            while (!isInterrupted()) {
                SocketChannel connection = null;
                try {
                    connection = channel.accept();
                    DataInputStream in = new DataInputStream(connection.socket().getInputStream());
                    int numRequests = in.readInt();
                    for (int i = 0; i < numRequests; i++) {
                        BufferRequest request = BufferRequest.read(in);
                        if (request instanceof ReduceBufferRequest) {
                            add((ReduceBufferRequest) request);
                            LOG.info("add new request " + request);
                        } else if (request instanceof MapBufferRequest) {
                            add((MapBufferRequest) request);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (connection != null)
                            connection.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
    };
    this.acceptor.setDaemon(true);
    this.acceptor.setPriority(Thread.MAX_PRIORITY);
    this.acceptor.start();

    this.serviceQueue = new Thread() {
        public void run() {
            List<OutputFile> service = new ArrayList<OutputFile>();
            while (!isInterrupted()) {
                try {
                    OutputFile o = queue.take();
                    service.add(o);
                    queue.drainTo(service);
                    for (OutputFile file : service) {
                        try {
                            if (file != null)
                                add(file);
                        } catch (Throwable t) {
                            t.printStackTrace();
                            LOG.error("Error service file: " + file + ". " + t);
                        }
                    }
                } catch (Throwable t) {
                    t.printStackTrace();
                    LOG.error(t);
                } finally {
                    service.clear();
                }
            }
            LOG.info("Service queue thread exit.");
        }
    };
    this.serviceQueue.setPriority(Thread.MAX_PRIORITY);
    this.serviceQueue.setDaemon(true);
    this.serviceQueue.start();
}

From source file:org.red5.server.undertow.UndertowLoader.java

/**
 * Initialization.// www.j  a  v a  2  s. c  om
 */
public void start() {
    log.info("Loading undertow context");
    //get a reference to the current threads classloader
    final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
    // root location for servlet container
    String serverRoot = System.getProperty("red5.root");
    log.info("Server root: {}", serverRoot);
    String confRoot = System.getProperty("red5.config_root");
    log.info("Config root: {}", confRoot);
    if (webappFolder == null) {
        // Use default webapps directory
        webappFolder = FileUtil.formatPath(System.getProperty("red5.root"), "/webapps");
    }
    System.setProperty("red5.webapp.root", webappFolder);
    log.info("Application root: {}", webappFolder);
    // scan the sub directories to determine our context paths
    buildContextPathList(webappFolder);
    try {
        // create our servlet container
        container = ServletContainer.Factory.newInstance();
        // create a root path handler
        final PathHandler rootHandler = new PathHandler();
        // create one server and use it everywhere
        Undertow.Builder builder = Undertow.builder();
        // loop through connectors adding listeners to the builder
        for (UndertowConnector undertowConnector : connectors) {
            InetSocketAddress addr = undertowConnector.getSocketAddress();
            builder.addListener(addr.getPort(), addr.getHostName(),
                    (undertowConnector.isSecure() ? ListenerType.HTTPS : ListenerType.HTTP));
        }
        log.trace("Classloader for undertow: {} TCL: {}", Undertow.class.getClassLoader(), originalClassLoader);
        // create references for later lookup
        LoaderBase.setApplicationLoader(new UndertowApplicationLoader(container, applicationContext));
        // loop the other contexts
        for (String contextPath : contextPaths) {
            // create a class loader for the context
            ClassLoader classLoader = buildWebClassLoader(originalClassLoader, webappFolder, contextPath);
            // create deployment info
            DeploymentInfo info = deployment().setClassLoader(classLoader)
                    .setContextPath(contextPath.equalsIgnoreCase("/ROOT") ? "/" : contextPath)
                    .setDefaultEncoding("UTF-8").setDeploymentName(contextPath.substring(1) + ".war")
                    .setUrlEncoding("UTF-8");
            // parse the web.xml and configure the context
            parseWebXml(webappFolder, contextPath, info);
            if (log.isDebugEnabled()) {
                log.debug("Deployment info - name: {} servlets: {} filters: {}", new Object[] {
                        info.getDisplayName(), info.getServlets().size(), info.getFilters().size() });
            }
            // add the new deployment to the servlet container
            DeploymentManager manager = container.addDeployment(info);
            // set a reference to the manager and deploy the context
            LoaderBase.setRed5ApplicationContext(contextPath, new UndertowApplicationContext(manager));
            // deploy
            manager.deploy();
            // add path
            rootHandler.addPrefixPath(info.getContextPath(), manager.start());
            // get deployment
            Deployment deployment = manager.getDeployment();
            // get servlet context
            final ServletContext servletContext = deployment.getServletContext();
            log.debug("Context initialized: {}", servletContext.getContextPath());
            try {
                log.debug("Context: {}", servletContext);
                final ClassLoader webClassLoader = info.getClassLoader();
                log.debug("Webapp classloader: {}", webClassLoader);
                // get the (spring) config file path
                final String contextConfigLocation = servletContext.getInitParameter(
                        org.springframework.web.context.ContextLoader.CONFIG_LOCATION_PARAM) == null
                                ? defaultSpringConfigLocation
                                : servletContext.getInitParameter(
                                        org.springframework.web.context.ContextLoader.CONFIG_LOCATION_PARAM);
                log.debug("Spring context config location: {}", contextConfigLocation);
                // get the (spring) parent context key
                final String parentContextKey = servletContext.getInitParameter(
                        org.springframework.web.context.ContextLoader.LOCATOR_FACTORY_KEY_PARAM) == null
                                ? defaultParentContextKey
                                : servletContext.getInitParameter(
                                        org.springframework.web.context.ContextLoader.LOCATOR_FACTORY_KEY_PARAM);
                log.debug("Spring parent context key: {}", parentContextKey);
                // set current threads classloader to the webapp classloader
                Thread.currentThread().setContextClassLoader(webClassLoader);
                // create a thread to speed-up application loading
                Thread thread = new Thread("Launcher:" + servletContext.getContextPath()) {
                    public void run() {
                        //set thread context classloader to web classloader
                        Thread.currentThread().setContextClassLoader(webClassLoader);
                        //get the web app's parent context
                        ApplicationContext parentContext = null;
                        if (applicationContext.containsBean(parentContextKey)) {
                            parentContext = (ApplicationContext) applicationContext.getBean(parentContextKey);
                        } else {
                            log.warn("Parent context was not found: {}", parentContextKey);
                        }
                        // create a spring web application context
                        final String contextClass = servletContext.getInitParameter(
                                org.springframework.web.context.ContextLoader.CONTEXT_CLASS_PARAM) == null
                                        ? XmlWebApplicationContext.class.getName()
                                        : servletContext.getInitParameter(
                                                org.springframework.web.context.ContextLoader.CONTEXT_CLASS_PARAM);
                        // web app context (spring)
                        ConfigurableWebApplicationContext appctx = null;
                        try {
                            Class<?> clazz = Class.forName(contextClass, true, webClassLoader);
                            appctx = (ConfigurableWebApplicationContext) clazz.newInstance();
                            // set the root webapp ctx attr on the each servlet context so spring can find it later
                            servletContext.setAttribute(
                                    WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appctx);
                            appctx.setConfigLocations(new String[] { contextConfigLocation });
                            appctx.setServletContext(servletContext);
                            // set parent context or use current app context
                            if (parentContext != null) {
                                appctx.setParent(parentContext);
                            } else {
                                appctx.setParent(applicationContext);
                            }
                            // refresh the factory
                            log.trace("Classloader prior to refresh: {}", appctx.getClassLoader());
                            appctx.refresh();
                            if (log.isDebugEnabled()) {
                                log.debug("Red5 app is active: {} running: {}", appctx.isActive(),
                                        appctx.isRunning());
                            }
                            appctx.start();
                        } catch (Throwable e) {
                            throw new RuntimeException("Failed to load webapplication context class", e);
                        }
                    }
                };
                thread.setDaemon(true);
                thread.start();
            } catch (Throwable t) {
                log.error("Error setting up context: {} due to: {}", servletContext.getContextPath(),
                        t.getMessage());
                t.printStackTrace();
            } finally {
                //reset the classloader
                Thread.currentThread().setContextClassLoader(originalClassLoader);
            }
        }
        // Dump deployments list
        if (log.isDebugEnabled()) {
            for (String deployment : container.listDeployments()) {
                log.debug("Container deployment: {}", deployment);
            }
        }
        // if everything is ok at this point then call the rtmpt and rtmps beans so they will init
        //         if (applicationContext.containsBean("rtmpt.server")) {
        //            log.debug("Initializing RTMPT");
        //            applicationContext.getBean("rtmpt.server");
        //            log.debug("Finished initializing RTMPT");
        //         } else {
        //            log.info("Dedicated RTMPT server configuration was not specified");
        //         }
        //         if (applicationContext.containsBean("rtmps.server")) {
        //            log.debug("Initializing RTMPS");
        //            applicationContext.getBean("rtmps.server");
        //            log.debug("Finished initializing RTMPS");
        //         } else {
        //            log.debug("Dedicated RTMPS server configuration was not specified");
        //         }
        // add a root handler
        builder.setHandler(rootHandler);
        // build the server instance
        server = builder.build();
        log.info("Starting Undertow");
        server.start();
    } catch (Exception e) {
        if (e instanceof BindException || e.getMessage().indexOf("BindException") != -1) {
            log.error(
                    "Error loading undertow, unable to bind connector. You may not have permission to use the selected port",
                    e);
        } else {
            log.error("Error loading undertow", e);
        }
    } finally {
        registerJMX();
    }
    log.debug("Undertow init exit");
}

From source file:com.mgmtp.perfload.core.client.web.ssl.LtSSLSocketFactory.java

@Override
public Socket connectSocket(final Socket sock, final InetSocketAddress remoteAddress,
        final InetSocketAddress localAddress, final HttpParams params) throws IOException {
    checkArgument(remoteAddress != null, "Remote address may not be null");
    checkArgument(params != null, "HTTP parameters may not be null");

    Socket socket = sock != null ? sock : new Socket();
    if (localAddress != null) {
        socket.setReuseAddress(HttpConnectionParams.getSoReuseaddr(params));
        socket.bind(localAddress);/*  ww  w.j a va2s . c  o  m*/
    }

    socket.setSoTimeout(HttpConnectionParams.getSoTimeout(params));
    socket.connect(remoteAddress, HttpConnectionParams.getConnectionTimeout(params));

    if (socket instanceof SSLSocket) {
        return socket;
    }

    return getSSLContext().getSocketFactory().createSocket(socket, remoteAddress.getHostName(),
            remoteAddress.getPort(), true);
}

From source file:org.apache.cxf.transport.http.asyncclient.AsyncHTTPConduit.java

@Override
protected void setupConnection(Message message, Address address, HTTPClientPolicy csPolicy) throws IOException {
    if (factory.isShutdown()) {
        message.put(USE_ASYNC, Boolean.FALSE);
        super.setupConnection(message, address, csPolicy);
        return;/*  w w w  . j  a  va 2 s .  c o  m*/
    }
    boolean addressChanged = false;
    // need to do some clean up work on the URI address
    URI uri = address.getURI();
    String uriString = uri.toString();
    if (uriString.startsWith("hc://")) {
        try {
            uriString = uriString.substring(5);
            uri = new URI(uriString);
            addressChanged = true;
        } catch (URISyntaxException ex) {
            throw new MalformedURLException("unsupport uri: " + uriString);
        }
    }
    String s = uri.getScheme();
    if (!"http".equals(s) && !"https".equals(s)) {
        throw new MalformedURLException("unknown protocol: " + s);
    }

    Object o = message.getContextualProperty(USE_ASYNC);
    if (o == null) {
        o = factory.getUseAsyncPolicy();
    }
    switch (UseAsyncPolicy.getPolicy(o)) {
    case ALWAYS:
        o = true;
        break;
    case NEVER:
        o = false;
        break;
    case ASYNC_ONLY:
    default:
        o = !message.getExchange().isSynchronous();
        break;
    }

    // check tlsClientParameters from message header
    TLSClientParameters clientParameters = message.get(TLSClientParameters.class);
    if (clientParameters == null) {
        clientParameters = tlsClientParameters;
    }
    if (uri.getScheme().equals("https") && clientParameters != null
            && clientParameters.getSSLSocketFactory() != null) {
        //if they configured in an SSLSocketFactory, we cannot do anything
        //with it as the NIO based transport cannot use socket created from
        //the SSLSocketFactory.
        o = false;
    }
    if (!MessageUtils.isTrue(o)) {
        message.put(USE_ASYNC, Boolean.FALSE);
        super.setupConnection(message, addressChanged ? new Address(uriString, uri) : address, csPolicy);
        return;
    }
    if (StringUtils.isEmpty(uri.getPath())) {
        //hc needs to have the path be "/" 
        uri = uri.resolve("/");
        addressChanged = true;
    }

    message.put(USE_ASYNC, Boolean.TRUE);
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Asynchronous connection to " + uri.toString() + " has been set up");
    }
    message.put("http.scheme", uri.getScheme());
    String httpRequestMethod = (String) message.get(Message.HTTP_REQUEST_METHOD);
    if (httpRequestMethod == null) {
        httpRequestMethod = "POST";
        message.put(Message.HTTP_REQUEST_METHOD, httpRequestMethod);
    }
    final CXFHttpRequest e = new CXFHttpRequest(httpRequestMethod);
    BasicHttpEntity entity = new BasicHttpEntity() {
        public boolean isRepeatable() {
            return e.getOutputStream().retransmitable();
        }
    };
    entity.setChunked(true);
    entity.setContentType((String) message.get(Message.CONTENT_TYPE));
    e.setURI(uri);

    e.setEntity(entity);

    RequestConfig.Builder b = RequestConfig.custom().setConnectTimeout((int) csPolicy.getConnectionTimeout())
            .setSocketTimeout((int) csPolicy.getReceiveTimeout())
            .setConnectionRequestTimeout((int) csPolicy.getReceiveTimeout());
    Proxy p = proxyFactory.createProxy(csPolicy, uri);
    if (p != null && p.type() != Proxy.Type.DIRECT) {
        InetSocketAddress isa = (InetSocketAddress) p.address();
        HttpHost proxy = new HttpHost(isa.getHostName(), isa.getPort());
        b.setProxy(proxy);
    }
    e.setConfig(b.build());

    message.put(CXFHttpRequest.class, e);
}

From source file:org.apache.hadoop.hdfs.DFSUtil.java

/**
 * Return a HttpServer.Builder that the journalnode / namenode / secondary
 * namenode can use to initialize their HTTP / HTTPS server.
 * <p>//from   w  w w  . j av  a 2 s  . co  m
 */
public static HttpServer3.Builder httpServerTemplateForNNAndJN(Configuration conf,
        final InetSocketAddress httpAddr, final InetSocketAddress httpsAddr, String name,
        String spnegoUserNameKey, String spnegoKeytabFileKey) throws IOException {
    HttpConfig.Policy policy = getHttpPolicy(conf);

    HttpServer3.Builder builder = new HttpServer3.Builder().setName(name).setConf(conf)
            .setACL(new AccessControlList(conf.get(DFS_ADMIN, " ")))
            .setSecurityEnabled(UserGroupInformation.isSecurityEnabled()).setUsernameConfKey(spnegoUserNameKey)
            .setKeytabConfKey(getSpnegoKeytabKey(conf, spnegoKeytabFileKey));

    // initialize the webserver for uploading/downloading files.
    if (UserGroupInformation.isSecurityEnabled()) {
        LOG.info("Starting web server as: "
                + SecurityUtil.getServerPrincipal(conf.get(spnegoUserNameKey), httpAddr.getHostName()));
    }

    if (policy.isHttpEnabled()) {
        if (httpAddr.getPort() == 0) {
            builder.setFindPort(true);
        }

        URI uri = URI.create("http://" + NetUtils.getHostPortString(httpAddr));
        builder.addEndpoint(uri);
        LOG.info("Starting Web-server for " + name + " at: " + uri);
    }

    if (policy.isHttpsEnabled() && httpsAddr != null) {
        Configuration sslConf = loadSslConfiguration(conf);
        loadSslConfToHttpServerBuilder(builder, sslConf);

        if (httpsAddr.getPort() == 0) {
            builder.setFindPort(true);
        }

        URI uri = URI.create("https://" + NetUtils.getHostPortString(httpsAddr));
        builder.addEndpoint(uri);
        LOG.info("Starting Web-server for " + name + " at: " + uri);
    }
    return builder;
}

From source file:com.xmlcalabash.library.ApacheHttpRequest.java

public void run() throws SaxonApiException {
    super.run();/*from  w w w.  j a  v  a  2s  .c o m*/

    XdmNode requestDoc = source.read();
    XdmNode start = S9apiUtils.getDocumentElement(requestDoc);

    if (!c_request.equals(start.getNodeName())) {
        throw new UnsupportedOperationException("Not a c:http-request!");
    }

    // Check for valid attributes
    XdmSequenceIterator iter = start.axisIterator(Axis.ATTRIBUTE);
    boolean ok = true;
    while (iter.hasNext()) {
        XdmNode attr = (XdmNode) iter.next();
        QName name = attr.getNodeName();
        if (_method.equals(name) || _href.equals(name) || _detailed.equals(name) || _status_only.equals(name)
                || _username.equals(name) || _password.equals(name) || _auth_method.equals(name)
                || _send_authorization.equals(name) || _override_content_type.equals(name)) {
            // nop
        } else {
            if (XMLConstants.DEFAULT_NS_PREFIX.equals(name.getNamespaceURI())) {
                throw new XProcException("Unsupported attribute on c:http-request: " + name);
            }
        }
    }

    method = start.getAttributeValue(_method);
    statusOnly = "true".equals(start.getAttributeValue(_status_only));
    detailed = "true".equals(start.getAttributeValue(_detailed));
    overrideContentType = start.getAttributeValue(_override_content_type);

    if (start.getAttributeValue(_href) == null) {
        throw new XProcException("The 'href' attribute must be specified on p:http-request");
    }

    requestURI = start.getBaseURI().resolve(start.getAttributeValue(_href));

    if ("file".equals(requestURI.getScheme())) {
        doFile();
        return;
    }

    client = new HttpClient();

    String timeOutStr = step.getExtensionAttribute(cx_timeout);
    if (timeOutStr != null) {
        HttpMethodParams params = client.getParams();
        params.setSoTimeout(Integer.parseInt(timeOutStr));
    }

    ProxySelector proxySelector = ProxySelector.getDefault();
    List<Proxy> plist = proxySelector.select(requestURI);
    // I have no idea what I'm expected to do if I get more than one...
    if (plist.size() > 0) {
        Proxy proxy = plist.get(0);
        switch (proxy.type()) {
        case DIRECT:
            // nop;
            break;
        case HTTP:
            // This can't cause a ClassCastException, right?
            InetSocketAddress addr = (InetSocketAddress) proxy.address();
            String host = addr.getHostName();
            int port = addr.getPort();
            client.getHostConfiguration().setProxy(host, port);
            break;
        default:
            // FIXME: send out a log message
            break;
        }
    }

    if (start.getAttributeValue(_username) != null) {
        String user = start.getAttributeValue(_username);
        String pass = start.getAttributeValue(_password);
        String meth = start.getAttributeValue(_auth_method);

        if (meth == null || !("basic".equals(meth.toLowerCase()) || "digest".equals(meth.toLowerCase()))) {
            throw XProcException.stepError(3, "Unsupported auth-method: " + meth);
        }

        String host = requestURI.getHost();
        int port = requestURI.getPort();
        AuthScope scope = new AuthScope(host, port);

        UsernamePasswordCredentials cred = new UsernamePasswordCredentials(user, pass);

        client.getState().setCredentials(scope, cred);
    }

    iter = start.axisIterator(Axis.CHILD);
    XdmNode body = null;
    while (iter.hasNext()) {
        XdmNode event = (XdmNode) iter.next();
        // FIXME: What about non-whitespace text nodes?
        if (event.getNodeKind() == XdmNodeKind.ELEMENT) {
            if (body != null) {
                throw new UnsupportedOperationException("Elements follow c:multipart or c:body");
            }

            if (XProcConstants.c_header.equals(event.getNodeName())) {
                headers.add(new Header(event.getAttributeValue(_name), event.getAttributeValue(_value)));
            } else if (XProcConstants.c_multipart.equals(event.getNodeName())
                    || XProcConstants.c_body.equals(event.getNodeName())) {
                body = event;
            } else {
                throw new UnsupportedOperationException("Unexpected request element: " + event.getNodeName());
            }
        }
    }

    HttpMethodBase httpResult;

    if (method == null) {
        throw new XProcException("Method must be specified.");
    }

    if ("get".equals(method.toLowerCase())) {
        httpResult = doGet();
    } else if ("post".equals(method.toLowerCase())) {
        httpResult = doPost(body);
    } else if ("put".equals(method.toLowerCase())) {
        httpResult = doPut(body);
    } else if ("head".equals(method.toLowerCase())) {
        httpResult = doHead();
    } else {
        throw new UnsupportedOperationException("Unrecognized http method: " + method);
    }

    TreeWriter tree = new TreeWriter(runtime);
    tree.startDocument(requestURI);

    try {
        // Execute the method.
        int statusCode = client.executeMethod(httpResult);

        String contentType = getContentType(httpResult);
        if (overrideContentType != null) {
            if ((xmlContentType(contentType) && overrideContentType.startsWith("image/"))
                    || (contentType.startsWith("text/") && overrideContentType.startsWith("image/"))
                    || (contentType.startsWith("image/") && xmlContentType(overrideContentType))
                    || (contentType.startsWith("image/") && overrideContentType.startsWith("text/"))
                    || (contentType.startsWith("multipart/") && !overrideContentType.startsWith("multipart/"))
                    || (!contentType.startsWith("multipart/")
                            && overrideContentType.startsWith("multipart/"))) {
                throw XProcException.stepError(30);
            }

            //System.err.println(overrideContentType + " overrides " + contentType);
            contentType = overrideContentType;
        }

        if (detailed) {
            tree.addStartElement(XProcConstants.c_response);
            tree.addAttribute(_status, "" + statusCode);
            tree.startContent();

            for (Header header : httpResult.getResponseHeaders()) {
                // I don't understand why/how HeaderElement parsing works. I get very weird results.
                // So I'm just going to go the long way around...
                String h = header.toString();
                int cp = h.indexOf(":");
                String name = header.getName();
                String value = h.substring(cp + 1).trim();

                tree.addStartElement(XProcConstants.c_header);
                tree.addAttribute(_name, name);
                tree.addAttribute(_value, value);
                tree.startContent();
                tree.addEndElement();
            }

            if (statusOnly) {
                // Skip reading the result
            } else {
                // Read the response body.
                InputStream bodyStream = httpResult.getResponseBodyAsStream();
                readBodyContent(tree, bodyStream, httpResult);
            }

            tree.addEndElement();
        } else {
            if (statusOnly) {
                // Skip reading the result
            } else {
                // Read the response body.
                InputStream bodyStream = httpResult.getResponseBodyAsStream();
                readBodyContent(tree, bodyStream, httpResult);
            }
        }
    } catch (Exception e) {
        throw new XProcException(e);
    } finally {
        // Release the connection.
        httpResult.releaseConnection();
    }

    tree.endDocument();

    XdmNode resultNode = tree.getResult();

    result.write(resultNode);
}

From source file:org.apache.synapse.transport.nhttp.HttpCoreNIOListener.java

/**
 * Restart specific endpoints which was updated by new configurations
 *
 * @param transportIn TransportInDescription of new configuration
 * @throws AxisFault/*from  w w  w  . j  av a  2 s.  com*/
 */
public void reloadSpecificEndpoints(final TransportInDescription transportIn) throws AxisFault {
    if (state != BaseConstants.STARTED) {
        return;
    }

    HttpHost host = new HttpHost(listenerContext.getHostname(), listenerContext.getPort(), scheme.getName());

    // Rebuild connection factory
    ServerConnFactoryBuilder connFactoryBuilder = initConnFactoryBuilder(transportIn, host);
    connFactory = connFactoryBuilder.build(params);
    iodispatch.update(connFactory);

    List<InetSocketAddress> endPointsClosed = new ArrayList<InetSocketAddress>();

    //Close endpoints related to new profile's bind addresses
    Set<InetSocketAddress> endPointsToReload = connFactory.getBindAddresses();

    for (InetSocketAddress inetSocketAddress : endPointsToReload) {
        for (ListenerEndpoint listenerEndpoint : ioReactor.getEndpoints()) {
            if (inetSocketAddress.getHostName()
                    .equalsIgnoreCase(((InetSocketAddress) listenerEndpoint.getAddress()).getHostName())) {
                listenerEndpoint.close();
                endPointsClosed.add((InetSocketAddress) listenerEndpoint.getAddress());
            }
        }
    }

    //Start closed inpoints again with new configurations
    startSpecificEndpoints(endPointsClosed);

    log.info(name + " Reloaded");
}