Example usage for java.util LinkedList toArray

List of usage examples for java.util LinkedList toArray

Introduction

In this page you can find the example usage for java.util LinkedList toArray.

Prototype

@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) 

Source Link

Document

Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.

Usage

From source file:de.uka.aifb.com.systemDynamics.gui.ModelExecutionChartPanel.java

/**
 * Creates panel./*from   w w  w.j a  va  2s .co m*/
 */
private void createPanel() {
    setLayout(new BorderLayout());

    // CENTER: chart
    ChartPanel chartPanel = new ChartPanel(createChart());
    // no context menu
    chartPanel.setPopupMenu(null);
    // not zoomable
    chartPanel.setMouseZoomable(false);
    add(chartPanel, BorderLayout.CENTER);

    // LINE_END: series table
    JPanel tablePanel = new JPanel(new GridBagLayout());
    String[] columnNames = { messages.getString("ModelExecutionChartPanel.Table.ColumnNames.ExtraAxis"),
            messages.getString("ModelExecutionChartPanel.Table.ColumnNames.LevelNode") };
    final MyTableModel tableModel = new MyTableModel(columnNames, xySeriesArray.length);
    for (int i = 0; i < xySeriesArray.length; i++) {
        tableModel.addEntry((String) xySeriesArray[i].getKey());
    }
    JTable table = new JTable(tableModel);
    table.setRowSelectionAllowed(false);
    JScrollPane tableScrollPane = new JScrollPane(table);
    int width = (int) Math.min(300, table.getPreferredSize().getWidth());
    int height = (int) Math.min(200, table.getPreferredSize().getHeight());
    tableScrollPane.getViewport().setPreferredSize(new Dimension(width, height));
    tableScrollPane.setMaximumSize(tableScrollPane.getViewport().getPreferredSize());
    axesButton = new JButton(messages.getString("ModelExecutionChartPanel.AxesButton.Text"));
    axesButton.setToolTipText(messages.getString("ModelExecutionChartPanel.AxesButton.ToolTipText"));
    axesButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            // create XYSeriesCollections (and renderer)
            XYSeriesCollection standardData = new XYSeriesCollection();
            XYLineAndShapeRenderer standardRenderer = new XYLineAndShapeRenderer(true, false);
            LinkedList<XYSeriesCollection> extraDataList = new LinkedList<XYSeriesCollection>();
            LinkedList<XYLineAndShapeRenderer> extraRendererList = new LinkedList<XYLineAndShapeRenderer>();
            for (int i = 0; i < tableModel.getRowCount(); i++) {
                if (tableModel.getValueAt(i, 0).equals(Boolean.FALSE)) {
                    standardData.addSeries(xySeriesArray[i]);
                    standardRenderer.setSeriesPaint(standardData.getSeriesCount() - 1,
                            DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE[i
                                    % DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE.length]);
                } else {
                    // extra axis
                    XYSeriesCollection extraData = new XYSeriesCollection();
                    extraData.addSeries(xySeriesArray[i]);
                    extraDataList.add(extraData);
                    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false);
                    extraRendererList.add(renderer);
                    renderer.setSeriesPaint(0, DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE[i
                            % DefaultDrawingSupplier.DEFAULT_PAINT_SEQUENCE.length]);
                }
            }
            LinkedList<XYSeriesCollection> dataList = new LinkedList<XYSeriesCollection>();
            LinkedList<XYLineAndShapeRenderer> rendererList = new LinkedList<XYLineAndShapeRenderer>();
            if (!standardData.getSeries().isEmpty()) {
                dataList.add(standardData);
                rendererList.add(standardRenderer);
            }
            for (XYSeriesCollection data : extraDataList) {
                dataList.add(data);
            }
            for (XYLineAndShapeRenderer renderer : extraRendererList) {
                rendererList.add(renderer);
            }

            // creates axes
            LinkedList<NumberAxis> axesList = new LinkedList<NumberAxis>();
            if (!standardData.getSeries().isEmpty()) {
                NumberAxis axis = new NumberAxis(messages.getString("ModelExecutionChartPanel.Value"));
                axis.setNumberFormatOverride(NumberFormat.getInstance(locale));
                axesList.add(axis);
            }
            for (XYSeriesCollection data : extraDataList) {
                NumberAxis axis = new NumberAxis((String) data.getSeries(0).getKey());
                axis.setNumberFormatOverride(NumberFormat.getInstance(locale));
                axesList.add(axis);
            }

            // store data and axes in plot
            XYPlot plot = chart.getXYPlot();
            plot.clearRangeAxes();
            plot.setRangeAxes(axesList.toArray(new NumberAxis[0]));
            for (int i = 0; i < plot.getDatasetCount(); i++) {
                plot.setDataset(i, null);
            }
            int datasetIndex = 0;
            Iterator<XYSeriesCollection> datasetIterator = dataList.iterator();
            Iterator<XYLineAndShapeRenderer> rendererIterator = rendererList.iterator();
            while (datasetIterator.hasNext()) {
                plot.setDataset(datasetIndex, datasetIterator.next());
                plot.setRenderer(datasetIndex, rendererIterator.next());
                datasetIndex++;
            }
            for (int i = 0; i < plot.getDatasetCount(); i++) {
                plot.mapDatasetToRangeAxis(i, i);
            }
        }
    });
    GridBagConstraints c = new GridBagConstraints();
    c.anchor = GridBagConstraints.CENTER;
    c.gridx = 0;
    c.gridy = 0;
    c.insets = new Insets(0, 0, 10, 0);
    tablePanel.add(tableScrollPane, c);
    c.gridx = 0;
    c.gridy = 1;
    tablePanel.add(axesButton, c);
    add(tablePanel, BorderLayout.LINE_END);

    // PAGE_END: number of rounds and execution button
    JPanel commandPanel = new JPanel();
    commandPanel.add(new JLabel(messages.getString("ModelExecutionChartPanel.NumberRounds")));
    final JTextField numberRoundsField = new JTextField("1", 5);
    numberRoundsField.addFocusListener(this);
    commandPanel.add(numberRoundsField);
    executionButton = new JButton(messages.getString("ModelExecutionChartPanel.ExecutionButton.Text"));
    executionButton.setToolTipText(messages.getString("ModelExecutionChartPanel.ExecutionButton.ToolTipText"));
    executionButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            int numberRounds = 0;
            boolean correctNumber = false;
            try {
                numberRounds = integerNumberFormatter.parse(numberRoundsField.getText()).intValue();
            } catch (ParseException parseExcep) {
                // do nothing
            }

            if (numberRounds >= 1) {
                correctNumber = true;
            }

            if (correctNumber) {
                ModelExecutionThread executionThread = new ModelExecutionThread(numberRounds);
                executionThread.start();
            } else {
                JOptionPane.showMessageDialog(null,
                        messages.getString("ModelExecutionChartPanel.Error.Message"),
                        messages.getString("ModelExecutionChartPanel.Error.Title"), JOptionPane.ERROR_MESSAGE);
            }
        }
    });
    commandPanel.add(executionButton);
    add(commandPanel, BorderLayout.PAGE_END);
}

From source file:com.heliosapm.script.AbstractDeployedScript.java

public String[] getPathSegments(final int trim) {
    if (trim == 0)
        return pathSegments.clone();
    final int pLength = pathSegments.length;
    final int absTrim = Math.abs(trim);

    if (absTrim > pLength)
        throw new IllegalArgumentException("The requested trim [" + trim + "] is larger than the path segment ["
                + pathSegments.length + "]");
    if (absTrim == pLength)
        return new String[0];
    LinkedList<String> psegs = new LinkedList<String>(Arrays.asList(pathSegments));
    for (int i = 0; i < absTrim; i++) {
        if (trim < 0)
            psegs.removeFirst();// w  w w . jav a 2  s.  c  o m
        else
            psegs.removeLast();
    }
    return psegs.toArray(new String[pLength - absTrim]);
}

From source file:com.jaspersoft.jasperserver.api.metadata.olap.service.impl.OlapConnectionServiceImpl.java

public XMLATestResult testConnection(ExecutionContext context, XMLAConnection xmlaConnection) {
    try {//  w  w w.ja  va2  s .  co  m
        OlapConnectionService service = this;
        OlapConnection connection = service.getOlapConnection(context, xmlaConnection);
        ResultSet rs;
        try {
            rs = connection.getMetaData().getDatabases();
        } catch (Exception e) {
            Throwable ee = e;
            while (ee.getCause() != null && ee.getCause() != ee)
                ee = ee.getCause();
            String message = ee.getClass().getName() + ": " + ee.getMessage();
            if (ee.getClass().equals(ConnectException.class) || ee.getClass().equals(SocketException.class)
                    || ee.getClass().equals(FileNotFoundException.class)
                    || ee.getClass().equals(UnknownHostException.class)) {
                return new XMLATestResult(XMLATestCode.URI_CONNECTION_FAILED, message, e);
            } else if (ee.getClass().equals(StringIndexOutOfBoundsException.class)) {
                return new XMLATestResult(XMLATestCode.BAD_URI, message, e);
            } else if (ee.getClass().equals(IOException.class)) {
                if (ee.getMessage().contains("401")) {
                    return new XMLATestResult(XMLATestCode.BAD_CREDENTIALS, message, e);
                } else {
                    return new XMLATestResult(XMLATestCode.BAD_URI, message, e);
                }
            } else {
                return new XMLATestResult(XMLATestCode.OTHER, message, e);
            }
        }
        try {
            Schema schema = connection.getOlapSchema();
        } catch (Exception e) {
            if (e.getMessage().contains("No datasource could be found")) {
                LinkedList<String> options = new LinkedList<String>();
                try {
                    while (rs.next()) {
                        options.add(rs.getString(1));
                    }
                } catch (Exception ee) {
                    //do nothing
                }
                return new XMLATestResult(XMLATestCode.BAD_DATASOURCE, e.getMessage(),
                        options.toArray(new String[0]), e);
            } else if (e.getMessage().contains("There is no catalog named")) {
                LinkedList<String> options = new LinkedList<String>();
                for (Catalog cat : connection.getOlapCatalogs()) {
                    options.add(cat.getName());
                }
                return new XMLATestResult(XMLATestCode.BAD_CATALOG, e.getMessage(),
                        options.toArray(new String[0]), e);
            } else {
                return new XMLATestResult(XMLATestCode.OTHER, e.getMessage(), e);
            }
        }
        return new XMLATestResult(XMLATestCode.OK);
    } catch (Exception e) {
        XMLATestResult result = new XMLATestResult(XMLATestCode.OTHER, e.getMessage(), e);
        return result;
    }
}

From source file:org.gcaldaemon.core.GmailEntry.java

public final GmailMessage[] receive(String title) throws Exception {

    // Open 'INBOX' folder
    Folder inbox = mailbox.getFolder("INBOX");
    inbox.open(Folder.READ_WRITE);/*from w  w w.  ja va 2  s  .  c  o m*/
    Message[] messages = inbox.getMessages();
    if (messages == null || messages.length == 0) {
        return new GmailMessage[0];
    }

    // Loop on messages
    LinkedList list = new LinkedList();
    for (int i = 0; i < messages.length; i++) {
        Message msg = messages[i];
        if (!msg.isSet(Flag.SEEN)) {
            String subject = msg.getSubject();
            if (title == null || title.length() == 0 || title.equals(subject)) {
                GmailMessage gm = new GmailMessage();
                Address[] from = msg.getFrom();
                msg.setFlag(Flag.SEEN, true);
                if (from == null || from.length == 0) {
                    continue;
                }
                gm.subject = subject;
                gm.from = from[0].toString();
                gm.memo = String.valueOf(msg.getContent());
                list.addLast(gm);
            }
        }
    }
    inbox.close(true);

    // Return the array of the messages
    GmailMessage[] array = new GmailMessage[list.size()];
    list.toArray(array);
    return array;
}

From source file:io.hummer.util.test.GenericTestResult.java

public void createGnuplotHisto(List<?> levels, String[] xValueNames, String[] titles, ResultType type,
        String xLabel, String yLabel, String outFile, String... additionalCommands) throws Exception {
    if (additionalCommands == null)
        additionalCommands = new String[0];
    LinkedList<String> temp = new LinkedList<String>(Arrays.asList(additionalCommands));
    additionalCommands = temp.toArray(new String[0]);
    createGnuplot("etc/createImageHisto.gnuplot", levels, xValueNames, titles, type, xLabel, yLabel, outFile,
            additionalCommands);/*  w w  w . j a  va  2  s  . c om*/
}

From source file:io.hummer.util.test.GenericTestResult.java

public void createGnuplotMulti(List<?> levels, String[] xValueNames, String[] titles, ResultType type,
        String xLabel, String yLabel, String outFile, String... additionalCommands) throws Exception {
    if (additionalCommands == null)
        additionalCommands = new String[0];
    List<String> levelStrings = collUtil.toStringList(levels);
    LinkedList<String> temp = new LinkedList<String>(Arrays.asList(additionalCommands));
    temp.add(CMD_MULTI_LINE);/*from  ww  w. j a  va 2s.  com*/
    additionalCommands = temp.toArray(new String[0]);
    createGnuplot("etc/createImageMulti.gnuplot", levelStrings, xValueNames, titles, type, xLabel, yLabel,
            outFile, additionalCommands);
}

From source file:org.apache.accumulo.miniclusterImpl.MiniAccumuloClusterImpl.java

/**
 * Starts Accumulo and Zookeeper processes. Can only be called once.
 *///ww w .j  a  v  a2s . c o  m
@SuppressFBWarnings(value = "UNENCRYPTED_SOCKET", justification = "insecure socket used for reservation")
@Override
public synchronized void start() throws IOException, InterruptedException {
    if (config.useMiniDFS() && miniDFS == null) {
        throw new IllegalStateException("Cannot restart mini when using miniDFS");
    }

    MiniAccumuloClusterControl control = getClusterControl();

    if (config.useExistingInstance()) {
        AccumuloConfiguration acuConf = config.getAccumuloConfiguration();
        Configuration hadoopConf = config.getHadoopConfiguration();

        ConfigurationCopy cc = new ConfigurationCopy(acuConf);
        VolumeManager fs;
        try {
            fs = VolumeManagerImpl.get(cc, hadoopConf);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Path instanceIdPath = ServerUtil.getAccumuloInstanceIdPath(fs);

        String instanceIdFromFile = ZooUtil.getInstanceIDFromHdfs(instanceIdPath, cc, hadoopConf);
        IZooReaderWriter zrw = new ZooReaderWriterFactory().getZooReaderWriter(
                cc.get(Property.INSTANCE_ZK_HOST), (int) cc.getTimeInMillis(Property.INSTANCE_ZK_TIMEOUT),
                cc.get(Property.INSTANCE_SECRET));

        String rootPath = ZooUtil.getRoot(instanceIdFromFile);

        String instanceName = null;
        try {
            for (String name : zrw.getChildren(Constants.ZROOT + Constants.ZINSTANCES)) {
                String instanceNamePath = Constants.ZROOT + Constants.ZINSTANCES + "/" + name;
                byte[] bytes = zrw.getData(instanceNamePath, new Stat());
                String iid = new String(bytes, UTF_8);
                if (iid.equals(instanceIdFromFile)) {
                    instanceName = name;
                }
            }
        } catch (KeeperException e) {
            throw new RuntimeException("Unable to read instance name from zookeeper.", e);
        }
        if (instanceName == null)
            throw new RuntimeException("Unable to read instance name from zookeeper.");

        config.setInstanceName(instanceName);
        if (!AccumuloStatus.isAccumuloOffline(zrw, rootPath))
            throw new RuntimeException("The Accumulo instance being used is already running. Aborting.");
    } else {
        if (!initialized) {
            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                try {
                    MiniAccumuloClusterImpl.this.stop();
                } catch (IOException e) {
                    log.error("IOException while attempting to stop the MiniAccumuloCluster.", e);
                } catch (InterruptedException e) {
                    log.error("The stopping of MiniAccumuloCluster was interrupted.", e);
                }
            }));
        }

        if (!config.useExistingZooKeepers())
            control.start(ServerType.ZOOKEEPER);

        if (!initialized) {
            if (!config.useExistingZooKeepers()) {
                // sleep a little bit to let zookeeper come up before calling init, seems to work better
                long startTime = System.currentTimeMillis();
                while (true) {
                    Socket s = null;
                    try {
                        s = new Socket("localhost", config.getZooKeeperPort());
                        s.setReuseAddress(true);
                        s.getOutputStream().write("ruok\n".getBytes());
                        s.getOutputStream().flush();
                        byte[] buffer = new byte[100];
                        int n = s.getInputStream().read(buffer);
                        if (n >= 4 && new String(buffer, 0, 4).equals("imok"))
                            break;
                    } catch (Exception e) {
                        if (System.currentTimeMillis() - startTime >= config.getZooKeeperStartupTime()) {
                            throw new ZooKeeperBindException("Zookeeper did not start within "
                                    + (config.getZooKeeperStartupTime() / 1000) + " seconds. Check the logs in "
                                    + config.getLogDir() + " for errors.  Last exception: " + e);
                        }
                        // Don't spin absurdly fast
                        sleepUninterruptibly(250, TimeUnit.MILLISECONDS);
                    } finally {
                        if (s != null)
                            s.close();
                    }
                }
            }

            LinkedList<String> args = new LinkedList<>();
            args.add("--instance-name");
            args.add(config.getInstanceName());
            args.add("--user");
            args.add(config.getRootUserName());
            args.add("--clear-instance-name");

            // If we aren't using SASL, add in the root password
            final String saslEnabled = config.getSiteConfig().get(Property.INSTANCE_RPC_SASL_ENABLED.getKey());
            if (saslEnabled == null || !Boolean.parseBoolean(saslEnabled)) {
                args.add("--password");
                args.add(config.getRootPassword());
            }

            Process initProcess = exec(Initialize.class, args.toArray(new String[0])).getProcess();
            int ret = initProcess.waitFor();
            if (ret != 0) {
                throw new RuntimeException("Initialize process returned " + ret + ". Check the logs in "
                        + config.getLogDir() + " for errors.");
            }
            initialized = true;
        }
    }

    log.info("Starting MAC against instance {} and zookeeper(s) {}.", config.getInstanceName(),
            config.getZooKeepers());

    control.start(ServerType.TABLET_SERVER);

    int ret = 0;
    for (int i = 0; i < 5; i++) {
        ret = exec(Main.class, SetGoalState.class.getName(), MasterGoalState.NORMAL.toString()).getProcess()
                .waitFor();
        if (ret == 0)
            break;
        sleepUninterruptibly(1, TimeUnit.SECONDS);
    }
    if (ret != 0) {
        throw new RuntimeException("Could not set master goal state, process returned " + ret
                + ". Check the logs in " + config.getLogDir() + " for errors.");
    }

    control.start(ServerType.MASTER);
    control.start(ServerType.GARBAGE_COLLECTOR);

    if (executor == null) {
        executor = Executors.newSingleThreadExecutor();
    }
}

From source file:org.testng.spring.test.AbstractDependencyInjectionSpringContextTests.java

private void initManagedVariableNames() throws IllegalAccessException {
    LinkedList managedVarNames = new LinkedList();
    Class clazz = getClass();/*from   w  ww.  j a v a 2 s  .c  o  m*/

    do {
        Field[] fields = clazz.getDeclaredFields();
        if (logger.isDebugEnabled()) {
            logger.debug("Found " + fields.length + " fields on " + clazz);
        }

        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            field.setAccessible(true);
            if (logger.isDebugEnabled()) {
                logger.debug("Candidate field: " + field);
            }
            if (isProtectedInstanceField(field)) {
                Object oldValue = field.get(this);
                if (oldValue == null) {
                    managedVarNames.add(field.getName());
                    if (logger.isDebugEnabled()) {
                        logger.debug("Added managed variable '" + field.getName() + "'");
                    }
                } else {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Rejected managed variable '" + field.getName() + "'");
                    }
                }
            }
        }
        clazz = clazz.getSuperclass();
    } while (!clazz.equals(AbstractDependencyInjectionSpringContextTests.class));

    this.managedVariableNames = (String[]) managedVarNames.toArray(new String[managedVarNames.size()]);
}

From source file:ch.randelshofer.cubetwister.HTMLExporter.java

/**
 * Reads the content of the input stream into a list of token.
 * If a token start with "${", its a placeholder.
 * If a token doesn't start with "${" its a literal text.
 *//*from  www .ja  v a2 s.  c o  m*/
private String[] toTokens(String filename, InputStream in) throws IOException {
    InputStreamReader reader = new InputStreamReader(in, "UTF8");
    StringBuilder buf = new StringBuilder();
    char[] cbuf = new char[256];
    int len;
    while (-1 != (len = reader.read(cbuf, 0, cbuf.length))) {
        buf.append(cbuf, 0, len);
    }

    int p1 = 0;
    int p2 = 0;
    LinkedList<String> tokens = new LinkedList<String>();
    while (true) {
        p1 = buf.indexOf("${", p2);
        if (p1 == -1) {
            break;
        }
        tokens.add(buf.substring(p2, p1));
        p2 = buf.indexOf("}", p1 + 2);
        if (p2 == -1) {
            throw new IOException("Closing curly bracket missing in " + filename + " after position " + p1);
        }
        p2++;
        tokens.add(buf.substring(p1, p2));
    }
    if (p2 != buf.length()) {
        tokens.add(buf.substring(p2));
    }
    return tokens.toArray(new String[tokens.size()]);
}

From source file:org.apache.accumulo.minicluster.impl.MiniAccumuloClusterImpl.java

/**
 * Starts Accumulo and Zookeeper processes. Can only be called once.
 *///from   w w w.  jav  a  2  s.  co  m
@Override
public synchronized void start() throws IOException, InterruptedException {
    if (config.useMiniDFS() && miniDFS == null) {
        throw new IllegalStateException("Cannot restart mini when using miniDFS");
    }

    MiniAccumuloClusterControl control = getClusterControl();

    if (config.useExistingInstance()) {
        Configuration acuConf = config.getAccumuloConfiguration();
        Configuration hadoopConf = config.getHadoopConfiguration();

        ConfigurationCopy cc = new ConfigurationCopy(acuConf);
        VolumeManager fs;
        try {
            fs = VolumeManagerImpl.get(cc, hadoopConf);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Path instanceIdPath = Accumulo.getAccumuloInstanceIdPath(fs);

        String instanceIdFromFile = ZooUtil.getInstanceIDFromHdfs(instanceIdPath, cc, hadoopConf);
        IZooReaderWriter zrw = new ZooReaderWriterFactory().getZooReaderWriter(
                cc.get(Property.INSTANCE_ZK_HOST), (int) cc.getTimeInMillis(Property.INSTANCE_ZK_TIMEOUT),
                cc.get(Property.INSTANCE_SECRET));

        String rootPath = ZooUtil.getRoot(instanceIdFromFile);

        String instanceName = null;
        try {
            for (String name : zrw.getChildren(Constants.ZROOT + Constants.ZINSTANCES)) {
                String instanceNamePath = Constants.ZROOT + Constants.ZINSTANCES + "/" + name;
                byte[] bytes = zrw.getData(instanceNamePath, new Stat());
                String iid = new String(bytes, UTF_8);
                if (iid.equals(instanceIdFromFile)) {
                    instanceName = name;
                }
            }
        } catch (KeeperException e) {
            throw new RuntimeException("Unable to read instance name from zookeeper.", e);
        }
        if (instanceName == null)
            throw new RuntimeException("Unable to read instance name from zookeeper.");

        config.setInstanceName(instanceName);
        if (!AccumuloStatus.isAccumuloOffline(zrw, rootPath))
            throw new RuntimeException("The Accumulo instance being used is already running. Aborting.");
    } else {
        if (!initialized) {
            Runtime.getRuntime().addShutdownHook(new Thread() {
                @Override
                public void run() {
                    try {
                        MiniAccumuloClusterImpl.this.stop();
                    } catch (IOException e) {
                        log.error("IOException while attempting to stop the MiniAccumuloCluster.", e);
                    } catch (InterruptedException e) {
                        log.error("The stopping of MiniAccumuloCluster was interrupted.", e);
                    }
                }
            });
        }

        if (!config.useExistingZooKeepers())
            control.start(ServerType.ZOOKEEPER);

        if (!initialized) {
            if (!config.useExistingZooKeepers()) {
                // sleep a little bit to let zookeeper come up before calling init, seems to work better
                long startTime = System.currentTimeMillis();
                while (true) {
                    Socket s = null;
                    try {
                        s = new Socket("localhost", config.getZooKeeperPort());
                        s.setReuseAddress(true);
                        s.getOutputStream().write("ruok\n".getBytes());
                        s.getOutputStream().flush();
                        byte buffer[] = new byte[100];
                        int n = s.getInputStream().read(buffer);
                        if (n >= 4 && new String(buffer, 0, 4).equals("imok"))
                            break;
                    } catch (Exception e) {
                        if (System.currentTimeMillis() - startTime >= config.getZooKeeperStartupTime()) {
                            throw new ZooKeeperBindException("Zookeeper did not start within "
                                    + (config.getZooKeeperStartupTime() / 1000) + " seconds. Check the logs in "
                                    + config.getLogDir() + " for errors.  Last exception: " + e);
                        }
                        // Don't spin absurdly fast
                        Thread.sleep(250);
                    } finally {
                        if (s != null)
                            s.close();
                    }
                }
            }

            LinkedList<String> args = new LinkedList<>();
            args.add("--instance-name");
            args.add(config.getInstanceName());
            args.add("--user");
            args.add(config.getRootUserName());
            args.add("--clear-instance-name");

            // If we aren't using SASL, add in the root password
            final String saslEnabled = config.getSiteConfig().get(Property.INSTANCE_RPC_SASL_ENABLED.getKey());
            if (null == saslEnabled || !Boolean.parseBoolean(saslEnabled)) {
                args.add("--password");
                args.add(config.getRootPassword());
            }

            Process initProcess = exec(Initialize.class, args.toArray(new String[0]));
            int ret = initProcess.waitFor();
            if (ret != 0) {
                throw new RuntimeException("Initialize process returned " + ret + ". Check the logs in "
                        + config.getLogDir() + " for errors.");
            }
            initialized = true;
        }
    }

    log.info("Starting MAC against instance {} and zookeeper(s) {}.", config.getInstanceName(),
            config.getZooKeepers());

    control.start(ServerType.TABLET_SERVER);

    int ret = 0;
    for (int i = 0; i < 5; i++) {
        ret = exec(Main.class, SetGoalState.class.getName(), MasterGoalState.NORMAL.toString()).waitFor();
        if (ret == 0)
            break;
        sleepUninterruptibly(1, TimeUnit.SECONDS);
    }
    if (ret != 0) {
        throw new RuntimeException("Could not set master goal state, process returned " + ret
                + ". Check the logs in " + config.getLogDir() + " for errors.");
    }

    control.start(ServerType.MASTER);
    control.start(ServerType.GARBAGE_COLLECTOR);

    if (null == executor) {
        executor = Executors.newSingleThreadExecutor();
    }
}