Example usage for io.netty.channel ChannelFuture addListener

List of usage examples for io.netty.channel ChannelFuture addListener

Introduction

In this page you can find the example usage for io.netty.channel ChannelFuture addListener.

Prototype

@Override
    ChannelFuture addListener(GenericFutureListener<? extends Future<? super Void>> listener);

Source Link

Usage

From source file:com.addthis.hydra.query.web.LegacyHandler.java

License:Apache License

public static Query handleQuery(Query query, KVPairs kv, HttpRequest request, ChannelHandlerContext ctx)
        throws IOException, QueryException {

    String async = kv.getValue("async");
    if (async == null) {
        return query;
    } else if (async.equals("new")) {
        StringBuilderWriter writer = new StringBuilderWriter(50);
        HttpResponse response = HttpUtils.startResponse(writer);
        String asyncUuid = genAsyncUuid();
        asyncCache.put(asyncUuid, query);
        if (query.isTraced()) {
            Query.emitTrace("async create " + asyncUuid + " from " + query);
        }/* w  w w  .j av a  2 s  .c om*/
        writer.write("{\"id\":\"" + asyncUuid + "\"}");
        ByteBuf textResponse = ByteBufUtil.encodeString(ctx.alloc(), CharBuffer.wrap(writer.getBuilder()),
                CharsetUtil.UTF_8);
        HttpContent content = new DefaultHttpContent(textResponse);
        response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, textResponse.readableBytes());
        if (HttpHeaders.isKeepAlive(request)) {
            response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
        }
        ctx.write(response);
        ctx.write(content);
        ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
        if (!HttpHeaders.isKeepAlive(request)) {
            lastContentFuture.addListener(ChannelFutureListener.CLOSE);
        }
        return null;
    } else {
        Query asyncQuery = asyncCache.getIfPresent(async);
        asyncCache.invalidate(async);
        if (query.isTraced()) {
            Query.emitTrace("async restore " + async + " as " + asyncQuery);
        }
        if (asyncQuery != null) {
            return asyncQuery;
        } else {
            throw new QueryException("Missing Async Id");
        }
    }
}

From source file:com.addthis.meshy.AggregateChannelFuture.java

License:Apache License

/** the promises collection should not be mutated after construction */
AggregateChannelFuture(Collection<ChannelFuture> futures, EventExecutor executor) {
    super(executor);
    this.futures = futures;
    this.complete = new AtomicInteger(0);
    this.aggregatingListener = future -> {
        if (!future.isSuccess()) {
            anyCause = future.cause();/*from   ww  w.j a  v  a  2s . c  o  m*/
        }
        if (complete.incrementAndGet() == futures.size()) {
            if (anyCause == null) {
                super.setSuccess(null);
            } else {
                super.setFailure(anyCause);
            }
        }
    };
    for (ChannelFuture future : futures) {
        future.addListener(aggregatingListener);
    }
}

From source file:com.addthis.meshy.ChannelState.java

License:Apache License

public boolean send(final ByteBuf sendBuffer, final SendWatcher watcher, final int reportBytes) {
    int attempts = 1;
    while (channel.isActive()) {
        final boolean inEventLoop = channel.eventLoop().inEventLoop();
        // if this thread is the io loop for this channel: make sure it is allowed to do writes
        if (inEventLoop && !channel.isWritable()) {
            channel.unsafe().forceFlush();
        }//from ww  w .j  a v a2 s  .  c  om
        if (channel.isWritable() || (attempts >= 500)
        // if this thread is the io loop for this channel: block writes only based on the actual socket queue;
        // channel writability factors in queued writes from other threads that we can't get to until we finish.
                || (inEventLoop
                        && (channel.unsafe().outboundBuffer().size() < estimateMaxQueued(sendBuffer)))) {
            if (attempts >= 500) {
                log.warn(
                        "Forcing write despite channel being backed up to prevent possible distributed deadlock");
            }
            ChannelFuture future = channel.writeAndFlush(sendBuffer);
            future.addListener(ignored -> {
                meshy.sentBytes(reportBytes);
                if (watcher != null) {
                    watcher.sendFinished(reportBytes);
                }
            });
            return true;
        } else {
            if ((attempts % 100) == 0) {
                ChannelOutboundBuffer outboundBuffer = channel.unsafe().outboundBuffer();
                if (outboundBuffer != null) {
                    log.info(
                            "Sleeping write because channel is unwritable. Attempt: {}, Pending Bytes: {}, State: {}",
                            attempts, outboundBuffer.totalPendingWriteBytes(), this);
                }
            }
            sleepUninterruptibly(10, TimeUnit.MILLISECONDS);
            writeSleeps.incrementAndGet();
            sleepMeter.mark();
        }
        attempts += 1;
    }
    if (reportBytes > 0) {
        /**
         * if bytes == 0 then it's a sendComplete() and
         * there are plenty of legit cases when a client would
         * disconnect before sendComplete() makes it back. best
         * example is StreamService when EOF framing tells the
         * client we're done before sendComplete() framing does.
         */
        log.debug("{} writing [{}] to dead channel", this, reportBytes);
        if (watcher != null) {
            /**
             * for accounting, rate limiting reasons, we have to report these as sent.
             * no need to report 0 bytes since it's an accounting no-op.
             */
            watcher.sendFinished(reportBytes);
        }
    }
    sendBuffer.release();
    return false;
}

From source file:com.addthis.meshy.MeshyServer.java

License:Apache License

/**
 * connects to a peer address.  if peerUuid is not know, method blocks
 */// w w  w .  j a v  a  2  s.  com
@Nullable
public ChannelFuture connectToPeer(@Nullable final String peerUuid, final InetSocketAddress pAddr) {
    synchronized (blockedPeers) {
        if (peerUuid != null && blockedPeers.contains(peerUuid)) {
            return null;
        }
    }
    updateLastEventTime();
    log.debug("{} request connect to {} @ {}", MeshyServer.this, peerUuid, pAddr);
    /* skip peering with self (and other meshes started in the same vm) */
    if (peerUuid != null && group.hasUuid(peerUuid)) {
        log.debug("{} skipping {} .. it's me", this, peerUuid);
        return null;
    }
    /* skip peering with self */
    try {
        for (Enumeration<NetworkInterface> eni = NetworkInterface.getNetworkInterfaces(); eni
                .hasMoreElements();) {
            for (Enumeration<InetAddress> eaddr = eni.nextElement().getInetAddresses(); eaddr
                    .hasMoreElements();) {
                InetAddress addr = eaddr.nextElement();
                if (addr.equals(pAddr.getAddress()) && pAddr.getPort() == serverPort) {
                    log.debug("{} skipping myself {} : {}", this, addr, serverPort);
                    return null;
                }
            }
        }
    } catch (SocketException e) {
        throw new RuntimeException(e);
    }
    /* check for local peering */
    if (!allowPeerLocal) {
        byte[] peerAddr = pAddr.getAddress().getAddress();
        for (byte[] addr : vmLocalNet) {
            if (LessBytes.equals(peerAddr, addr)) {
                log.info("peer reject local {}", pAddr);
                return null;
            }
        }
    }
    /* skip peering again */
    log.debug("{} peer.check (uuid={} addr={})", this, peerUuid, pAddr);
    synchronized (connectedChannels) {
        for (ChannelState channelState : connectedChannels) {
            log.trace(" --> state={}", channelState);
            if (peerUuid != null && channelState.getName() != null && channelState.getName().equals(peerUuid)) {
                log.trace("{} 1.peer.uuid {} already connected", this, peerUuid);
                return null;
            }
            InetSocketAddress remoteAddr = channelState.getRemoteAddress();
            if (remoteAddr != null && remoteAddr.equals(pAddr)) {
                log.trace("{} 2.peer.addr {} already connected", this, pAddr);
                return null;
            }
        }
        /* already actively peering with this uuid */
        if (peerUuid != null && !inPeering.add(peerUuid)) {
            log.trace("{} skip already peering {}", MeshyServer.this, peerUuid);
            return null;
        }
    }
    log.debug("{} connecting to {} @ {}", this, peerUuid, pAddr);
    /* connect to peer */
    ChannelFuture connectionFuture = connect(pAddr);
    if (peerUuid != null) {
        connectionFuture.addListener(f -> {
            if (!f.isSuccess()) {
                synchronized (connectedChannels) {
                    inPeering.remove(peerUuid);
                }
            }
        });
    }
    return connectionFuture;
}

From source file:com.adobe.acs.livereload.impl.WebSocketServerHandler.java

License:Apache License

private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // Generate an error page if response getStatus code is not OK (200).
    if (res.getStatus().code() != HttpServletResponse.SC_OK) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);/*from  ww w .  j ava 2 s .  c  o  m*/
        buf.release();
        setContentLength(res, res.content().readableBytes());
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!isKeepAlive(req) || res.getStatus().code() != HttpServletResponse.SC_OK) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.andrewkroh.cisco.xmlservices.DefaultXmlPushService.java

License:Apache License

@Override
public ListenableFuture<XmlPushResponse> submitCommand(IpPhone phone, CiscoIPPhoneExecute command,
        XmlPushCallback commandCallback) {
    checkRunning();/*w w w .j  a  v  a2 s .c  o  m*/

    String callbackUrl = null;
    if (commandCallback != null) {
        callbackUrl = callbackManager.registerCallback(commandCallback);
    }

    final CiscoIPPhoneExecute commandCopy = CLONER.deepClone(command);

    final HttpRequest httpRequest = buildRequest(phone.getHostname(), phone.getUsername(), phone.getPassword(),
            commandCopy, callbackUrl);

    final SettableFuture<XmlPushResponse> responseFuture = SettableFuture.create();

    ChannelFuture channelFuture = bootstrap.connect(phone.getHostname(), phone.getPort());
    channelFuture.addListener(new ChannelConnectListener<XmlPushResponse>(httpRequest, PHONE_KEY, phone,
            PUSH_RESP_KEY, responseFuture, bootstrap.group(), responseTimeoutMs));

    return responseFuture;
}

From source file:com.athena.dolly.websocket.server.test.WebSocketServerHandler.java

License:Apache License

private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // Generate an error page if response getStatus code is not OK (200).
    if (res.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);/*from  ww w .  ja  v  a2 s .  com*/
        buf.release();
        setContentLength(res, res.content().readableBytes());
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.channel().writeAndFlush(res);
    if (!isKeepAlive(req) || res.getStatus().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.athena.dolly.websocket.server.test.WebSocketSslServerHandler.java

License:Apache License

private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
    // Generate an error page if response getStatus code is not OK (200).
    if (res.getStatus().code() != 200) {
        ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
        res.content().writeBytes(buf);/*from  w  ww  .jav a 2  s  . com*/
        buf.release();
        setContentLength(res, res.content().readableBytes());
    }

    // Send the response and close the connection if necessary.
    ChannelFuture f = ctx.channel().write(res);
    if (!isKeepAlive(req) || res.getStatus().code() != 200) {
        f.addListener(ChannelFutureListener.CLOSE);
    }
}

From source file:com.athena.peacock.controller.netty.PeacockServerHandler.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*from   www  . j av  a  2  s. c  om*/
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    logger.debug("channelRead0() has invoked.");
    logger.debug("[Server] IP Address => " + ctx.channel().remoteAddress().toString());
    logger.debug("[Server] Object => " + msg.getClass().getName());
    //logger.debug("[Server] Contents => " + msg.toString());

    if ("bye".equals(msg.toString())) {
        // Response and exit.
        ChannelFuture future = ctx.write("This channel will be closed.");
        future.addListener(ChannelFutureListener.CLOSE);
    } else {
        if (msg instanceof PeacockDatagram) {
            MessageType messageType = ((PeacockDatagram<?>) msg).getMessageType();

            switch (messageType) {
            case COMMAND:
                break;
            case RESPONSE:
                ProvisioningResponseMessage responseMsg = ((PeacockDatagram<ProvisioningResponseMessage>) msg)
                        .getMessage();

                if (responseMsg.isBlocking()) {
                    CallbackManagement.poll().handle(responseMsg);
                }
                break;
            case SYSTEM_STATUS:
                AgentSystemStatusMessage statusMsg = ((PeacockDatagram<AgentSystemStatusMessage>) msg)
                        .getMessage();

                //ThreadLocal cannot use.
                //List<MonFactorDto> monFactorList = (List<MonFactorDto>) ThreadLocalUtil.get(PeacockConstant.MON_FACTOR_LIST);
                List<MonFactorDto> monFactorList = AppContext.getBean(MonFactorHandler.class)
                        .getMonFactorList();

                List<MonDataDto> monDataList = new ArrayList<MonDataDto>();
                MonDataDto monData = null;

                for (MonFactorDto monFactor : monFactorList) {
                    monData = new MonDataDto();

                    monData.setMachineId(statusMsg.getAgentId());
                    monData.setMonFactorId(monFactor.getMonFactorId());
                    monData.setMonDataValue(getMonDataValue(monFactor, statusMsg));
                    monData.setRegUserId(1);
                    monData.setUpdUserId(1);

                    monDataList.add(monData);
                }

                if (this.monitorService == null) {
                    monitorService = AppContext.getBean(MonitorService.class);
                }

                monitorService.insertMonDataList(monDataList);

                break;
            case INITIAL_INFO:
                AgentInitialInfoMessage infoMsg = ((PeacockDatagram<AgentInitialInfoMessage>) msg).getMessage();

                if (infoMsg.getMachineId() != null) {
                    // register a new channel
                    ChannelManagement.registerChannel(infoMsg.getMachineId(), ctx.channel());
                    break;
                }

                String ipAddr = ctx.channel().remoteAddress().toString();
                ipAddr = ipAddr.substring(1, ipAddr.indexOf(":"));

                // ipAddr?  rhev_id RHEV Manager .
                String machineId = infoMsg.getAgentId();
                Integer hypervisorId = null;
                String displayName = null;
                String clusterName = null;
                String isPrd = "N";
                String isVm = "N";
                String description = null;
                boolean isMatch = false;
                try {
                    List<RHEVMRestTemplate> templates = RHEVMRestTemplateManager.getAllTemplates();

                    if (templates == null || templates.size() == 0) {
                        List<HypervisorDto> hypervisorList = AppContext.getBean(HypervisorService.class)
                                .getHypervisorList();
                        RHEVMRestTemplateManager.resetRHEVMRestTemplate(hypervisorList);
                        templates = RHEVMRestTemplateManager.getAllTemplates();
                    }

                    logger.debug("[PeacockServerHandler] templates.size() : {}", templates.size());

                    for (RHEVMRestTemplate restTemplate : templates) {
                        VMs vms = restTemplate.submit("/api/vms?search=" + ipAddr, HttpMethod.GET, VMs.class);

                        if (vms.getVMs().size() > 0) {
                            isVm = "Y";

                            List<VM> vmList = vms.getVMs();
                            List<IP> ipList = null;
                            for (VM vm : vmList) {
                                // ip ? ? getIps() null? .
                                ipList = vm.getGuestInfo().getIps().getIPs();

                                for (IP ip : ipList) {
                                    if (ip.getAddress().equals(ipAddr)) {
                                        isMatch = true;
                                        machineId = vm.getId();
                                        hypervisorId = restTemplate.getHypervisorId();
                                        displayName = vm.getName();
                                        description = vm.getDescription();

                                        Cluster cluster = restTemplate.submit(vm.getCluster().getHref(),
                                                HttpMethod.GET, Cluster.class);
                                        clusterName = cluster.getName();
                                        break;
                                    }
                                }

                                if (isMatch) {
                                    break;
                                }
                            }
                        }

                        if (isMatch) {
                            break;
                        }
                    }
                } catch (Exception e) {
                    // ignore
                    logger.error("Unhandled Exception has occurred.", e);
                }

                // register a new channel
                ChannelManagement.registerChannel(machineId, ctx.channel());

                // Agent? RHEV Manager? ?? ID ??? AgentID 
                //  Agent? Software  ?? ?  Software  ? ? 
                AgentInitialInfoMessage returnMsg = new AgentInitialInfoMessage();
                returnMsg.setAgentId(machineId);
                PeacockDatagram<AbstractMessage> datagram = new PeacockDatagram<AbstractMessage>(returnMsg);
                ctx.channel().writeAndFlush(datagram);

                if (this.machineService == null) {
                    machineService = AppContext.getBean(MachineService.class);
                }

                // Instance  DB? .
                MachineDto machine = new MachineDto();
                machine.setMachineId(machineId);
                machine.setHypervisorId(hypervisorId);
                machine.setDisplayName(displayName);
                machine.setDescription(description);

                if (StringUtils.isNotEmpty(displayName)) {
                    if (displayName.toLowerCase().startsWith("hhilws")
                            && !displayName.toLowerCase().startsWith("hhilwsd")) {
                        isPrd = "Y";
                    }
                }
                machine.setIsPrd(isPrd);

                machine.setMachineMacAddr(infoMsg.getMacAddrMap().get(ipAddr));
                machine.setIsVm(isVm);
                machine.setCluster(clusterName);
                machine.setOsName(infoMsg.getOsName());
                machine.setOsVer(infoMsg.getOsVersion());
                machine.setOsArch(infoMsg.getOsArch());
                machine.setCpuClock(Integer.toString(infoMsg.getCpuClock()));
                machine.setCpuNum(Integer.toString(infoMsg.getCpuNum()));
                machine.setMemSize(Long.toString(infoMsg.getMemSize()));
                machine.setIpAddr(ipAddr);
                machine.setHostName(infoMsg.getHostName());
                machine.setRegUserId(1);
                machine.setUpdUserId(1);

                machineService.insertMachine(machine);

                // machine_additional_info_tbl? hostname ?  IP    ?  .( ? IP applyYn  ?)
                machine = machineService.getAdditionalInfo(machineId);

                boolean hostnameChanged = false;
                //   hostname   chhost.sh  .
                if (machine != null && StringUtils.isNotEmpty(machine.getHostName())
                        && !machine.getHostName().equals(infoMsg.getHostName())) {
                    try {
                        // /etc/hosts ?? ? ipAddress  Machine? IP?  ? IP? ?.
                        String ipAddress = null;

                        if (StringUtils.isNotEmpty(machine.getIpAddress())) {
                            ipAddress = machine.getIpAddress();
                        } else {
                            ipAddress = ipAddr;
                        }

                        ProvisioningCommandMessage cmdMsg = new ProvisioningCommandMessage();
                        cmdMsg.setAgentId(machine.getMachineId());
                        //cmdMsg.setBlocking(true);

                        int sequence = 0;
                        Command command = new Command("SET_HOSTNAME");

                        ShellAction action = new ShellAction(sequence++);
                        action.setCommand("sh");
                        action.addArguments("chhost.sh");
                        action.addArguments(ipAddress);
                        action.addArguments(machine.getHostName());
                        command.addAction(action);

                        cmdMsg.addCommand(command);

                        datagram = new PeacockDatagram<AbstractMessage>(cmdMsg);
                        ctx.channel().writeAndFlush(datagram);

                        hostnameChanged = true;
                    } catch (Exception e) {
                        // HostName ? ??  IP ?   ??  .
                        logger.error("Unhandled exception has occurred while change hostname.", e);
                    }
                }

                boolean resetIp = false;
                if (machine != null && StringUtils.isNotEmpty(machine.getIpAddress())) {
                    if (machine.getApplyYn().equals("N") && !machine.getIpAddress().equals(ipAddr)) {
                        //  IP ?   Agent ? ? ? ? ???   .
                        machine.setIpAddr(ipAddr);
                        machineService.applyStaticIp(machine);
                        resetIp = true;
                    }
                }

                if (!resetIp) {
                    if (hostnameChanged) {
                        // IP  ? hostname ?  peacock-agent restart .
                        machineService.agentRestart(machineId);
                    } else {
                        // Package   ? Software      ? ?? .
                        if (this.softwareService == null) {
                            softwareService = AppContext.getBean(SoftwareService.class);
                        }
                        List<SoftwareDto> softwareList = softwareService.getSoftwareInstallListAll(machineId);

                        PackageService packageService = AppContext.getBean(PackageService.class);
                        PackageDto ospackage = new PackageDto();
                        ospackage.setMachineId(machineId);
                        int packageCnt = packageService.getPackageListCnt(ospackage);

                        returnMsg = new AgentInitialInfoMessage();
                        returnMsg.setAgentId(machineId);
                        if (softwareList != null && softwareList.size() > 0) {
                            returnMsg.setSoftwareInstalled("Y");
                        } else {
                            returnMsg.setSoftwareInstalled("N");
                        }
                        if (packageCnt > 0) {
                            returnMsg.setPackageCollected("Y");
                        } else {
                            returnMsg.setPackageCollected("N");
                        }
                        datagram = new PeacockDatagram<AbstractMessage>(returnMsg);
                        ctx.channel().writeAndFlush(datagram);
                    }
                }

                break;
            case PACKAGE_INFO:
                OSPackageInfoMessage packageMsg = ((PeacockDatagram<OSPackageInfoMessage>) msg).getMessage();
                List<PackageInfo> packageInfoList = packageMsg.getPackageInfoList();
                PackageInfo packageInfo = null;
                List<PackageDto> packageList = new ArrayList<PackageDto>();
                PackageDto ospackage = null;
                for (int i = 0; i < packageInfoList.size(); i++) {
                    packageInfo = packageInfoList.get(i);

                    ospackage = new PackageDto();
                    ospackage.setPkgId(i + 1);
                    ospackage.setMachineId(packageMsg.getAgentId());
                    ospackage.setName(packageInfo.getName());
                    ospackage.setArch(packageInfo.getArch());
                    ospackage.setSize(packageInfo.getSize());
                    ospackage.setVersion(packageInfo.getVersion());
                    ospackage.setReleaseInfo(packageInfo.getRelease());
                    ospackage.setInstallDate(packageInfo.getInstallDate());
                    ospackage.setSummary(packageInfo.getSummary());
                    ospackage.setDescription(packageInfo.getDescription());

                    packageList.add(ospackage);
                }

                if (packageList.size() > 0) {
                    if (packageService == null) {
                        packageService = AppContext.getBean(PackageService.class);
                    }

                    packageService.insertPackageList(packageList);
                }

                break;
            case SOFTWARE_INFO:
                SoftwareInfoMessage softwareMsg = ((PeacockDatagram<SoftwareInfoMessage>) msg).getMessage();
                List<SoftwareInfo> softwareInfoList = softwareMsg.getSoftwareInfoList();
                SoftwareInfo softwareInfo = null;

                if (softwareRepoService == null) {
                    softwareRepoService = AppContext.getBean(SoftwareRepoService.class);
                }

                SoftwareRepoDto softwareRepo = new SoftwareRepoDto();
                softwareRepo.setStart(0);
                softwareRepo.setLimit(100);
                List<SoftwareRepoDto> softwareRepoList = softwareRepoService.getSoftwareRepoList(softwareRepo);

                List<ConfigDto> configList = null;
                List<ConfigInfo> configInfoList = null;
                SoftwareDto software = null;
                ConfigDto config = null;
                int softwareId = 0;

                StringBuilder stopCmd = null;
                StringBuilder startCmd = null;

                for (int i = 0; i < softwareInfoList.size(); i++) {
                    softwareInfo = softwareInfoList.get(i);

                    for (SoftwareRepoDto repo : softwareRepoList) {
                        softwareId = 0;

                        if (repo.getSoftwareName().toLowerCase()
                                .indexOf(softwareInfo.getName().toLowerCase()) > 0) {
                            // ?  ? ??    ? softwareId .
                            softwareId = repo.getSoftwareId();
                            if (repo.getSoftwareVersion().startsWith(softwareInfo.getVersion())) {
                                softwareId = repo.getSoftwareId();
                                break;
                            }
                        }
                    }

                    //software.setInstallLocation(apacheHome + "," + serverHome + "/bin," + serverHome + "/conf," + serverHome + "/log," + serverHome + "/run," + serverHome + "/www");
                    //software.setInstallLocation(serverHome + "/apps," + serverHome + "/bin," + serverHome + "/Servers," + serverHome + "/svrlogs," + serverHome + "/wily," + serverHome + "/jboss-ews-2.1");
                    //software.setInstallLocation(jbossHome + "," + serverBase + ", " + serverHome + "/apps," + serverHome + "/svrlogs," + serverHome + "/wily");

                    stopCmd = new StringBuilder();
                    startCmd = new StringBuilder();

                    stopCmd.append("WORKING_DIR:").append(softwareInfo.getStopWorkingDir()).append(",")
                            .append("CMD:").append(softwareInfo.getStopCommand()).append(",").append("ARGS:")
                            .append(softwareInfo.getStopArgs());

                    startCmd.append("WORKING_DIR:").append(softwareInfo.getStartWorkingDir()).append(",")
                            .append("CMD:").append(softwareInfo.getStartCommand()).append(",").append("ARGS:")
                            .append(softwareInfo.getStartArgs());

                    software = new SoftwareDto();
                    software.setMachineId(softwareMsg.getAgentId());
                    software.setSoftwareId(softwareId);
                    software.setInstallLocation(StringUtils.join(softwareInfo.getInstallLocations(), ","));
                    software.setInstallStat("COMPLETED");
                    software.setInstallLog("Software installed manually.");
                    software.setServiceStopCmd(stopCmd.toString());
                    software.setServiceStartCmd(startCmd.toString());
                    software.setDescription("");
                    software.setDeleteYn("N");

                    configInfoList = softwareInfo.getConfigInfoList();
                    configList = new ArrayList<ConfigDto>();

                    for (ConfigInfo configInfo : configInfoList) {
                        config = new ConfigDto();
                        config.setMachineId(softwareMsg.getAgentId());
                        config.setSoftwareId(softwareId);
                        config.setConfigFileLocation(configInfo.getConfigFileLocation());
                        config.setConfigFileName(configInfo.getConfigFileName());
                        config.setConfigFileContents(configInfo.getConfigFileContents());
                        config.setDeleteYn("N");

                        configList.add(config);
                    }

                    if (softwareService == null) {
                        softwareService = AppContext.getBean(SoftwareService.class);
                    }

                    softwareService.insertSoftware(software, configList);
                }

                break;
            }
        }
    }
}

From source file:com.baidu.jprotobuf.pbrpc.transport.ChannelPoolObjectFactory.java

License:Apache License

@Override
public PooledObject<Connection> wrap(Connection obj) {
    Connection connection = fetchConnection();

    InetSocketAddress address;//from   w  ww  .j  a  v  a2  s.c o m
    if (host == null) {
        address = new InetSocketAddress(port);
    } else {
        address = new InetSocketAddress(host, port);
    }
    ChannelFuture future = this.rpcClient.connect(address);

    // Wait until the connection is made successfully.
    future.awaitUninterruptibly();
    if (!future.isSuccess()) {
        LOGGER.log(Level.SEVERE, "failed to get result from stp", future.cause());
    } else {
        connection.setIsConnected(true);
    }

    future.addListener(new RpcChannelFutureListener(connection));
    connection.setFuture(future);

    return new DefaultPooledObject<Connection>(connection);
}