Example usage for io.netty.channel ChannelHandlerContext channel

List of usage examples for io.netty.channel ChannelHandlerContext channel

Introduction

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

Prototype

Channel channel();

Source Link

Document

Return the Channel which is bound to the ChannelHandlerContext .

Usage

From source file:com.athena.meerkat.agent.netty.MeerkatClientHandler.java

License:Apache License

@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    LOGGER.debug("channelInactive() has invoked. RemoteAddress=[{}]", ctx.channel().remoteAddress());

    // deregister a closed channel
    ChannelManagement.deregisterChannel(ctx.channel());

    if (ChannelManagement.getChannelSize() == 0) {
        connected = false;/* ww w . ja v a  2s  .c  o m*/
    }

    // ? ? ? 5  ?? .
    if (client == null) {
        client = AppContext.getBean(MeerkatClient.class);
    }

    final EventLoop eventLoop = ctx.channel().eventLoop();
    final String ipAddr = ctx.channel().remoteAddress().toString();
    eventLoop.schedule(new Runnable() {
        public void run() {
            LOGGER.debug("Attempt to reconnect within 5 seconds.");
            client.createBootstrap(new Bootstrap(), eventLoop, ipAddr.substring(1, ipAddr.indexOf(":")));
        }
    }, 5L, TimeUnit.SECONDS);

    super.channelInactive(ctx);
}

From source file:com.athena.peacock.agent.netty.PeacockClientHandler.java

License:Apache License

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    logger.debug("channelActive() has invoked. RemoteAddress=[{}]", ctx.channel().remoteAddress());

    connected = true;//from w  w  w  .  j  ava  2  s  .  c  om

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

    // register a new channel
    if (ChannelManagement.registerChannel(ipAddr, ctx.channel()) == 1) {
        // ? ? ?? ?? ? System  .
        ctx.writeAndFlush(getAgentInitialInfo());
    } else {
        while (true) {
            if (this.machineId == null) {
                Thread.sleep(100);
            } else {
                break;
            }
        }

        AgentInitialInfoMessage message = new AgentInitialInfoMessage();
        message.setMachineId(this.machineId);

        ctx.writeAndFlush(new PeacockDatagram<AgentInitialInfoMessage>(message));
    }
}

From source file:com.athena.peacock.agent.netty.PeacockClientHandler.java

License:Apache License

@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    logger.debug("channelInactive() has invoked. RemoteAddress=[{}]", ctx.channel().remoteAddress());

    // deregister a closed channel
    ChannelManagement.deregisterChannel(ctx.channel());

    if (ChannelManagement.getChannelSize() == 0) {
        connected = false;//from   ww w.ja va  2  s.c o  m
    }

    // ? ? ? 5  ?? .
    if (client == null) {
        client = AppContext.getBean(PeacockClient.class);
    }

    final EventLoop eventLoop = ctx.channel().eventLoop();
    final String ipAddr = ctx.channel().remoteAddress().toString();
    eventLoop.schedule(new Runnable() {
        @Override
        public void run() {
            logger.debug("Attempt to reconnect within 5 seconds.");
            client.createBootstrap(new Bootstrap(), eventLoop, ipAddr.substring(1, ipAddr.indexOf(":")));
        }
    }, 5L, TimeUnit.SECONDS);

    super.channelInactive(ctx);
}

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

License:Open Source License

@SuppressWarnings("unchecked")
@Override/* w  ww.  j a  v  a2s.  c  o  m*/
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.athena.peacock.controller.netty.PeacockServerHandler.java

License:Open Source License

@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    logger.debug("channelInactive() has invoked.");

    // deregister a closed channel
    ChannelManagement.deregisterChannel(ctx.channel());
}

From source file:com.baidu.rigel.biplatform.tesseract.isservice.netty.service.FileClientHandler.java

License:Open Source License

@Override
public void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof ServerFeedbackMessage) {
        message = (ServerFeedbackMessage) msg;
    } else {/*from  w  w  w . j  av  a2 s  .co m*/
        message = (ServerExceptionMessage) msg;
    }
    ctx.channel().close();

}

From source file:com.baidu.rigel.biplatform.tesseract.isservice.netty.service.FileServerHandler.java

License:Open Source License

/**
 * private FileChannel getFileChannel(String filePath) throws
 * FileNotFoundException { if(this.fcoutMap.containsKey(filePath)){ return
 * this.fcoutMap.get(filePath); } File fout = new File(filePath);
 * if(fout.exists()){ fout.delete(); } FileChannel fcout = null; fcout = new
 * FileOutputStream(fout, true).getChannel(); this.fcoutMap.put(filePath,
 * fcout); return fcout;/*from w  w w  .  j a v  a2s  . c o  m*/
 * 
 * }
 * 
 * private boolean releaseFileChannel(String filePath) throws IOException {
 * if(this.fcoutMap.containsKey(filePath)){ FileChannel
 * f=this.fcoutMap.get(filePath); f.close(); this.fcoutMap.remove(filePath);
 * return true; }
 * 
 * return false; }
 * 
 * @throws IndexAndSearchException
 **/
@Override
public void messageReceived(ChannelHandlerContext ctx, Object msg) throws IndexAndSearchException {
    LOGGER.info("get message from client " + msg);
    SendFileMessage sendFileMessage = (SendFileMessage) msg;
    MessageHeader messageHeader = new MessageHeader(NettyAction.NETTY_ACTION_COPYFILE_FEEDBACK);

    if (sendFileMessage == null || StringUtils.isEmpty(sendFileMessage.getTargetFilePath())) {
        ServerFeedbackMessage backMessage = new ServerFeedbackMessage(messageHeader,
                TesseractConstant.FEED_BACK_MSG_RESULT_FAIL, "sendFileMessage empty");
        ctx.writeAndFlush(backMessage);
    }
    String targetFilePath = sendFileMessage.getTargetFilePath();
    File fout = new File(targetFilePath);
    if (fout.exists() && sendFileMessage.isFirst()) {
        fout.delete();
    } else if (!fout.getParentFile().exists()) {
        fout.getParentFile().mkdirs();
    }

    FileOutputStream fos = null;
    FileChannel fcout = null;
    try {
        fos = new FileOutputStream(fout, true);
        fcout = fos.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(TesseractConstant.FILE_BLOCK_SIZE * 2);
        buffer.put(sendFileMessage.getContent());
        buffer.flip();
        fcout.write(buffer);
        fos.flush();
        buffer.clear();

    } catch (Exception e) {
        throw new IndexAndSearchException(
                TesseractExceptionUtils.getExceptionMessage(IndexAndSearchException.INDEXEXCEPTION_MESSAGE,
                        IndexAndSearchExceptionType.INDEX_EXCEPTION),
                e.getCause(), IndexAndSearchExceptionType.INDEX_EXCEPTION);
    } finally {
        try {
            fcout.close();
            fos.close();
        } catch (IOException e) {
            throw new IndexAndSearchException(
                    TesseractExceptionUtils.getExceptionMessage(IndexAndSearchException.INDEXEXCEPTION_MESSAGE,
                            IndexAndSearchExceptionType.INDEX_EXCEPTION),
                    e.getCause(), IndexAndSearchExceptionType.INDEX_EXCEPTION);
        }

    }
    if (sendFileMessage.isLast()) {
        try {
            FileUtils.doUncompressFile(targetFilePath, null);
        } catch (IOException e) {
            throw new IndexAndSearchException(
                    TesseractExceptionUtils.getExceptionMessage(IndexAndSearchException.INDEXEXCEPTION_MESSAGE,
                            IndexAndSearchExceptionType.INDEX_EXCEPTION),
                    e.getCause(), IndexAndSearchExceptionType.INDEX_EXCEPTION);
        }
    }

    MessageHeader mh = new MessageHeader(NettyAction.NETTY_ACTION_COPYFILE_FEEDBACK);
    String result = FileUtils.SUCC;
    String message = "copy success";
    ServerFeedbackMessage backMessage = new ServerFeedbackMessage(mh, result, message);

    ctx.writeAndFlush(backMessage);
    ctx.channel().closeFuture();

}

From source file:com.baidu.rigel.biplatform.tesseract.isservice.netty.service.IndexClientHandler.java

License:Open Source License

@Override
public void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception {
    logger.info(String.format(LogInfoConstants.INFO_PATTERN_MESSAGE_RECEIVED_BEGIN, "IndexClientHandler"));
    if (msg instanceof IndexMessage) {
        message = (IndexMessage) msg;/*from www .  j av  a  2 s . co m*/
    } else {
        message = (ServerExceptionMessage) msg;
    }
    ctx.channel().close();
    logger.info(String.format(LogInfoConstants.INFO_PATTERN_MESSAGE_RECEIVED_END, "IndexClientHandler"));

}

From source file:com.baidu.rigel.biplatform.tesseract.isservice.netty.service.IndexServerHandler.java

License:Open Source License

public void messageReceived_00(ChannelHandlerContext ctx, Object msg) throws Exception {
    logger.info(String.format(LogInfoConstants.INFO_PATTERN_MESSAGE_RECEIVED_BEGIN, "IndexServerHandler"));
    IndexMessage indexMsg = (IndexMessage) msg;
    // ??/*from  ww w.  jav a 2 s.c o m*/
    File idxFile = new File(indexMsg.getIdxPath());
    File idxServiceFile = new File(indexMsg.getIdxServicePath());

    if (indexMsg.getMessageHeader().getAction().equals(NettyAction.NETTY_ACTION_UPDATE)
            || indexMsg.getMessageHeader().getAction().equals(NettyAction.NETTY_ACTION_INITINDEX)) {
        // ??
        // ?
        FileUtils.deleteFile(idxFile);
        if (indexMsg.getMessageHeader().getAction().equals(NettyAction.NETTY_ACTION_UPDATE)
                && idxServiceFile.exists()) {
            // ?
            FileUtils.copyFolder(indexMsg.getIdxServicePath(), indexMsg.getIdxPath());
        }
    }

    IndexWriter idxWriter = IndexWriterFactory.getIndexWriterWithSingleSlot(indexMsg.getIdxPath());

    TesseractResultSet data = indexMsg.getDataBody();
    long currDiskSize = FileUtils.getDiskSize(indexMsg.getIdxPath());
    BigDecimal currMaxId = null;
    // ??
    if (currDiskSize < indexMsg.getBlockSize()) {
        while (data.next() && currDiskSize < indexMsg.getBlockSize()) {
            Document doc = new Document();
            String[] fieldNameArr = data.getFieldNameArray();
            for (String select : fieldNameArr) {
                if (select.equals(indexMsg.getIdName())) {
                    currMaxId = data.getBigDecimal(select);
                }

                doc.add(new StringField(select, data.getString(select), Field.Store.NO));
            }

            idxWriter.addDocument(doc);
        }
        idxWriter.commit();
        idxWriter.close();

    }

    String feedBackIndexServicePath = null;
    String feedBackIndexFilePath = null;

    // ? or ???indexWriter\?
    long totalDiskSize = FileUtils.getDiskSize(indexMsg.getIdxPath());
    if (totalDiskSize > indexMsg.getBlockSize() || indexMsg.isLastPiece()) {
        IndexWriterFactory.destoryWriters(indexMsg.getIdxPath());
        feedBackIndexServicePath = indexMsg.getIdxPath();
        feedBackIndexFilePath = indexMsg.getIdxServicePath();
    } else {
        feedBackIndexServicePath = indexMsg.getIdxServicePath();
        feedBackIndexFilePath = indexMsg.getIdxPath();
    }

    MessageHeader messageHeader = new MessageHeader(NettyAction.NETTY_ACTION_INDEX_FEEDBACK);

    IndexMessage indexFeedbackMsg = new IndexMessage(messageHeader, indexMsg.getDataBody());
    indexFeedbackMsg.setBlockSize(indexMsg.getBlockSize());
    indexFeedbackMsg.setDiskSize(totalDiskSize);
    indexFeedbackMsg.setIdxServicePath(feedBackIndexServicePath);
    indexFeedbackMsg.setIdxPath(feedBackIndexFilePath);
    indexFeedbackMsg.setIdName(indexMsg.getIdName());
    indexFeedbackMsg.setMaxId(currMaxId);
    ctx.writeAndFlush(indexFeedbackMsg);
    ctx.channel().close();
    logger.info(String.format(LogInfoConstants.INFO_PATTERN_MESSAGE_RECEIVED_END, "IndexServerHandler"));
}

From source file:com.baidu.rigel.biplatform.tesseract.isservice.netty.service.IndexServerHandler.java

License:Open Source License

@Override
public void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception {
    logger.info(String.format(LogInfoConstants.INFO_PATTERN_MESSAGE_RECEIVED_BEGIN, "IndexServerHandler"));
    IndexMessage indexMsg = (IndexMessage) msg;
    // ??/*from   w w w.  ja v  a 2  s.  com*/
    File idxFile = new File(indexMsg.getIdxPath());
    File idxServiceFile = new File(indexMsg.getIdxServicePath());

    if (indexMsg.getMessageHeader().getAction().equals(NettyAction.NETTY_ACTION_UPDATE)
            || indexMsg.getMessageHeader().getAction().equals(NettyAction.NETTY_ACTION_INITINDEX)) {
        // ??
        // ?
        FileUtils.deleteFile(idxFile);
        if (indexMsg.getMessageHeader().getAction().equals(NettyAction.NETTY_ACTION_UPDATE)
                && idxServiceFile.exists()) {
            // ?
            FileUtils.copyFolder(indexMsg.getIdxServicePath(), indexMsg.getIdxPath());
        }
    }

    IndexWriter idxWriter = IndexWriterFactory.getIndexWriter(indexMsg.getIdxPath());

    TesseractResultSet data = indexMsg.getDataBody();
    long currDiskSize = FileUtils.getDiskSize(indexMsg.getIdxPath());
    BigDecimal currMaxId = null;
    // ??
    if (currDiskSize < indexMsg.getBlockSize()) {
        while (data.next() && currDiskSize < indexMsg.getBlockSize()) {
            Document doc = new Document();
            String[] fieldNameArr = data.getFieldNameArray();
            for (String select : fieldNameArr) {
                if (select.equals(indexMsg.getIdName())) {
                    currMaxId = data.getBigDecimal(select);
                }

                doc.add(new StringField(select, data.getString(select), Field.Store.NO));
            }

            idxWriter.addDocument(doc);

            if ((currDiskSize + idxWriter.ramBytesUsed()) > indexMsg.getBlockSize()) {
                // ??????
                idxWriter.commit();
                // ??
                currDiskSize = FileUtils.getDiskSize(indexMsg.getIdxPath());
            }
        }
        idxWriter.commit();

    }

    String feedBackIndexServicePath = null;
    String feedBackIndexFilePath = null;
    // ? or ???indexWriter\?
    long totalDiskSize = FileUtils.getDiskSize(indexMsg.getIdxPath());
    if (totalDiskSize > indexMsg.getBlockSize() || indexMsg.isLastPiece()) {
        IndexWriterFactory.destoryWriters(indexMsg.getIdxPath());
        feedBackIndexServicePath = indexMsg.getIdxPath();
        feedBackIndexFilePath = indexMsg.getIdxServicePath();
    } else {
        feedBackIndexServicePath = indexMsg.getIdxServicePath();
        feedBackIndexFilePath = indexMsg.getIdxPath();
    }

    MessageHeader messageHeader = new MessageHeader(NettyAction.NETTY_ACTION_INDEX_FEEDBACK);

    IndexMessage indexFeedbackMsg = new IndexMessage(messageHeader, indexMsg.getDataBody());
    indexFeedbackMsg.setBlockSize(indexMsg.getBlockSize());
    indexFeedbackMsg.setDiskSize(totalDiskSize);
    indexFeedbackMsg.setIdxServicePath(feedBackIndexServicePath);
    indexFeedbackMsg.setIdxPath(feedBackIndexFilePath);
    indexFeedbackMsg.setIdName(indexMsg.getIdName());
    indexFeedbackMsg.setMaxId(currMaxId);
    ctx.writeAndFlush(indexFeedbackMsg);
    ctx.channel().close();
    logger.info(String.format(LogInfoConstants.INFO_PATTERN_MESSAGE_RECEIVED_END, "IndexServerHandler"));
}