Example usage for java.lang Boolean toString

List of usage examples for java.lang Boolean toString

Introduction

In this page you can find the example usage for java.lang Boolean toString.

Prototype

public static String toString(boolean b) 

Source Link

Document

Returns a String object representing the specified boolean.

Usage

From source file:eu.itesla_project.online.tools.RunTDSimulationsMpiTool.java

@Override
public void run(CommandLine line) throws Exception {

    OnlineWorkflowStartParameters startconfig = OnlineWorkflowStartParameters.loadDefault();

    String host = line.getOptionValue(OnlineWorkflowCommand.HOST);
    String port = line.getOptionValue(OnlineWorkflowCommand.PORT);
    String threads = line.getOptionValue(OnlineWorkflowCommand.THREADS);
    if (host != null)
        startconfig.setJmxHost(host);/*from  ww w .  j av a 2s. c  om*/
    if (port != null)
        startconfig.setJmxPort(Integer.valueOf(port));
    if (threads != null)
        startconfig.setThreads(Integer.valueOf(threads));

    String urlString = "service:jmx:rmi:///jndi/rmi://" + startconfig.getJmxHost() + ":"
            + startconfig.getJmxPort() + "/jmxrmi";

    JMXServiceURL serviceURL = new JMXServiceURL(urlString);
    Map<String, String> jmxEnv = new HashMap<>();
    JMXConnector connector = JMXConnectorFactory.connect(serviceURL, jmxEnv);
    MBeanServerConnection mbsc = connector.getMBeanServerConnection();

    ObjectName name = new ObjectName(LocalOnlineApplicationMBean.BEAN_NAME);
    LocalOnlineApplicationMBean application = MBeanServerInvocationHandler.newProxyInstance(mbsc, name,
            LocalOnlineApplicationMBean.class, false);

    boolean emptyContingency = line.hasOption("empty-contingency");
    Path caseFile = Paths.get(line.getOptionValue("case-file"));
    application.runTDSimulations(startconfig, caseFile.toString(), line.getOptionValue("contingencies"),
            Boolean.toString(emptyContingency), line.getOptionValue("output-folder"));
}

From source file:org.jfrog.teamcity.server.trigger.EditArtifactoryTriggerController.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response, Element element) {
    String selectedUrl = request.getParameter("selectedUrlId");

    if (StringUtils.isNotBlank(selectedUrl)) {
        long id = Long.parseLong(selectedUrl);

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        password = RSACipher.decryptWebRequestData(password);
        boolean useTriggerCredentials = StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password);

        String loadTargetRepos = request.getParameter("loadTargetRepos");
        if (StringUtils.isNotBlank(loadTargetRepos) && Boolean.valueOf(loadTargetRepos)) {
            Element deployableReposElement = new Element("deployableRepos");
            List<String> repos = deployableServers.getServerLocalAndCacheRepos(id, useTriggerCredentials,
                    username, password);
            for (String repo : repos) {
                deployableReposElement.addContent(new Element("repoName").addContent(repo));
            }//from w w  w  .j  a va  2  s  . c o m
            element.addContent(deployableReposElement);
        }

        String checkArtifactoryHasAddons = request.getParameter("checkArtifactoryHasAddons");
        if (StringUtils.isNotBlank(checkArtifactoryHasAddons) && Boolean.valueOf(checkArtifactoryHasAddons)) {
            Element hasAddonsElement = new Element("hasAddons");
            hasAddonsElement.setText(Boolean.toString(
                    deployableServers.serverHasAddons(id, useTriggerCredentials, username, password)));
            element.addContent(hasAddonsElement);
        }

        String checkCompatibleVersion = request.getParameter("checkCompatibleVersion");
        if (StringUtils.isNotBlank(checkCompatibleVersion) && Boolean.valueOf(checkCompatibleVersion)) {
            Element compatibleVersionElement = new Element("compatibleVersion");
            compatibleVersionElement.setText(
                    deployableServers.isServerCompatible(id, useTriggerCredentials, username, password));
            element.addContent(compatibleVersionElement);
        }
    }
}

From source file:mobisocial.metrics.MusubiExceptionHandler.java

static JSONObject jsonForException(Context context, Throwable ex, boolean caught) {
    JSONObject json = new JSONObject();
    try {//w  w w .  j  a  v  a2s . c o m
        Writer traceWriter = new StringWriter();
        PrintWriter printer = new PrintWriter(traceWriter);
        ex.printStackTrace(printer);
        json.put("type", "exception");
        json.put("caught", caught);
        json.put("app", context.getPackageName());
        json.put("message", ex.getMessage());
        json.put("trace", traceWriter.toString());
        json.put("timestamp", Long.toString(new Date().getTime()));

        boolean devmode = MusubiBaseActivity.isDeveloperModeEnabled(context);
        json.put("musubi_devmode", Boolean.toString(devmode));
        if (devmode) {
            IdentitiesManager im = new IdentitiesManager(App.getDatabaseSource(context));
            MIdentity id = im.getMyDefaultIdentity();
            String user = "Unknown";
            if (id != null) {
                user = UiUtil.safeNameForIdentity(id);
            }
            json.put("musubi_devmode_user_id", user);
            user = App.getMusubi(context).userForLocalDevice(null).getName();
            json.put("musubi_devmode_user_name", user);
        }
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            json.put("musubi_version_name", info.versionName);
            json.put("musubi_version_code", Integer.toString(info.versionCode));
        } catch (NameNotFoundException e) {
            // shouldn't happen, but not fatal.
        }
        json.put("android_api", Integer.toString(Build.VERSION.SDK_INT));
        json.put("android_release", Build.VERSION.RELEASE);
        json.put("android_model", Build.MODEL);
        json.put("android_make", Build.MANUFACTURER);
    } catch (JSONException e) {
    }
    return json;
}

From source file:com.koda.integ.hbase.test.BlockCacheBaseTest.java

@Override
public void setUp() throws Exception {

    if (initDone)
        return;/* ww  w. j  a v a2  s .  c  o  m*/

    ConsoleAppender console = new ConsoleAppender(); // create appender
    // configure the appender
    String PATTERN = "%d [%p|%c|%C{1}] %m%n";
    console.setLayout(new PatternLayout(PATTERN));
    console.setThreshold(Level.WARN);

    console.activateOptions();
    // add appender to any Logger (here is root)
    Logger.getRootLogger().removeAllAppenders();
    Logger.getRootLogger().addAppender(console);
    Configuration conf = UTIL.getConfiguration();
    conf.set("hbase.zookeeper.useMulti", "false");

    // Cache configuration
    conf.set(OffHeapBlockCache.BLOCK_CACHE_MEMORY_SIZE, Long.toString(cacheSize));
    conf.set(OffHeapBlockCache.BLOCK_CACHE_IMPL, cacheImplClass);
    //conf.set(OffHeapBlockCache.BLOCK_CACHE_YOUNG_GEN_FACTOR, Float.toString(youngGenFactor));
    conf.set(OffHeapBlockCache.BLOCK_CACHE_COMPRESSION, cacheCompression);
    conf.set(OffHeapBlockCache.BLOCK_CACHE_OVERFLOW_TO_EXT_STORAGE_ENABLED,
            Boolean.toString(cacheOverflowEnabled));
    conf.set("io.storefile.bloom.block.size", Integer.toString(BLOOM_BLOCK_SIZE));
    conf.set("hfile.index.block.max.size", Integer.toString(INDEX_BLOCK_SIZE));
    conf.set(OffHeapBlockCache.HEAP_BLOCK_CACHE_MEMORY_RATIO, Float.toString(onHeapCacheRatio));

    // Enable snapshot
    UTIL.startMiniCluster(1);
    initDone = true;
    if (data != null)
        return;
    data = generateData(N);
    cluster = UTIL.getMiniHBaseCluster();
    createTables(VERSIONS);
    createHBaseTables();
    putAllData(_tableA, N);

}

From source file:blue.orchestra.blueSynthBuilder.PresetGroup.java

public Element saveAsXML() {
    Element retVal = new Element("presetGroup");
    retVal.setAttribute("name", getPresetGroupName());

    if (currentPresetUniqueId != null) {
        retVal.setAttribute("currentPresetUniqueId", currentPresetUniqueId);
        retVal.setAttribute("currentPresetModified", Boolean.toString(currentPresetModified));
    }//  w  w w .ja  va2s .  c  o m

    for (Iterator<PresetGroup> iter = subGroups.iterator(); iter.hasNext();) {
        PresetGroup subGroup = iter.next();

        retVal.addElement(subGroup.saveAsXML());
    }

    for (Iterator<Preset> iter = presets.iterator(); iter.hasNext();) {
        Preset preset = iter.next();

        retVal.addElement(preset.saveAsXML());
    }

    return retVal;
}

From source file:cm.aptoide.pt.DownloadQueueService.java

public void startDownload(String localPath, DownloadNode downloadNode, String apkid, String[] login,
        Context context, boolean isUpdate) {
    this.context = context;
    HashMap<String, String> notification = new HashMap<String, String>();
    notification.put("remotePath", downloadNode.repo + "/" + downloadNode.path);
    notification.put("md5hash", downloadNode.md5h);

    notification.put("apkid", apkid);
    notification.put("intSize", Integer.toString(downloadNode.size));
    notification.put("intProgress", "0");
    notification.put("localPath", localPath);
    notification.put("isUpdate", Boolean.toString(isUpdate));
    /*Changed by Rafael Campos*/
    notification.put("version", downloadNode.version);

    if (login != null) {
        notification.put("loginRequired", "true");
        notification.put("username", login[0]);
        notification.put("password", login[1]);
    } else {//from   w  w  w  .  j  a  v a 2s.  c om
        notification.put("loginRequired", "false");
    }
    Log.d("Aptoide-DowloadQueueService", "download Started");
    notifications.put(apkid.hashCode(), notification);
    setNotification(apkid.hashCode(), 0);
    downloadFile(apkid.hashCode());
}

From source file:eu.itesla_project.online.tools.PrintOnlineWorkflowOptimizerResultsTool.java

@Override
public void run(CommandLine line) throws Exception {
    OnlineConfig config = OnlineConfig.load();
    OnlineDb onlinedb = config.getOnlineDbFactoryClass().newInstance().create();
    String workflowId = line.getOptionValue("workflow");
    OnlineWorkflowResults wfResults = onlinedb.getResults(workflowId);
    if (wfResults != null) {
        if (!wfResults.getContingenciesWithActions().isEmpty()) {
            Table table = new Table(5, BorderStyle.CLASSIC_WIDE);
            StringWriter content = new StringWriter();
            CsvWriter cvsWriter = new CsvWriter(content, ',');
            String[] headers = new String[5];
            int i = 0;
            table.addCell("Contingency", new CellStyle(CellStyle.HorizontalAlign.center));
            headers[i++] = "Contingency";
            table.addCell("State", new CellStyle(CellStyle.HorizontalAlign.center));
            headers[i++] = "State";
            table.addCell("Actions Found", new CellStyle(CellStyle.HorizontalAlign.center));
            headers[i++] = "Actions Found";
            table.addCell("Status", new CellStyle(CellStyle.HorizontalAlign.center));
            headers[i++] = "Status";
            table.addCell("Actions", new CellStyle(CellStyle.HorizontalAlign.center));
            headers[i++] = "Actions";
            cvsWriter.writeRecord(headers);
            for (String contingencyId : wfResults.getContingenciesWithActions()) {
                for (Integer stateId : wfResults.getUnsafeStatesWithActions(contingencyId).keySet()) {
                    String[] values = new String[5];
                    i = 0;/* w  w w  .j av a2s .  c  om*/
                    table.addCell(contingencyId);
                    values[i++] = contingencyId;
                    table.addCell(stateId.toString(), new CellStyle(CellStyle.HorizontalAlign.right));
                    values[i++] = stateId.toString();
                    table.addCell(
                            Boolean.toString(wfResults.getUnsafeStatesWithActions(contingencyId).get(stateId)),
                            new CellStyle(CellStyle.HorizontalAlign.right));
                    values[i++] = Boolean
                            .toString(wfResults.getUnsafeStatesWithActions(contingencyId).get(stateId));
                    table.addCell(wfResults.getStateStatus(contingencyId, stateId).name());
                    values[i++] = wfResults.getStateStatus(contingencyId, stateId).name();
                    String json = "-";
                    if (wfResults.getActionsIds(contingencyId, stateId) != null)
                        //                     json = Utils.actionsToJson(wfResults, contingencyId, stateId);
                        json = Utils.actionsToJsonExtended(wfResults, contingencyId, stateId);
                    table.addCell(json);
                    values[i++] = json;
                    cvsWriter.writeRecord(values);
                }
            }
            cvsWriter.flush();
            if (line.hasOption("csv"))
                System.out.println(content.toString());
            else
                System.out.println(table.render());
            cvsWriter.close();
        } else
            System.out.println("\nNo contingencies requiring corrective actions");
    } else
        System.out.println("No results for this workflow");
    onlinedb.close();
}

From source file:cycronix.ctudp.CTudp.java

public CTudp(String[] arg) {
    String[] chanName = new String[32];
    String defaultChanName = "udpchan";
    String[] csvChanNames = null;
    int ssNum[] = new int[32];
    int defaultPort = 4445;
    double dt[] = new double[32];
    double defaultDT = 0.0;
    int numChan = 0;

    // For communicating with UDP server; we send a "keep alive" heartbeat message to this server
    // and will receive UDP packets from this server
    DatagramSocket clientSocket = null; // This socket will be shared by UDPread and UDPHeartbeatTask classes
    InetAddress udpserverIP = null;
    int udpserverPort = -1;
    int heartbeatPeriod_msec = -1;
    boolean bCSVTest = false; // If the "-csvtest" option has been specified along with the "-udpserver" option, then the heartbeat message itself is a CSV string that can be used for testing CTudp in loopback mode.

    // Optional local UDP server that can be started to serve test data
    int testserverPort = -1;
    int testserverPeriod_msec = -1;

    ///*from  ww w  .  j  av a  2 s  .  com*/
    // Argument processing using Apache Commons CLI
    //
    // 1. Setup command line options
    Options options = new Options();
    options.addOption("h", "help", false, "Print this message.");
    options.addOption("pack", false,
            "Blocks of data should be packed?  default = " + Boolean.toString(packMode) + ".");
    options.addOption(Option.builder("s").argName("source name").hasArg()
            .desc("Name of source to write packets to; default = \"" + srcName + "\".").build());
    options.addOption(Option.builder("c").argName("channel name").hasArg()
            .desc("Name of channel to write packets to; default = \"" + defaultChanName + "\".").build());
    options.addOption(Option.builder("csplit").argName("channel name(s)").hasArg().desc(
            "Comma-separated list of channel names; split an incoming CSV string into a series of channels with the given names; supported channel name suffixes and their associated data types: .txt (string), .csv or no suffix (numeric), .f32 (32-bit floating point), .f64 (64-bit floating point).")
            .build());
    options.addOption(Option.builder("e").argName("exception val").hasArg().desc(
            "If a CSV string is being parsed (using the -csplit option) and there is an error saving a string component as a floating point value, use this \"exception value\" in its place; default = "
                    + Double.toString(exceptionVal) + ".")
            .build());
    options.addOption(Option.builder("m").argName("multicast address").hasArg()
            .desc("Multicast UDP address (224.0.0.1 to 239.255.255.255).").build());
    options.addOption(Option.builder("p").argName("UDP port").hasArg()
            .desc("Port number to listen for UDP packets on; default = " + Integer.toString(defaultPort) + ".")
            .build());
    options.addOption(Option.builder("d").argName("delta-Time").hasArg()
            .desc("Fixed delta-time (msec) between frames; specify 0 to use arrival-times; default = "
                    + Double.toString(defaultDT) + ".")
            .build());
    options.addOption(Option.builder("f").argName("autoFlush").hasArg().desc(
            "Flush interval (sec); amount of data per zipfile; default = " + Double.toString(autoFlush) + ".")
            .build());
    options.addOption(Option.builder("t").argName("trim-Time").hasArg()
            .desc("Trim (ring-buffer loop) time (sec); specify 0 for indefinite; default = "
                    + Double.toString(trimTime) + ".")
            .build());
    options.addOption(Option.builder("udpserver").argName("IP,port,period_msec").hasArg().desc(
            "Talk to a UDP server; send a periodic keep-alive message to the given IP:port at the specified period and receive packets from this server; not to be used with the \"-p\" option.")
            .build());
    options.addOption(Option.builder("testserver").argName("port,period_msec").hasArg().desc(
            "Start a UDP server on the local machine to serve CSV strings at the specified period with the format specified by the \"-csplit\" option (if no \"-csplit\" option has been specified, a simple text message is output). The test server waits for a message from the client before starting packet flow. This feature can be used along with the \"-udpserver\" option for local/loopback testing (NOTE: make sure the server ports match).")
            .build());
    options.addOption(Option.builder("bps").argName("blocks_per_seg").hasArg()
            .desc("Number of blocks per segment; specify 0 for no segments; default = "
                    + Long.toString(blocksPerSegment) + ".")
            .build());
    options.addOption("w", false, "Split the captured string on white space rather than commas.");
    options.addOption("x", "debug", false, "Debug mode.");

    // 2. Parse command line options
    CommandLineParser parser = new DefaultParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, arg);
    } catch (ParseException exp) { // oops, something went wrong
        System.err.println("Command line argument parsing failed: " + exp.getMessage());
        return;
    }

    // 3. Retrieve the command line values
    if (line.hasOption("help")) { // Display help message and quit
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(120);
        formatter.printHelp("CTudp", options);
        return;
    }

    srcName = line.getOptionValue("s", srcName);

    String chanNameL = line.getOptionValue("c", defaultChanName);
    chanName = chanNameL.split(",");
    numChan = chanName.length;

    if (line.hasOption("csplit")) {
        chanNameL = line.getOptionValue("csplit");
        csvChanNames = chanNameL.split(",");
        if (numChan > 1) {
            System.err.println(
                    "Error: don't use the \"-csplit\" option when receiving packets from multiple UDP ports.");
            System.exit(0);
        }
        // Make sure that the channel names either have no suffix or will end in .txt, .csv, .f32, .f64
        for (int i = 0; i < csvChanNames.length; ++i) {
            int dotIdx = csvChanNames[i].lastIndexOf('.');
            if ((dotIdx > -1) && (!csvChanNames[i].endsWith(".txt")) && (!csvChanNames[i].endsWith(".csv"))
                    && (!csvChanNames[i].endsWith(".f32")) && (!csvChanNames[i].endsWith(".f64"))) {
                System.err.println(
                        "Error: illegal channel name specified in the \"-csplit\" list: " + csvChanNames[i]);
                System.err.println(
                        "\tAccepted channel names: channels with no suffix or with .txt, .csv, .f32 or .f64 suffixes.");
                System.exit(0);
            }
        }
    }

    String exceptionValStr = line.getOptionValue("e", Double.toString(exceptionVal));
    try {
        exceptionVal = Double.parseDouble(exceptionValStr);
    } catch (NumberFormatException nfe) {
        System.err.println("Error parsing the given exception value (\"-e\" flag).");
        System.exit(0);
    }

    multiCast = line.getOptionValue("m", multiCast);

    String nss = line.getOptionValue("p", Integer.toString(defaultPort));
    String[] ssnums = nss.split(",");
    numSock = ssnums.length;
    for (int i = 0; i < numSock; i++)
        ssNum[i] = Integer.parseInt(ssnums[i]);

    String sdt = line.getOptionValue("d", Double.toString(defaultDT));
    String[] ssdt = sdt.split(",");
    for (int i = 0; i < ssdt.length; i++)
        dt[i] = Double.parseDouble(ssdt[i]);

    autoFlush = Double.parseDouble(line.getOptionValue("f", "" + autoFlush));

    trimTime = Double.parseDouble(line.getOptionValue("t", Double.toString(trimTime)));

    blocksPerSegment = Long.parseLong(line.getOptionValue("bps", Long.toString(blocksPerSegment)));

    if (line.hasOption("pack")) {
        packMode = true;
    }

    bSplitOnWhiteSpace = line.hasOption("w");

    debug = line.hasOption("debug");

    // Parameters when talking to a UDP server
    // Can't specify both "-p" and "-udpserver"
    if (line.hasOption("p") && line.hasOption("udpserver")) {
        System.err.println(
                "Specify either \"-p\" (to listen on the given port(s)) or \"-udpserver\" (to talk to UDP server), not both.");
        System.exit(0);
    }
    if (line.hasOption("udpserver")) {
        String udpserverStr = line.getOptionValue("udpserver");
        // Parse the server,port,period_msec from this string
        String[] udpserverConfigCSV = udpserverStr.split(",");
        if (udpserverConfigCSV.length != 3) {
            System.err.println(
                    "Error: the \"-udpserver\" argument must contain 3 parameters: IP,port,period_msec");
            System.exit(0);
        }
        try {
            udpserverIP = InetAddress.getByName(udpserverConfigCSV[0]);
        } catch (UnknownHostException e) {
            System.err.println("Error processing the \"-udpserver\" server name:\n" + e);
            System.exit(0);
        }
        try {
            udpserverPort = Integer.parseInt(udpserverConfigCSV[1]);
            if (udpserverPort <= 0) {
                throw new Exception("Invalid port number");
            }
        } catch (Exception e) {
            System.err.println("Error: the \"-udpserver\" port must be an integer greater than 0.");
            System.exit(0);
        }
        try {
            heartbeatPeriod_msec = Integer.parseInt(udpserverConfigCSV[2]);
            if (heartbeatPeriod_msec <= 0) {
                throw new Exception("Invalid period");
            }
        } catch (Exception e) {
            System.err.println("Error: the \"-udpserver\" period_msec must be an integer greater than 0.");
            System.exit(0);
        }
    }

    if (line.hasOption("testserver")) {
        String testserverStr = line.getOptionValue("testserver");
        // Parse the port,period_msec from this string
        String[] testserverConfigCSV = testserverStr.split(",");
        if (testserverConfigCSV.length != 2) {
            System.err
                    .println("Error: the \"-testserver\" argument must contain 2 parameters: port,period_msec");
            System.exit(0);
        }
        try {
            testserverPort = Integer.parseInt(testserverConfigCSV[0]);
            if (testserverPort <= 0) {
                throw new Exception("Invalid port number");
            }
        } catch (Exception e) {
            System.err.println("Error: the \"-testserver\" port must be an integer greater than 0.");
            System.exit(0);
        }
        try {
            testserverPeriod_msec = Integer.parseInt(testserverConfigCSV[1]);
            if (testserverPeriod_msec <= 0) {
                throw new Exception("Invalid period");
            }
        } catch (Exception e) {
            System.err.println("Error: the \"-testserver\" period_msec must be an integer greater than 0.");
            System.exit(0);
        }
    }

    if (numSock != numChan) {
        System.err.println("Error:  must specify same number of channels and ports!");
        System.exit(0);
    }
    if (multiCast != null && numSock > 1) {
        System.err.println("Error: can only have one multicast socket!");
        System.exit(0);
    }
    if (numSock == 0)
        numSock = 1; // use defaults

    System.err.println("Source name: " + srcName);
    if (udpserverIP == null) {
        for (int i = 0; i < numSock; i++) {
            System.err.println("Channel[" + i + "]: " + chanName[i]);
            System.err.println("UDPport[" + i + "]: " + ssNum[i]);
        }
    }
    if (csvChanNames != null) {
        System.err.println("\nIncoming csv strings will be split into the following channels:");
        for (int i = 0; i < (csvChanNames.length - 1); ++i) {
            System.err.print(csvChanNames[i] + ",");
        }
        System.err.println(csvChanNames[csvChanNames.length - 1]);
    }

    //
    // If user has requested it, start the test UDP server
    //
    if (testserverPort > -1) {
        UDPserver svr = null;
        try {
            svr = new UDPserver(testserverPort, testserverPeriod_msec, csvChanNames);
        } catch (SocketException se) {
            System.err.println("Error: caught exception trying to start test server:\n" + se);
            System.exit(0);
        }
        svr.start();
    }

    //
    // If user requested it, initialize communication with the UDP server
    //
    if (udpserverIP != null) {
        try {
            // This DatagramSocket will be shared by UDPread and UDPHeartbeatTask classes
            clientSocket = new DatagramSocket();
        } catch (SocketException e) {
            System.err.println("Error creating DatagramSocket:\n" + e);
            System.exit(0);
        }
        Timer time = new Timer();
        UDPHeartbeatTask heartbeatTask = new UDPHeartbeatTask(clientSocket, udpserverIP, udpserverPort);
        time.schedule(heartbeatTask, 0, heartbeatPeriod_msec);
    }

    //
    // setup CTwriter
    //
    try {
        ctw = new CTwriter(srcName, trimTime);
        ctw.setBlockMode(packMode, zipMode);
        CTinfo.setDebug(debug);
        ctw.autoSegment(blocksPerSegment);
        autoFlushMillis = (long) (autoFlush * 1000.);
        // ctw.autoFlush(autoFlush);      // auto flush to zip once per interval (sec) of data
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(0);
    }

    //
    // start a thread for each port
    // if we are talking to a UDP server, there is only 1 instance of UDPread
    //
    if (clientSocket != null) {
        System.err.println("Talk to UDP server at " + udpserverIP + ":" + udpserverPort);
        new UDPread(clientSocket, chanName[0], csvChanNames, dt[0]).start();
    } else {
        for (int i = 0; i < numSock; i++) {
            System.err.println("start thread for port: " + ssNum[i] + ", chan: " + chanName[i]);
            new UDPread(ssNum[i], chanName[i], csvChanNames, dt[i]).start();
        }
    }
}

From source file:com.adyrhan.networkclipboard.HttpServer.java

public void stopServer() {
    try {/*from  w  w  w .j  a  v a  2 s .  com*/
        Log.d(TAG, "HttpServer.stopServer() called! mIsRunning value is " + Boolean.toString(mIsRunning.get()));
        if (mIsRunning.get() && mThread != null) {
            Log.d(TAG, "Trying to stop Http server...");
            mThread.interrupt();
            mSocket.close();
            while (mIsRunning.get()) {
                Thread.sleep(10);
            }
        }

    } catch (IOException e) {
        Log.e(TAG, "Error while trying to close socket");
    } catch (InterruptedException e) {
        Log.e(TAG, null, e);
    }
}