Example usage for java.util ArrayList toArray

List of usage examples for java.util ArrayList toArray

Introduction

In this page you can find the example usage for java.util ArrayList 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:com.openkm.jcr.JCRUtils.java

/**
 * Convert a Value array to String array.
 *//*from  w  w w  . jav  a2s  . co m*/
public static String[] rolValue2String(Value[] values)
        throws ValueFormatException, IllegalStateException, javax.jcr.RepositoryException {
    ArrayList<String> list = new ArrayList<String>();

    for (int i = 0; i < values.length; i++) {
        // Do not propagate private OpenKM roles
        if (!values[i].getString().equals(Config.DEFAULT_ADMIN_ROLE)) {
            list.add(values[i].getString());
        }
    }

    return (String[]) list.toArray(new String[list.size()]);
}

From source file:com.intel.cosbench.driver.random.HistogramIntGenerator.java

private static HistogramIntGenerator tryParse(String pattern) {
    pattern = StringUtils.substringBetween(pattern, "(", ")");
    String[] args = StringUtils.split(pattern, ',');
    ArrayList<Bucket> bucketsList = new ArrayList<Bucket>();
    for (String arg : args) {
        String[] values = StringUtils.split(arg, '|');
        if (values.length != 3) {
            throw new IllegalArgumentException();
        }//  w  w  w  .  j  a  va  2 s .  com
        int lower = Integer.parseInt(values[0]);
        int upper = Integer.parseInt(values[1]);
        int weight = Integer.parseInt(values[2]);
        bucketsList.add(new Bucket(lower, upper, weight));
    }
    if (bucketsList.isEmpty()) {
        throw new IllegalArgumentException();
    }
    Collections.sort(bucketsList, new LowerComparator());
    final Bucket[] buckets = bucketsList.toArray(new Bucket[0]);
    int cumulativeWeight = 0;
    for (Bucket bucket : buckets) {
        cumulativeWeight += bucket.weight;
        bucket.cumulativeWeight = cumulativeWeight;
    }
    return new HistogramIntGenerator(buckets);
}

From source file:com.microsoftopentechnologies.intellij.helpers.AndroidStudioHelper.java

public static void deleteActivityTemplates(Object caller) throws IOException, InterruptedException {
    String[] cmd = null;/* w  w w.  j  av a 2  s  . c  o m*/

    String templatePath = URLDecoder
            .decode(ApplicationComponent.class.getResource("").getPath().replace("file:/", ""), "UTF-8");
    templatePath = templatePath.replace("/", File.separator);
    templatePath = templatePath.substring(0, templatePath.indexOf(File.separator + "lib"));
    templatePath = templatePath + File.separator + "plugins" + File.separator + "android" + File.separator;
    templatePath = templatePath + "lib" + File.separator + "templates" + File.separator + "activities"
            + File.separator;

    String[] env = null;

    String tmpdir = getTempLocation();
    BufferedInputStream bufferedInputStream = new BufferedInputStream(
            ServiceCodeReferenceHelper.getTemplateResource("ActivityTemplate.zip"));
    unZip(bufferedInputStream, tmpdir);

    if (System.getProperty("os.name").toLowerCase().startsWith("windows")) {
        try {
            VirtualFile mobileTemplate = LocalFileSystem.getInstance()
                    .findFileByIoFile(new File(templatePath + mobileServicesTemplateName));
            VirtualFile officeTemplate = LocalFileSystem.getInstance()
                    .findFileByIoFile(new File(templatePath + officeTemplateName));

            if (mobileTemplate != null)
                mobileTemplate.delete(caller);

            if (officeTemplate != null)
                officeTemplate.delete(caller);
        } catch (IOException ex) {
            PrintWriter printWriter = new PrintWriter(tmpdir + "\\script.bat");
            printWriter.println("@echo off");
            printWriter.println("del \"" + templatePath + mobileServicesTemplateName + "\" /Q /S");
            printWriter.println("del \"" + templatePath + officeTemplateName + "\" /Q /S");
            printWriter.flush();
            printWriter.close();

            String[] tmpcmd = { tmpdir + "\\elevate.exe", "script.bat", "1" };

            cmd = tmpcmd;

            ArrayList<String> tempenvlist = new ArrayList<String>();
            for (String envval : System.getenv().keySet())
                tempenvlist.add(String.format("%s=%s", envval, System.getenv().get(envval)));

            tempenvlist.add("PRECOMPILE_STREAMLINE_FILES=1");
            env = new String[tempenvlist.size()];
            tempenvlist.toArray(env);

            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec(cmd, env, new File(tmpdir));
            proc.waitFor();
        }
    } else if (System.getProperty("os.name").toLowerCase().startsWith("mac")) {
        VirtualFile mobileTemplate = LocalFileSystem.getInstance()
                .findFileByIoFile(new File(templatePath + mobileServicesTemplateName));
        VirtualFile officeTemplate = LocalFileSystem.getInstance()
                .findFileByIoFile(new File(templatePath + officeTemplateName));

        if (mobileTemplate != null && officeTemplate != null) {
            exec(new String[] { "osascript", "-e",
                    "do shell script \"rm -r \\\"/" + templatePath + mobileServicesTemplateName + "\\\"\"",
                    "-e", "do shell script \"rm -r \\\"/" + templatePath + officeTemplateName + "\\\"\"" },
                    tmpdir);
        }
    } else {
        try {
            VirtualFile mobileTemplate = LocalFileSystem.getInstance()
                    .findFileByIoFile(new File(templatePath + mobileServicesTemplateName));
            VirtualFile officeTemplate = LocalFileSystem.getInstance()
                    .findFileByIoFile(new File(templatePath + officeTemplateName));

            mobileTemplate.delete(caller);
            officeTemplate.delete(caller);
        } catch (IOException ex) {

            JPasswordField pf = new JPasswordField();
            int okCxl = JOptionPane.showConfirmDialog(null, pf,
                    "To copy Microsoft Services templates, the plugin needs your password:",
                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

            if (okCxl == JOptionPane.OK_OPTION) {
                String password = new String(pf.getPassword());

                exec(new String[] { "echo", password, "|", "sudo", "-S", "rm", "-r",
                        tmpdir + mobileServicesTemplateName, templatePath + mobileServicesTemplateName },
                        tmpdir);

                exec(new String[] { "echo", password, "|", "sudo", "-S", "rm", "-r",
                        tmpdir + officeTemplateName, templatePath + officeTemplateName }, tmpdir);
            }
        }
    }
}

From source file:com.hichinaschool.flashcards.anki.ReadText.java

public static void textToSpeech(String text, long did, int ord, int qa) {
    mTextToSpeak = text;//from w w  w .  j a  va2s .co m
    mQuestionAnswer = qa;
    mDid = did;
    mOrd = ord;

    String language = getLanguage(mDid, mOrd, mQuestionAnswer);
    if (availableTtsLocales.isEmpty()) {
        Locale[] systemLocales = Locale.getAvailableLocales();
        for (Locale loc : systemLocales) {
            if (mTts.isLanguageAvailable(loc) == TextToSpeech.LANG_COUNTRY_AVAILABLE) {
                availableTtsLocales.add(new String[] { loc.getISO3Language(), loc.getDisplayName() });
            }
        }
    }

    // Check, if stored language is available
    for (int i = 0; i < availableTtsLocales.size(); i++) {
        if (language.equals(NO_TTS)) {
            return;
        } else if (language.equals(availableTtsLocales.get(i)[0])) {
            speak(mTextToSpeak, language);
            return;
        }
    }

    // Otherwise ask
    Resources res = mReviewer.getResources();
    StyledDialog.Builder builder = new StyledDialog.Builder(mReviewer);
    if (availableTtsLocales.size() == 0) {
        builder.setTitle(res.getString(R.string.no_tts_available_title));
        builder.setMessage(res.getString(R.string.no_tts_available_message));
        builder.setIcon(R.drawable.ic_dialog_alert);
        builder.setPositiveButton(res.getString(R.string.ok), null);
    } else {
        ArrayList<CharSequence> dialogItems = new ArrayList<CharSequence>();
        final ArrayList<String> dialogIds = new ArrayList<String>();
        builder.setTitle(R.string.select_locale_title);
        // Add option: "no tts"
        dialogItems.add(res.getString(R.string.tts_no_tts));
        dialogIds.add(NO_TTS);
        for (int i = 0; i < availableTtsLocales.size(); i++) {
            dialogItems.add(availableTtsLocales.get(i)[1]);
            dialogIds.add(availableTtsLocales.get(i)[0]);
        }
        String[] items = new String[dialogItems.size()];
        dialogItems.toArray(items);

        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                MetaDB.storeLanguage(mReviewer, mDid, mOrd, mQuestionAnswer, dialogIds.get(which));
                speak(mTextToSpeak, dialogIds.get(which));
            }
        });
    }
    builder.create().show();
}

From source file:gdsc.smlm.ij.plugins.ResultsManager.java

/**
 * Add a list of input sources to the generic dialog. The choice field will be named inputName. If the file input option
 * is true then a field will be added name 'Input_file'.
 * // ww w.ja v a  2 s.c  o  m
 * @param gd
 * @param inputName
 * @param inputOption The option to select by default
 * @param source
 * @param fileInput
 */
public static void addInputSourceToDialog(GenericDialog gd, String inputName, String inputOption,
        ArrayList<String> source, boolean fileInput) {
    String[] options = source.toArray(new String[source.size()]);
    // Find the option
    inputOption = removeSizeSuffix(inputOption);

    int optionIndex = 0;
    for (int i = 0; i < options.length; i++) {
        String name = removeSizeSuffix(options[i]);
        if (name.equals(inputOption)) {
            optionIndex = i;
            break;
        }
    }
    gd.addChoice(inputName, options, options[optionIndex]);
    if (fileInput)
        gd.addStringField("Input_file", inputFilename, 30);
}

From source file:com.qpark.eip.core.failure.BaseFailureHandler.java

/**
 * Handles the exception classes://from w w  w.  j  a  v a2s .c o m
 * <ul>
 * <li>{@link FailureException}</li>
 * <li>{@link SoapFaultClientException}</li>
 * <li>{@link Exception}</li>
 * </ul>
 *
 * @param e
 * @param rp
 * @param defaultCode
 * @param log
 */
public static FailureDescription handleException(final Throwable e, final String defaultCode, final Logger log,
        final Object... data) {
    FailureDescription fd = null;
    if (InvocationTargetException.class.isInstance(e)) {
        fd = handleException(((InvocationTargetException) e).getTargetException(), defaultCode, log, data);
    } else if (MessageHandlingException.class.isInstance(e)) {
        fd = handleException(((MessagingException) e).getCause(), defaultCode, log, data);
    } else if (MessagingException.class.isInstance(e)) {
        fd = handleException(((MessagingException) e).getCause(), defaultCode, log, data);
    } else if (SoapFaultClientException.class.isInstance(e)) {
        ArrayList<Object> list = new ArrayList<Object>(data == null ? 1 : data.length + 1);
        if (data != null) {
            list.addAll(Arrays.asList(data));
        }
        if (e.getMessage() != null) {
            list.add(0, e.getMessage());
        }
        fd = getFailure("E_SOAP_FAULT_CLIENT_ERROR", e, list.toArray(new Object[list.size()]));
        if (log.isDebugEnabled()) {
            log.error(e.getMessage(), e);
        } else {
            log.error(e.getMessage());
        }
    } else if (WebServiceIOException.class.isInstance(e)) {
        fd = handleWebServiceIOException((WebServiceIOException) e, defaultCode, log, data);
    } else if (SoapFaultException.class.isInstance(e)) {
        ArrayList<Object> list = new ArrayList<Object>(data == null ? 1 : data.length + 1);
        if (data != null) {
            list.addAll(Arrays.asList(data));
        }
        if (e.getMessage() != null) {
            list.add(0, e.getMessage());
        }
        fd = handleSoapFaultException((SoapFaultException) e, defaultCode, log,
                list.toArray(new Object[list.size()]));
        if (fd == null) {
            fd = getFailure("E_SOAP_MESSAGE_VALIDATION_ERROR", e);
        }
        if (log.isDebugEnabled()) {
            log.error(e.getMessage(), e);
        } else {
            log.error(e.getMessage());
        }
    } else if (SQLException.class.isInstance(e)) {
        fd = handleSQLException((SQLException) e, DEFAULT_DATABASE, log, data);
    } else if (e.getCause() != null) {
        fd = handleException(e.getCause(), defaultCode, log, data);
    } else {
        fd = getFailure(defaultCode == null ? DEFAULT : defaultCode, e);
        if (log.isDebugEnabled()) {
            log.error(e.getMessage(), e);
        } else {
            log.error(e.getMessage());
        }
    }
    return fd;
}

From source file:net.pms.external.ExternalFactory.java

public static void loadJARs(URL[] jarURLs, boolean download) {
    // find lib jars first
    ArrayList<URL> libs = new ArrayList<>();

    for (URL jarURL : jarURLs) {
        if (isLib(jarURL)) {
            libs.add(jarURL);/*from w  w  w.j  a v a  2  s .c om*/
        }
    }

    URL[] jarURLs1 = new URL[libs.size() + 1];
    libs.toArray(jarURLs1);
    int pos = libs.size();

    for (URL jarURL : jarURLs) {
        jarURLs1[pos] = jarURL;
        loadJAR(jarURLs1, download, jarURL);
    }
}

From source file:com.shishu.utility.string.StringUtil.java

public static String[] getCookie(HttpServletRequest request) throws UnsupportedEncodingException {
    Cookie cookies[] = request.getCookies();
    ArrayList al = new ArrayList();
    if (cookies == null)
        return null;
    for (int i = 0; i < cookies.length; i++)
        al.add(cookies[i].getName() + " = " + URLDecoder.decode(cookies[i].getValue(), "utf-8"));

    return (String[]) al.toArray(new String[0]);
}

From source file:OS.java

/**
 * Returns a list of the preferred locations for storing user- specific data
 * in descending order.//ww  w  .jav a 2 s . c om
 */
public static File[] listUserDataFolders() {
    String home = System.getProperty("user.home");
    ArrayList folders = new ArrayList();

    if (isWinNT()) {
        folders.add(new File(home + "\\Application Data"));
        folders.add(new File(home + "\\Local Settings\\Application Data"));
    }

    else if (isVista()) {
        folders.add(new File(home + "\\AppData"));
        folders.add(new File(home + "\\AppData\\Local"));
    }

    else if (isMac()) {
        folders.add(new File(home + "/Library/Application Support"));
    }

    folders.add(new File(home));

    File[] files = new File[folders.size()];
    return (File[]) folders.toArray(files);
}

From source file:Main.java

/**
 * Splits a string into a number of tokens.
 * The text is split by '?' and '*'.//from   w  w  w  . j  av  a 2 s. co m
 * Where multiple '*' occur consecutively they are collapsed into a single '*'.
 *
 * @param text  the text to split
 * @return the array of tokens, never null
 */
static String[] splitOnTokens(String text) {
    // used by wildcardMatch
    // package level so a unit test may run on this

    if (text.indexOf('?') == -1 && text.indexOf('*') == -1) {
        return new String[] { text };
    }

    char[] array = text.toCharArray();
    ArrayList<String> list = new ArrayList<String>();
    StringBuilder buffer = new StringBuilder();
    for (int i = 0; i < array.length; i++) {
        if (array[i] == '?' || array[i] == '*') {
            if (buffer.length() != 0) {
                list.add(buffer.toString());
                buffer.setLength(0);
            }
            if (array[i] == '?') {
                list.add("?");
            } else if (list.isEmpty() || i > 0 && list.get(list.size() - 1).equals("*") == false) {
                list.add("*");
            }
        } else {
            buffer.append(array[i]);
        }
    }
    if (buffer.length() != 0) {
        list.add(buffer.toString());
    }

    return list.toArray(new String[list.size()]);
}