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:org.apache98.hadoop.conf.Configuration.java

private Resource loadResource(Properties properties, Resource wrapper, boolean quiet) {
    String name = UNKNOWN_RESOURCE;
    try {//from ww w. j a  v  a 2  s. c o m
        Object resource = wrapper.getResource();
        name = wrapper.getName();

        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        // ignore all comments inside the xml file
        docBuilderFactory.setIgnoringComments(true);

        // allow includes in the xml file
        docBuilderFactory.setNamespaceAware(true);
        try {
            docBuilderFactory.setXIncludeAware(true);
        } catch (UnsupportedOperationException e) {
            LOG.error("Failed to set setXIncludeAware(true) for parser " + docBuilderFactory + ":" + e, e);
        }
        DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
        Document doc = null;
        Element root = null;
        boolean returnCachedProperties = false;

        if (resource instanceof URL) { // an URL resource
            doc = parse(builder, (URL) resource);
        } else if (resource instanceof String) { // a CLASSPATH resource
            URL url = getResource((String) resource);
            doc = parse(builder, url);
        } else if (resource instanceof Path) { // a file resource
            // Can't use FileSystem API or we get an infinite loop
            // since FileSystem uses Configuration API. Use java.io.File instead.
            File file = new File(((Path) resource).toUri().getPath()).getAbsoluteFile();
            if (file.exists()) {
                if (!quiet) {
                    LOG.debug("parsing File " + file);
                }
                doc = parse(builder, new BufferedInputStream(new FileInputStream(file)),
                        ((Path) resource).toString());
            }
        } else if (resource instanceof InputStream) {
            doc = parse(builder, (InputStream) resource, null);
            returnCachedProperties = true;
        } else if (resource instanceof Properties) {
            overlay(properties, (Properties) resource);
        } else if (resource instanceof Element) {
            root = (Element) resource;
        }

        if (root == null) {
            if (doc == null) {
                if (quiet) {
                    return null;
                }
                throw new RuntimeException(resource + " not found");
            }
            root = doc.getDocumentElement();
        }
        Properties toAddTo = properties;
        if (returnCachedProperties) {
            toAddTo = new Properties();
        }
        if (!"configuration".equals(root.getTagName())) {
            LOG.fatal("bad conf file: top-level element not <configuration>");
        }
        NodeList props = root.getChildNodes();
        DeprecationContext deprecations = deprecationContext.get();
        for (int i = 0; i < props.getLength(); i++) {
            Node propNode = props.item(i);
            if (!(propNode instanceof Element)) {
                continue;
            }
            Element prop = (Element) propNode;
            if ("configuration".equals(prop.getTagName())) {
                loadResource(toAddTo, new Resource(prop, name), quiet);
                continue;
            }
            if (!"property".equals(prop.getTagName())) {
                LOG.warn("bad conf file: element not <property>");
            }
            NodeList fields = prop.getChildNodes();
            String attr = null;
            String value = null;
            boolean finalParameter = false;
            LinkedList<String> source = new LinkedList<String>();
            for (int j = 0; j < fields.getLength(); j++) {
                Node fieldNode = fields.item(j);
                if (!(fieldNode instanceof Element)) {
                    continue;
                }
                Element field = (Element) fieldNode;
                if ("name".equals(field.getTagName()) && field.hasChildNodes()) {
                    attr = StringInterner.weakIntern(((Text) field.getFirstChild()).getData().trim());
                }
                if ("value".equals(field.getTagName()) && field.hasChildNodes()) {
                    value = StringInterner.weakIntern(((Text) field.getFirstChild()).getData());
                }
                if ("final".equals(field.getTagName()) && field.hasChildNodes()) {
                    finalParameter = "true".equals(((Text) field.getFirstChild()).getData());
                }
                if ("source".equals(field.getTagName()) && field.hasChildNodes()) {
                    source.add(StringInterner.weakIntern(((Text) field.getFirstChild()).getData()));
                }
            }
            source.add(name);

            // Ignore this parameter if it has already been marked as 'final'
            if (attr != null) {
                if (deprecations.getDeprecatedKeyMap().containsKey(attr)) {
                    DeprecatedKeyInfo keyInfo = deprecations.getDeprecatedKeyMap().get(attr);
                    keyInfo.clearAccessed();
                    for (String key : keyInfo.newKeys) {
                        // update new keys with deprecated key's value
                        loadProperty(toAddTo, name, key, value, finalParameter,
                                source.toArray(new String[source.size()]));
                    }
                } else {
                    loadProperty(toAddTo, name, attr, value, finalParameter,
                            source.toArray(new String[source.size()]));
                }
            }
        }

        if (returnCachedProperties) {
            overlay(properties, toAddTo);
            return new Resource(toAddTo, name);
        }
        return null;
    } catch (IOException e) {
        LOG.fatal("error parsing conf " + name, e);
        throw new RuntimeException(e);
    } catch (DOMException e) {
        LOG.fatal("error parsing conf " + name, e);
        throw new RuntimeException(e);
    } catch (SAXException e) {
        LOG.fatal("error parsing conf " + name, e);
        throw new RuntimeException(e);
    } catch (ParserConfigurationException e) {
        LOG.fatal("error parsing conf " + name, e);
        throw new RuntimeException(e);
    }
}

From source file:es.caib.seycon.ng.servei.XarxaServiceImpl.java

protected Collection<Maquina> handleFindMaquinaByFiltreSenseRestriccions(String nom, String sistemaOperatiu,
        String adreca, String dhcp, String correu, String ofimatica, String alias, String mac,
        String descripcio, String xarxa, String codiUsuari, Boolean filtra) throws Exception {
    if (nom != null && (nom.trim().compareTo("") == 0 || nom.trim().compareTo("%") == 0)) { //$NON-NLS-1$ //$NON-NLS-2$
        nom = null;/*from w ww .  java 2 s.  c o m*/
    }
    if (sistemaOperatiu != null
            && (sistemaOperatiu.trim().compareTo("") == 0 || sistemaOperatiu.trim().compareTo( //$NON-NLS-1$
                    "%") == 0)) { //$NON-NLS-1$
        sistemaOperatiu = null;
    }
    if (adreca != null && (adreca.trim().compareTo("") == 0 || adreca.trim().compareTo("%") == 0)) { //$NON-NLS-1$ //$NON-NLS-2$
        adreca = null;
    }
    if (dhcp != null && (dhcp.trim().compareTo("") == 0 || dhcp.trim().compareTo("%") == 0)) { //$NON-NLS-1$ //$NON-NLS-2$
        dhcp = null;
    }
    if (correu != null && (correu.trim().compareTo("") == 0 || correu.trim().compareTo("%") == 0)) { //$NON-NLS-1$ //$NON-NLS-2$
        correu = null;
    }
    if (ofimatica != null && (ofimatica.trim().compareTo("") == 0 || ofimatica.trim().compareTo("%") == 0)) { //$NON-NLS-1$ //$NON-NLS-2$
        ofimatica = null;
    }
    if (alias != null && (alias.trim().compareTo("") == 0 || alias.trim().compareTo("%") == 0)) { //$NON-NLS-1$ //$NON-NLS-2$
        alias = null;
    }
    if (mac != null && (mac.trim().compareTo("") == 0 || mac.trim().compareTo("%") == 0)) { //$NON-NLS-1$ //$NON-NLS-2$
        mac = null;
    }
    if (descripcio != null && (descripcio.trim().compareTo("") == 0 || descripcio.trim().compareTo("%") == 0)) { //$NON-NLS-1$ //$NON-NLS-2$
        descripcio = null;
    }
    if (xarxa != null && (xarxa.trim().compareTo("") == 0 || xarxa.trim().compareTo("%") == 0)) { //$NON-NLS-1$ //$NON-NLS-2$
        xarxa = null;
    }

    if (codiUsuari != null && (codiUsuari.trim().compareTo("") == 0 || codiUsuari.trim().compareTo("%") == 0)) { //$NON-NLS-1$ //$NON-NLS-2$
        codiUsuari = null;
    }

    Collection<MaquinaEntity> maquines = null;

    LinkedList<Parameter> params = new LinkedList<Parameter>();
    // Realizamos la siguiente consulta (sin tener cuenta el alias)
    String query = "select distinct maquina from " //$NON-NLS-1$
            + " es.caib.seycon.ng.model.SessioEntity sessio " //$NON-NLS-1$
            + " right outer join sessio.maquina as maquina " //$NON-NLS-1$
            + " left outer join sessio.usuari as usuari" + //$NON-NLS-1$
            " where maquina.deleted = false "; //$NON-NLS-1$
    if (nom != null) {
        query = query + "and maquina.nom like :nom "; //$NON-NLS-1$
        params.add(new Parameter("nom", nom)); //$NON-NLS-1$
    }
    if (sistemaOperatiu != null) {
        //            query = query + "and maquina.oldSistemaOperatiu like :sistemaOperatiu "
        //            + "or maquina.operatingSystem = :operatingSystem ";
        //            params.add(new Parameter("sistemaOperatiu", sistemaOperatiu)); //$NON-NLS-1$
        query = query + "and maquina.operatingSystem.name = :operatingSystem "; //$NON-NLS-1$
        params.add(new Parameter("operatingSystem", sistemaOperatiu)); //$NON-NLS-1$
    }
    if (adreca != null) {
        query = query + "and maquina.adreca like :adreca "; //$NON-NLS-1$
        params.add(new Parameter("adreca", adreca)); //$NON-NLS-1$
    }
    if (dhcp != null) {
        query = query + "and maquina.dhcp like :dhcp "; //$NON-NLS-1$
        params.add(new Parameter("adreca", adreca)); //$NON-NLS-1$
    }
    if (correu != null) {
        query = query + "and maquina.correu like :correu "; //$NON-NLS-1$
        params.add(new Parameter("correu", correu)); //$NON-NLS-1$
    }
    if (ofimatica != null) {
        query = query + "and maquina.ofimatica like :ofimatica) "; //$NON-NLS-1$
        params.add(new Parameter("ofimatica", ofimatica)); //$NON-NLS-1$
    }
    if (mac != null) {
        query = query + "and maquina.mac like :mac "; //$NON-NLS-1$
        params.add(new Parameter("mac", mac)); //$NON-NLS-1$
    }
    if (descripcio != null) {
        query = query + "and maquina.descripcio like :descripcio "; //$NON-NLS-1$
        params.add(new Parameter("descripcio", descripcio)); //$NON-NLS-1$
    }
    if (xarxa != null) {
        query = query + "and maquina.xarxa.codi like :xarxa "; //$NON-NLS-1$
        params.add(new Parameter("xarxa", xarxa)); //$NON-NLS-1$
    }
    if (codiUsuari != null) {
        query = query + "and usuari.codi like :codiUsuari "; //$NON-NLS-1$
        params.add(new Parameter("codiUsuari", codiUsuari)); //$NON-NLS-1$
    }
    query = query + "order by maquina.nom "; //$NON-NLS-1$

    maquines = getMaquinaEntityDao().query(query, params.toArray(new Parameter[0]));

    // Filtramos por alias (si se ha especificado algn valor)
    if (alias != null) {
        Collection<AliasMaquinaEntity> maquinesAlias = getAliasMaquinaEntityDao().findMaquinaByAlias(alias);
        HashSet<Long> h_maquinesAlias = new HashSet(maquinesAlias.size());
        for (Iterator it = maquinesAlias.iterator(); it.hasNext();) {
            MaquinaEntity maqAlias = (MaquinaEntity) it.next();
            h_maquinesAlias.add(maqAlias.getId());
        }
        // Nos quedamos slo con las mquinas de la bsqueda que tengan el
        // alias indicado
        for (Iterator it = maquines.iterator(); it.hasNext();) {
            MaquinaEntity maq = (MaquinaEntity) it.next();
            if (!h_maquinesAlias.contains(maq.getId()))
                it.remove(); // Lo eliminamos (no tiene el alias buscado)
        }

    }
    return getMaquinaEntityDao().toMaquinaList(maquines);
}

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

public OnlineFileListener(ThreadGroup mainGroup, Configurator configurator) throws Exception {
    super(mainGroup, "File listener");
    this.configurator = configurator;

    // Get polling times
    long timeout = configurator.getConfigProperty(Configurator.FILE_POLLING_FILE, 10000L);
    if (timeout < 1000L) {
        log.warn("The fastest file polling period is '1 sec'!");
        timeout = 1000L;/*from w  w  w  . j a va 2 s  . c o  m*/
    }
    filePollingTime = timeout;
    timeout = configurator.getConfigProperty(Configurator.FILE_POLLING_GOOGLE, 600000L);
    if (timeout < 180000L) {
        log.warn("The fastest Google Calendar polling period is '3 min'!");
        timeout = 180000L;
    }
    googlePollingTime = timeout;

    // Get reloader script's path
    reloaderScript = configurator.getConfigProperty(Configurator.FILE_RELOADER_SCRIPT, null);

    // Get parameters
    LinkedList iCalFileList = new LinkedList();
    LinkedList usernameList = new LinkedList();
    LinkedList passwordList = new LinkedList();
    LinkedList urlList = new LinkedList();
    String parameterPostfix;
    int gapCounter = 0;
    for (int j, i = 1;; i++) {

        // Create parameter postfix [..n]
        if (i == 1) {
            parameterPostfix = "";
        } else {
            parameterPostfix = Integer.toString(i);
        }
        if (configurator.getConfigProperty(Configurator.FILE_ICAL_PATH + parameterPostfix, null) == null) {
            if (gapCounter < MAX_INDEX_GAP) {
                gapCounter++;
                continue;
            }
            break;
        }
        gapCounter = 0;

        // Get local file path
        String filePath = configurator.getConfigProperty(Configurator.FILE_ICAL_PATH + parameterPostfix,
                "/google" + i + ".ics");
        if (filePath.startsWith("~")) {
            filePath = filePath.substring(1);
        }
        if (filePath.endsWith("/*.ics")) {
            filePath = filePath.substring(0, filePath.length() - 6);
        }
        log.info("Start listening file " + filePath + "...");
        File iCalFile = new File(filePath);

        // Get username
        String username = configurator.getConfigProperty(Configurator.FILE_GOOGLE_USERNAME + parameterPostfix,
                null);

        // Get password
        String password = null;
        if (configurator.getConfigProperty(Configurator.FILE_GOOGLE_PASSWORD + parameterPostfix,
                null) != null) {
            password = configurator.getPasswordProperty(Configurator.FILE_GOOGLE_PASSWORD + parameterPostfix);
        }

        // Get calendar URL
        String url = configurator.getConfigProperty(Configurator.FILE_PRIVATE_ICAL_URL + parameterPostfix,
                null);

        // Verify parameters
        if (url == null) {
            throw new NullPointerException("Missing private ICAL URL (" + Configurator.FILE_PRIVATE_ICAL_URL
                    + parameterPostfix + ")!");
        }
        if (!configurator.isFeedConverterEnabled()) {
            if (username == null) {
                throw new NullPointerException(
                        "Missing username (" + Configurator.FILE_GOOGLE_USERNAME + parameterPostfix + ")!");
            }
            if (password == null) {
                throw new NullPointerException(
                        "Missing password (" + Configurator.FILE_GOOGLE_PASSWORD + parameterPostfix + ")!");
            }
            j = url.indexOf("/calendar");
            if (j > 0) {
                url = url.substring(j);
            }
            if (url.charAt(0) != '/') {
                throw new NullPointerException("Invalid private ICAL URL (" + Configurator.FILE_PRIVATE_ICAL_URL
                        + parameterPostfix + ")!");
            }
            j = url.indexOf('@');
            if (j != -1) {
                url = url.substring(0, j) + "%40" + url.substring(j + 1);
            }
            j = url.indexOf("googlemail.com");
            if (j != -1) {
                url = url.substring(0, j) + "gmail.com" + url.substring(j + 14);
            }
        } else {
            if (url.startsWith("calendar/")) {
                url = '/' + url;
            }
        }

        // Add parameters to lists
        iCalFileList.addLast(iCalFile);
        usernameList.addLast(username);
        passwordList.addLast(password);
        urlList.addLast(url);
    }

    // Create object arrays
    iCalFiles = new File[iCalFileList.size()];
    usernames = new String[usernameList.size()];
    passwords = new String[passwordList.size()];
    urls = new String[urlList.size()];
    iCalFileList.toArray(iCalFiles);
    usernameList.toArray(usernames);
    passwordList.toArray(passwords);
    urlList.toArray(urls);
    log.info("File listener started successfully.");

    // Start listener
    start();
}

From source file:org.pdfsam.plugin.split.listeners.RunButtonActionListener.java

public void actionPerformed(ActionEvent e) {

    if (WorkExecutor.getInstance().getRunningThreads() > 0 || panel.getSelectionPanel().isAdding()) {
        DialogUtility.showWarningAddingDocument(panel);
        return;/*from w  ww.ja  va2 s.  c o m*/
    }
    if (!panel.getSameAsSourceRadio().isSelected()
            && StringUtils.isEmpty(panel.getDestinationFolderText().getText())) {
        DialogUtility.showWarningNoDestinationSelected(panel, DialogUtility.DIRECTORY_DESTINATION);
        return;
    }
    PdfSelectionTableItem[] items = panel.getSelectionPanel().getTableRows();
    if (items == null || items.length != 1) {
        DialogUtility.showWarningNoDocsSelected(panel, DialogUtility.ONE_DOC);
        return;
    }
    LinkedList<String> args = new LinkedList<String>();
    try {
        PdfSelectionTableItem item = null;
        // overwrite confirmation
        if (panel.getOverwriteCheckbox().isSelected()
                && Configuration.getInstance().isAskOverwriteConfirmation()) {
            int dialogRet = DialogUtility.askForOverwriteConfirmation(panel);
            if (JOptionPane.NO_OPTION == dialogRet) {
                panel.getOverwriteCheckbox().setSelected(false);
            } else if (JOptionPane.CANCEL_OPTION == dialogRet) {
                return;
            }
        }

        item = items[0];
        args.add("-" + SplitParsedCommand.F_ARG);
        String f = item.getInputFile().getAbsolutePath();
        if ((item.getPassword()) != null && (item.getPassword()).length() > 0) {
            log.debug(GettextResource.gettext(Configuration.getInstance().getI18nResourceBundle(),
                    "Found a password for input file."));
            f += ":" + item.getPassword();
        }
        args.add(f);

        args.add("-" + SplitParsedCommand.P_ARG);
        args.add(panel.getOutPrefixText().getText());
        args.add("-" + SplitParsedCommand.S_ARG);
        String splitType = panel.getSplitType();
        args.add(splitType);
        // check if is needed page option
        if (splitType.equals(SplitParsedCommand.S_SPLIT)) {
            args.add("-" + SplitParsedCommand.N_ARG);
            args.add(panel.getThisPageTextField().getText());
        } else if (splitType.equals(SplitParsedCommand.S_NSPLIT)) {
            args.add("-" + SplitParsedCommand.N_ARG);
            args.add(panel.getnPagesTextField().getText());
        } else if (splitType.equals(SplitParsedCommand.S_SIZE)) {
            args.add("-" + SplitParsedCommand.B_ARG);
            if (panel.getSplitSizeCombo().isSelectedItem() && panel.getSplitSizeCombo().isValidSelectedItem()) {
                args.add(Long.toString(panel.getSplitSizeCombo().getSelectedBytes()));
            } else {
                throw new Exception(GettextResource.gettext(Configuration.getInstance().getI18nResourceBundle(),
                        "Invalid split size"));
            }
        } else if (splitType.equals(SplitParsedCommand.S_BLEVEL)) {
            args.add("-" + SplitParsedCommand.BL_ARG);
            args.add((String) panel.getbLevelCombo().getSelectedItem());
        }

        args.add("-" + SplitParsedCommand.O_ARG);
        // check radio for output options
        if (panel.getSameAsSourceRadio().isSelected()) {
            if (item != null) {
                args.add(item.getInputFile().getParent());
            }
        } else {
            if (StringUtils.isEmpty(panel.getDestinationFolderText().getText())) {
                String suggestedDir = getSuggestedDestinationDirectory(item);
                int chosenOpt = DialogUtility.showConfirmOuputLocationDialog(panel, suggestedDir);
                if (JOptionPane.YES_OPTION == chosenOpt) {
                    panel.getDestinationFolderText().setText(suggestedDir);
                } else if (JOptionPane.CANCEL_OPTION == chosenOpt) {
                    return;
                }

            }
            args.add(panel.getDestinationFolderText().getText());
        }
        if (panel.getOverwriteCheckbox().isSelected())
            args.add("-" + SplitParsedCommand.OVERWRITE_ARG);
        if (panel.getOutputCompressedCheck().isSelected())
            args.add("-" + SplitParsedCommand.COMPRESSED_ARG);
        args.add("-" + SplitParsedCommand.PDFVERSION_ARG);
        if (JPdfVersionCombo.SAME_AS_SOURCE
                .equals(((StringItem) panel.getVersionCombo().getSelectedItem()).getId())) {
            StringItem minItem = panel.getVersionCombo().getMinItem();
            String currentPdfVersion = Character.toString(item.getPdfVersion());
            if (minItem != null) {
                if (Integer.parseInt(currentPdfVersion) < Integer.parseInt(minItem.getId())) {
                    if (JOptionPane.YES_OPTION != DialogUtility.askForPdfVersionConfilct(panel,
                            minItem.getDescription())) {
                        return;
                    }
                }
            }
            args.add(currentPdfVersion);
        } else {
            args.add(((StringItem) panel.getVersionCombo().getSelectedItem()).getId());
        }
        args.add(AbstractParsedCommand.COMMAND_SPLIT);

        String[] myStringArray = args.toArray(new String[args.size()]);
        WorkExecutor.getInstance().execute(new WorkThread(myStringArray));

    } catch (Exception ex) {
        log.error(GettextResource.gettext(Configuration.getInstance().getI18nResourceBundle(), "Error: "), ex);
        SoundPlayer.getInstance().playErrorSound();
    }

}

From source file:org.pdfsam.plugin.docinfo.listeners.RunButtonActionListener.java

@Override
public void actionPerformed(ActionEvent e) {
    if (WorkExecutor.getInstance().getRunningThreads() > 0 || panel.getSelectionPanel().isAdding()) {
        DialogUtility.showWarningAddingDocument(panel);
        return;//from  w ww.  jav a 2  s.c  om
    }
    PdfSelectionTableItem[] items = panel.getSelectionPanel().getTableRows();
    if (items == null || items.length != 1) {
        DialogUtility.showWarningNoDocsSelected(panel, DialogUtility.ONE_DOC);
        return;
    }
    if (StringUtils.isEmpty(panel.getDestinationTextField().getText())
            && !panel.getSameAsSourceRadio().isSelected()) {
        DialogUtility.showWarningNoDestinationSelected(panel, DialogUtility.FILE_DESTINATION);
        return;
    }
    LinkedList<String> args = new LinkedList<String>();
    try {
        PdfSelectionTableItem item = null;
        item = items[0];
        String destination = "";

        if (panel.getSameAsSourceRadio().isSelected()) {
            destination = item.getInputFile().getAbsolutePath();
        } else {
            // overwrite confirmation
            if (panel.getOverwriteCheckbox().isSelected()
                    && Configuration.getInstance().isAskOverwriteConfirmation()) {
                int dialogRet = DialogUtility.askForOverwriteConfirmation(panel);
                if (JOptionPane.NO_OPTION == dialogRet) {
                    panel.getOverwriteCheckbox().setSelected(false);
                } else if (JOptionPane.CANCEL_OPTION == dialogRet) {
                    return;
                }
            }

            ensurePdfExtensionOnTextField(panel.getDestinationTextField());
            destination = panel.getDestinationTextField().getText();
            File destinationDir = new File(destination);
            File parent = destinationDir.getParentFile();
            if (!(parent != null && parent.exists())) {
                String suggestedDir = getSuggestedOutputFile(items[items.length - 1], destinationDir.getName());
                int chosenOpt = DialogUtility.showConfirmOuputLocationDialog(panel, suggestedDir);
                if (JOptionPane.YES_OPTION == chosenOpt) {
                    destination = suggestedDir;
                } else if (JOptionPane.CANCEL_OPTION == chosenOpt) {
                    return;
                }
            }
        }
        panel.getDestinationTextField().setText(destination);

        // check if the file already exists and the user didn't select to overwrite
        File destFile = (destination != null) ? new File(destination) : null;
        if (destFile != null && destFile.exists() && !panel.getOverwriteCheckbox().isSelected()) {
            int chosenOpt = DialogUtility.askForOverwriteOutputFileDialog(panel, destFile.getName());
            if (JOptionPane.YES_OPTION == chosenOpt) {
                panel.getOverwriteCheckbox().setSelected(true);
            } else if (JOptionPane.CANCEL_OPTION == chosenOpt) {
                return;
            }
        }

        args.add("-" + DocumentInfoParsedCommand.O_ARG);
        args.add(destination);

        args.add("-" + DocumentInfoParsedCommand.TITLE_ARG);
        args.add(panel.getTitleTextField().getText());

        args.add("-" + DocumentInfoParsedCommand.AUTHOR_ARG);
        args.add(panel.getAuthorTextField().getText());

        args.add("-" + DocumentInfoParsedCommand.SUBJECT_ARG);
        args.add(panel.getSubjectTextField().getText());

        args.add("-" + DocumentInfoParsedCommand.KEYWORDS_ARG);
        args.add(panel.getKeywordsTextField().getText());

        if (panel.getOverwriteCheckbox().isSelected())
            args.add("-" + DocumentInfoParsedCommand.OVERWRITE_ARG);
        if (panel.getOutputCompressedCheck().isSelected())
            args.add("-" + DocumentInfoParsedCommand.COMPRESSED_ARG);

        args.add("-" + SplitParsedCommand.PDFVERSION_ARG);
        if (JPdfVersionCombo.SAME_AS_SOURCE
                .equals(((StringItem) panel.getVersionCombo().getSelectedItem()).getId())) {
            StringItem minItem = panel.getVersionCombo().getMinItem();
            String currentPdfVersion = Character.toString(item.getPdfVersion());
            if (minItem != null) {
                if (Integer.parseInt(currentPdfVersion) < Integer.parseInt(minItem.getId())) {
                    if (JOptionPane.YES_OPTION != DialogUtility.askForPdfVersionConfilct(panel,
                            minItem.getDescription())) {
                        return;
                    }
                }
            }
            args.add(currentPdfVersion);
        } else {
            args.add(((StringItem) panel.getVersionCombo().getSelectedItem()).getId());
        }

        args.add("-" + DocumentInfoParsedCommand.F_ARG);
        String f = item.getInputFile().getAbsolutePath();
        if ((item.getPassword()) != null && (item.getPassword()).length() > 0) {
            log.debug(GettextResource.gettext(Configuration.getInstance().getI18nResourceBundle(),
                    "Found a password for input file."));
            f += ":" + item.getPassword();
        }
        args.add(f);

        args.add(AbstractParsedCommand.COMMAND_SETDOCINFO);

        String[] myStringArray = args.toArray(new String[args.size()]);
        WorkExecutor.getInstance().execute(new WorkThread(myStringArray));
    } catch (Exception ex) {
        log.error(GettextResource.gettext(Configuration.getInstance().getI18nResourceBundle(), "Error: "), ex);
        SoundPlayer.getInstance().playErrorSound();
    }
}

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

final byte[] syncronizeNow(CachedCalendar calendar) throws Exception {
    log.debug("Starting Google Calendar synchronizer...");

    // Create processing variables
    boolean remoteEventChanged;
    Event entry;//from  w  w  w.  ja  va  2s .c  om
    String uid, remoteUID;
    long remoteDate;
    Long storedDate;
    VEvent event;
    int i;

    // Load offline history
    loadEventRegistry();

    // Get historical parameters
    HashMap uids = (HashMap) eventRegistry.get(calendar.url);
    if (uids == null) {
        uids = new HashMap();
    }

    // Processed unique IDs
    HashSet processedUids = new HashSet();

    // Parse ics files
    Calendar localCalendar = ICalUtilities.parseCalendar(calendar.body);
    Calendar remoteCalendar = ICalUtilities.parseCalendar(calendar.previousBody);

    // Get local and remote changes
    VEvent[] localChanges = ICalUtilities.getNewEvents(remoteCalendar, localCalendar, true, calendar.url);
    VEvent[] remoteChanges = ICalUtilities.getNewEvents(localCalendar, remoteCalendar, false, null);

    // Updatable and removable events
    LinkedList insertableList = new LinkedList();
    LinkedList updatableList = new LinkedList();
    LinkedList removableList = new LinkedList();

    // Process local changes
    for (i = 0; i < localChanges.length; i++) {
        event = localChanges[i];
        uid = ICalUtilities.getUid(event);
        if (uid == null) {
            log.error("Invalid ical file (missing event ID)!");
            continue;
        }

        // Find remote pair
        entry = GCalUtilities.findEvent(calendar, event);
        if (entry == null) {
            if (uids.containsKey(uid)) {

                // Event removed at Google side -> download & remove
                if (log.isDebugEnabled()) {
                    log.debug("Removed event (" + ICalUtilities.getEventTitle(event)
                            + ") found in the Google Calendar.");
                }
            } else {

                // New local event -> insert
                if (log.isDebugEnabled()) {
                    log.debug("New event (" + ICalUtilities.getEventTitle(event)
                            + ") found in the local calendar.");
                }
                insertableList.addLast(event);
            }
        } else {

            // Add local and remote ID to processed UIDs
            processedUids.add(entry.getId());

            // Get remote event's modification date
            remoteDate = entry.getUpdated().getValue();
            storedDate = (Long) uids.get(uid);
            remoteEventChanged = true;
            if (storedDate == null) {
                remoteUID = GCalUtilities.getRemoteUID(calendar, uid);
                if (remoteUID != null) {
                    storedDate = (Long) uids.get(remoteUID);
                }
            }
            if (storedDate != null) {

                // FIXME If a 'reminder' changes in GCal singly,
                // Google Calendar does NOT update the LAST_MODIFIED
                // timestamp. Otherwise this comparison works.
                // there is no ms info in ics file
                remoteEventChanged = storedDate.longValue() != remoteDate / 1000 * 1000;
            }
            if (remoteEventChanged) {

                // Event modified at Google side -> download & update
                if (log.isDebugEnabled()) {
                    log.debug("Updated event (" + ICalUtilities.getEventTitle(event)
                            + ") found in the Google Calendar.");
                }
            } else {

                // Local event modified -> update
                if (log.isDebugEnabled()) {
                    log.debug("Updated event (" + ICalUtilities.getEventTitle(event)
                            + ") found in the local calendar.");
                }
                updatableList.addLast(event);
            }
        }
    }

    // Process remote changes
    for (i = 0; i < remoteChanges.length; i++) {
        event = remoteChanges[i];

        // Verify remote ID
        entry = GCalUtilities.findEvent(calendar, event);
        if (entry == null || processedUids.contains(entry.getId())) {
            continue;
        }

        // Verify local ID
        uid = ICalUtilities.getUid(event);
        if (uid == null) {
            log.error("Invalid ical file (missing event ID)!");
            continue;
        }

        // Find ID in history
        if (uids.containsKey(uid)) {

            // Local event removed -> remove event
            if (log.isDebugEnabled()) {
                log.debug("Removed event (" + ICalUtilities.getEventTitle(event)
                        + ") found in the local calendar.");
            }
            removableList.addLast(event);
        } else {

            // New remote event -> download & create
            if (log.isDebugEnabled()) {
                log.debug(
                        "New event (" + ICalUtilities.getEventTitle(event) + ") found in the Google Calendar.");
            }
        }
    }

    // Check changes
    if (localChanges.length == 0 && remoteChanges.length == 0) {

        // Save offline registry
        saveEventRegistry(calendar.url, calendar.previousBody);

        // Return previous body
        return calendar.previousBody;
    }

    // Show progress monitor
    if (monitor != null) {
        monitor.setVisible(true);
    }
    try {

        // Do modifications
        if (!removableList.isEmpty() && deleteEnabled) {

            // Remove Google entries
            VEvent[] events = new VEvent[removableList.size()];
            removableList.toArray(events);
            GCalUtilities.removeEvents(calendar, events);
        }
        VTimeZone[] timeZones;
        if (!updatableList.isEmpty() || !insertableList.isEmpty()) {

            // Get timezones
            timeZones = ICalUtilities.getTimeZones(localCalendar);
        } else {
            timeZones = new VTimeZone[0];
        }
        if (!updatableList.isEmpty()) {

            // Update Google entries
            VEvent[] events = new VEvent[updatableList.size()];
            updatableList.toArray(events);
            GCalUtilities.updateEvents(calendar, timeZones, events);
        }
        if (!insertableList.isEmpty()) {

            // Insert new Google entries
            VEvent[] events = new VEvent[insertableList.size()];
            insertableList.toArray(events);
            GCalUtilities.insertEvents(calendar, timeZones, events);
        }

        // Load new calendar from Google
        byte[] newBytes = GCalUtilities.loadCalendar(calendar);

        // Save offline registry
        saveEventRegistry(calendar.url, newBytes);

        // Return new ics file
        return newBytes;
    } finally {

        // Hide progress monitor
        if (monitor != null) {
            try {
                monitor.setVisible(false);
            } catch (Throwable ignored) {
            }
        }
    }
}

From source file:edu.umn.msi.tropix.persistence.service.impl.TropixObjectServiceImpl.java

public PermissionReport[] getPermissionReports(final String cagridId, final String objectId) {
    final LinkedList<PermissionReport> reports = new LinkedList<PermissionReport>();
    final TropixObject object = getTropixObjectDao().loadTropixObject(objectId);
    if (object instanceof VirtualFolder && ((VirtualFolder) object).getRoot()) {
        final Map<String, PermissionReport> userReports = new HashMap<String, PermissionReport>();
        final PermissionReport ownerReport = getPermissionReport(getTropixObjectDao().getOwner(object.getId()));
        ownerReport.setPermission(PermissionType.Owner);
        reports.add(ownerReport);/* w ww.j a v a2  s .co  m*/
        userReports.put(ownerReport.getId(), ownerReport);

        for (final User writeUser : getTropixObjectDao().getVirtualPermissionUsers(objectId, "write")) {
            if (!userReports.containsKey(writeUser.getCagridId())) {
                final PermissionReport report = getPermissionReport(writeUser);
                report.setPermission(PermissionType.Write);
                reports.add(report);
                userReports.put(report.getId(), report);
            }
        }
        for (final User readUser : getTropixObjectDao().getVirtualPermissionUsers(objectId, "read")) {
            if (!userReports.containsKey(readUser.getCagridId())) {
                final PermissionReport report = getPermissionReport(readUser);
                report.setPermission(PermissionType.Read);
                reports.add(report);
            }
        }

        final Map<String, PermissionReport> groupReports = new HashMap<String, PermissionReport>();
        for (final Group writeGroup : getTropixObjectDao().getVirtualPermissionGroups(objectId, "write")) {
            final PermissionReport report = getPermissionReport(writeGroup);
            report.setPermission(PermissionType.Write);
            reports.add(report);
            groupReports.put(report.getId(), report);
        }
        for (final Group readGroup : getTropixObjectDao().getVirtualPermissionGroups(objectId, "read")) {
            final String groupId = readGroup.getId();
            if (!groupReports.containsKey(groupId)) {
                final PermissionReport report = getPermissionReport(readGroup);
                report.setPermission(PermissionType.Read);
                reports.add(report);
            }
        }
    } else if (!(object instanceof VirtualFolder)) {
        final Map<String, PermissionReport> userReports = new HashMap<String, PermissionReport>();
        final Map<String, PermissionReport> groupReports = new HashMap<String, PermissionReport>();
        final Collection<DirectPermission> permissions = getTropixObjectDao().getRoles(objectId);

        for (final DirectPermission permission : permissions) {
            for (final User user : permission.getUsers()) {
                final String userId = user.getCagridId();
                if (userReports.containsKey(userId)) {
                    final PermissionReport report = userReports.get(userId);
                    report.setPermission(getStrongerPermission(getPermissionType(permission.getRole()),
                            report.getPermission()));
                } else {
                    final PermissionReport report = getPermissionReport(user);
                    report.setPermission(getPermissionType(permission.getRole()));
                    reports.add(report);
                    userReports.put(userId, report);
                }
            }

            for (final Group group : permission.getGroups()) {
                final String groupId = group.getId();
                if (groupReports.containsKey(groupId)) {
                    final PermissionReport report = groupReports.get(groupId);
                    report.setPermission(getStrongerPermission(getPermissionType(permission.getRole()),
                            report.getPermission()));
                } else {
                    final PermissionReport report = getPermissionReport(group);
                    report.setPermission(getPermissionType(permission.getRole()));
                    reports.add(report);
                    groupReports.put(groupId, report);
                }
            }
        }

        for (final VirtualFolder virtualFolder : object.getParentVirtualFolders()) {
            final PermissionReport report = new PermissionReport();
            report.setId(virtualFolder.getId());
            report.setName(getVirtualFolderPath(virtualFolder));
            report.setPermissionSource(PermissionSourceType.SharedFolder);
            reports.add(report);
        }
    }
    return reports.toArray(new PermissionReport[reports.size()]);
}

From source file:org.openscience.cdk.applications.taverna.weka.regression.EvaluateRegressionResultsAsPDFActivity.java

@Override
public void work() throws Exception {
    // Get input/* w  w  w  .  j  av a  2  s  . co  m*/
    String[] options = ((String) this.getConfiguration()
            .getAdditionalProperty(CDKTavernaConstants.PROPERTY_SCATTER_PLOT_OPTIONS)).split(";");
    List<File> modelFiles = this.getInputAsFileList(this.INPUT_PORTS[0]);
    List<Instances> trainDatasets = this.getInputAsList(this.INPUT_PORTS[1], Instances.class);
    List<Instances> testDatasets = null;
    if (options[0].equals("" + TEST_TRAININGSET_PORT)) {
        testDatasets = this.getInputAsList(this.INPUT_PORTS[2], Instances.class);
    } else {
        testDatasets = null;
    }
    String directory = modelFiles.get(0).getParent();

    // Do work
    ArrayList<String> resultFiles = new ArrayList<String>();
    HashMap<UUID, Double> orgClassMap = new HashMap<UUID, Double>();
    HashMap<UUID, Double> calcClassMap = new HashMap<UUID, Double>();
    WekaTools tools = new WekaTools();
    ChartTool chartTool = new ChartTool();
    List<Object> rmseCharts = new ArrayList<Object>();
    List<Double> trainMeanRMSE = new ArrayList<Double>();
    List<Double> testMeanRMSE = new ArrayList<Double>();
    List<Double> cvMeanRMSE = new ArrayList<Double>();
    DefaultCategoryDataset[] ratioRMSESet = new DefaultCategoryDataset[trainDatasets.size()];
    for (int i = 0; i < trainDatasets.size(); i++) {
        ratioRMSESet[i] = new DefaultCategoryDataset();
    }
    List<Double> trainingSetRatios = null;
    int fileIDX = 1;
    while (!modelFiles.isEmpty()) {
        trainingSetRatios = new ArrayList<Double>();
        List<Double> trainRMSE = new ArrayList<Double>();
        HashSet<Integer> trainSkippedRMSE = new HashSet<Integer>();
        List<Double> testRMSE = new ArrayList<Double>();
        HashSet<Integer> testSkippedRMSE = new HashSet<Integer>();
        List<Double> cvRMSE = new ArrayList<Double>();
        HashSet<Integer> cvSkippedRMSE = new HashSet<Integer>();
        List<Object> chartsObjects = new LinkedList<Object>();
        File modelFile = null;
        Classifier classifier = null;
        String name = "";
        for (int j = 0; j < trainDatasets.size(); j++) {
            LinkedList<Double> predictedValues = new LinkedList<Double>();
            LinkedList<Double> orgValues = new LinkedList<Double>();
            LinkedList<Double[]> yResidueValues = new LinkedList<Double[]>();
            LinkedList<String> yResidueNames = new LinkedList<String>();
            if (modelFiles.isEmpty()) {
                break;
            }
            calcClassMap.clear();
            modelFile = modelFiles.remove(0);
            classifier = (Classifier) SerializationHelper.read(modelFile.getPath());
            Instances testset = null;
            if (testDatasets != null) {
                testset = testDatasets.get(j);
            }
            name = classifier.getClass().getSimpleName();
            String sum = "Method: " + name + " " + tools.getOptionsFromFile(modelFile, name) + "\n\n";
            // Produce training set data
            Instances trainset = trainDatasets.get(j);
            Instances trainUUIDSet = Filter.useFilter(trainset, tools.getIDGetter(trainset));
            trainset = Filter.useFilter(trainset, tools.getIDRemover(trainset));
            double trainingSetRatio = 1.0;
            if (testset != null) {
                trainingSetRatio = trainset.numInstances()
                        / (double) (trainset.numInstances() + testset.numInstances());
            }
            trainingSetRatios.add(trainingSetRatio * 100);
            // Predict
            for (int k = 0; k < trainset.numInstances(); k++) {
                UUID uuid = UUID.fromString(trainUUIDSet.instance(k).stringValue(0));
                orgClassMap.put(uuid, trainset.instance(k).classValue());
                calcClassMap.put(uuid, classifier.classifyInstance(trainset.instance(k)));
            }
            // Evaluate
            Evaluation trainEval = new Evaluation(trainset);
            trainEval.evaluateModel(classifier, trainset);
            // Chart data
            DefaultXYDataset xyDataSet = new DefaultXYDataset();
            String trainSeries = "Training Set (RMSE: "
                    + String.format("%.2f", trainEval.rootMeanSquaredError()) + ")";
            XYSeries series = new XYSeries(trainSeries);
            Double[] yTrainResidues = new Double[trainUUIDSet.numInstances()];
            Double[] orgTrain = new Double[trainUUIDSet.numInstances()];
            Double[] calc = new Double[trainUUIDSet.numInstances()];
            for (int k = 0; k < trainUUIDSet.numInstances(); k++) {
                UUID uuid = UUID.fromString(trainUUIDSet.instance(k).stringValue(0));
                orgTrain[k] = orgClassMap.get(uuid);
                calc[k] = calcClassMap.get(uuid);
                if (calc[k] != null && orgTrain[k] != null) {
                    series.add(orgTrain[k].doubleValue(), calc[k]);
                    yTrainResidues[k] = calc[k].doubleValue() - orgTrain[k].doubleValue();
                } else {
                    ErrorLogger.getInstance().writeError("Can't find value for UUID: " + uuid.toString(),
                            this.getActivityName());
                    throw new CDKTavernaException(this.getActivityName(),
                            "Can't find value for UUID: " + uuid.toString());
                }
            }
            orgValues.addAll(Arrays.asList(orgTrain));
            predictedValues.addAll(Arrays.asList(calc));
            CollectionUtilities.sortTwoArrays(orgTrain, yTrainResidues);
            yResidueValues.add(yTrainResidues);
            yResidueNames.add(trainSeries);
            xyDataSet.addSeries(trainSeries, series.toArray());

            // Summary
            sum += "Training Set:\n";
            if (trainEval.rootRelativeSquaredError() > 300) {
                trainSkippedRMSE.add(j);
            }
            trainRMSE.add(trainEval.rootMeanSquaredError());
            sum += trainEval.toSummaryString(true);
            // Produce test set data
            if (testset != null) {
                Instances testUUIDSet = Filter.useFilter(testset, tools.getIDGetter(testset));
                testset = Filter.useFilter(testset, tools.getIDRemover(testset));
                // Predict
                for (int k = 0; k < testset.numInstances(); k++) {
                    UUID uuid = UUID.fromString(testUUIDSet.instance(k).stringValue(0));
                    orgClassMap.put(uuid, testset.instance(k).classValue());
                    calcClassMap.put(uuid, classifier.classifyInstance(testset.instance(k)));
                }
                // Evaluate
                Evaluation testEval = new Evaluation(testset);
                testEval.evaluateModel(classifier, testset);
                // Chart data
                String testSeries = "Test Set (RMSE: " + String.format("%.2f", testEval.rootMeanSquaredError())
                        + ")";
                series = new XYSeries(testSeries);
                Double[] yTestResidues = new Double[testUUIDSet.numInstances()];
                Double[] orgTest = new Double[testUUIDSet.numInstances()];
                calc = new Double[testUUIDSet.numInstances()];
                for (int k = 0; k < testUUIDSet.numInstances(); k++) {
                    UUID uuid = UUID.fromString(testUUIDSet.instance(k).stringValue(0));
                    orgTest[k] = orgClassMap.get(uuid);
                    calc[k] = calcClassMap.get(uuid);
                    if (calc[k] != null && orgTest[k] != null) {
                        series.add(orgTest[k].doubleValue(), calc[k].doubleValue());
                        yTestResidues[k] = calc[k].doubleValue() - orgTest[k].doubleValue();
                    } else {
                        ErrorLogger.getInstance().writeError("Can't find value for UUID: " + uuid.toString(),
                                this.getActivityName());
                        throw new CDKTavernaException(this.getActivityName(),
                                "Can't find value for UUID: " + uuid.toString());
                    }
                }
                orgValues.addAll(Arrays.asList(orgTest));
                predictedValues.addAll(Arrays.asList(calc));
                CollectionUtilities.sortTwoArrays(orgTest, yTestResidues);
                yResidueValues.add(yTestResidues);
                yResidueNames.add(testSeries);
                xyDataSet.addSeries(testSeries, series.toArray());
                // Create summary
                sum += "\nTest Set:\n";
                if (testEval.rootRelativeSquaredError() > 300) {
                    testSkippedRMSE.add(j);
                }
                testRMSE.add(testEval.rootMeanSquaredError());
                sum += testEval.toSummaryString(true);
            }
            // Produce cross validation data
            if (Boolean.parseBoolean(options[1])) {
                Evaluation cvEval = new Evaluation(trainset);
                if (testset != null) {
                    Instances fullSet = tools.getFullSet(trainset, testset);
                    cvEval.crossValidateModel(classifier, fullSet, 10, new Random(1));
                } else {
                    cvEval.crossValidateModel(classifier, trainset, 10, new Random(1));
                }
                sum += "\n10-fold cross-validation:\n";
                if (cvEval.rootRelativeSquaredError() > 300) {
                    cvSkippedRMSE.add(j);
                }
                cvRMSE.add(cvEval.rootMeanSquaredError());
                sum += cvEval.toSummaryString(true);
            }

            // Create scatter plot
            String header = classifier.getClass().getSimpleName() + "\n Training set ratio: "
                    + String.format("%.2f", trainingSetRatios.get(j)) + "%" + "\n Model name: "
                    + modelFile.getName();
            chartsObjects
                    .add(chartTool.createScatterPlot(xyDataSet, header, "Original values", "Predicted values"));
            // Create residue plot
            chartsObjects.add(chartTool.createResiduePlot(yResidueValues, header, "Index",
                    "(Predicted - Original)", yResidueNames));
            // Create curve
            Double[] tmpOrg = new Double[orgValues.size()];
            tmpOrg = orgValues.toArray(tmpOrg);
            Double[] tmpPred = new Double[predictedValues.size()];
            tmpPred = predictedValues.toArray(tmpPred);
            CollectionUtilities.sortTwoArrays(tmpOrg, tmpPred);
            DefaultXYDataset dataSet = new DefaultXYDataset();
            String orgName = "Original";
            XYSeries orgSeries = new XYSeries(orgName);
            String predName = "Predicted";
            XYSeries predSeries = new XYSeries(predName);
            for (int k = 0; k < tmpOrg.length; k++) {
                orgSeries.add((k + 1), tmpOrg[k]);
                predSeries.add((k + 1), tmpPred[k]);
            }
            dataSet.addSeries(orgName, orgSeries.toArray());
            dataSet.addSeries(predName, predSeries.toArray());
            chartsObjects.add(chartTool.createXYLineChart(header, "Index", "Value", dataSet, true, false));
            // Add summary
            chartsObjects.add(sum);
        }
        // Create RMSE Plot
        DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
        double meanRMSE = 0;
        for (int i = 0; i < trainRMSE.size(); i++) {
            if (!trainSkippedRMSE.contains(i)) {
                dataSet.addValue(trainRMSE.get(i), "Training Set",
                        "(" + String.format("%.2f", trainingSetRatios.get(i)) + "%/" + (i + 1) + ")");
                ratioRMSESet[i].addValue(trainRMSE.get(i), "Training Set",
                        "(" + String.format("%.2f", trainingSetRatios.get(i)) + "%/" + (i + 1) + "/" + fileIDX
                                + ")");
            }
            meanRMSE += trainRMSE.get(i);
        }
        trainMeanRMSE.add(meanRMSE / trainRMSE.size());
        meanRMSE = 0;
        if (!testRMSE.isEmpty()) {
            for (int i = 0; i < testRMSE.size(); i++) {
                if (!testSkippedRMSE.contains(i)) {
                    dataSet.addValue(testRMSE.get(i), "Test Set",
                            "(" + String.format("%.2f", trainingSetRatios.get(i)) + "%/" + (i + 1) + ")");
                    ratioRMSESet[i].addValue(testRMSE.get(i), "Test Set",
                            "(" + String.format("%.2f", trainingSetRatios.get(i)) + "%/" + (i + 1) + "/"
                                    + fileIDX + ")");
                }
                meanRMSE += testRMSE.get(i);
            }
            testMeanRMSE.add(meanRMSE / testRMSE.size());
        }
        meanRMSE = 0;
        if (!cvRMSE.isEmpty()) {
            for (int i = 0; i < cvRMSE.size(); i++) {
                if (!cvSkippedRMSE.contains(i)) {
                    dataSet.addValue(cvRMSE.get(i), "10-fold Cross-validation",
                            "(" + String.format("%.2f", trainingSetRatios.get(i)) + "%/" + (i + 1) + ")");
                    ratioRMSESet[i].addValue(cvRMSE.get(i), "10-fold Cross-validation",
                            "(" + String.format("%.2f", trainingSetRatios.get(i)) + "%/" + (i + 1) + "/"
                                    + fileIDX + ")");
                }
                meanRMSE += cvRMSE.get(i);
            }
            cvMeanRMSE.add(meanRMSE / cvRMSE.size());
        }
        JFreeChart rmseChart = chartTool.createLineChart(
                "RMSE Plot\n Classifier:" + name + " " + tools.getOptionsFromFile(modelFile, name),
                "(Training set ratio/Set Index/File index)", "RMSE", dataSet, false, true);
        chartsObjects.add(rmseChart);
        rmseCharts.add(rmseChart);
        // Write PDF
        File file = FileNameGenerator.getNewFile(directory, ".pdf", "ScatterPlot");
        chartTool.writeChartAsPDF(file, chartsObjects);
        resultFiles.add(file.getPath());
        fileIDX++;
    }
    // Create set ratio RMSE plots
    for (int i = 0; i < ratioRMSESet.length; i++) {
        JFreeChart rmseChart = chartTool
                .createLineChart(
                        "Set RMSE plot\n" + "(" + String.format("%.2f", trainingSetRatios.get(i)) + "%/"
                                + (i + 1) + ")",
                        "(Training set ratio/Index)", "RMSE", ratioRMSESet[i], false, true);
        rmseCharts.add(rmseChart);
    }
    // Create mean RMSE plot
    DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
    for (int i = 0; i < trainMeanRMSE.size(); i++) {
        dataSet.addValue(trainMeanRMSE.get(i), "Training Set", "" + (i + 1));
    }
    for (int i = 0; i < testMeanRMSE.size(); i++) {
        dataSet.addValue(testMeanRMSE.get(i), "Test Set", "" + (i + 1));
    }
    for (int i = 0; i < cvMeanRMSE.size(); i++) {
        dataSet.addValue(cvMeanRMSE.get(i), "10-fold Cross-validation", "" + (i + 1));
    }
    JFreeChart rmseChart = chartTool.createLineChart("RMSE Mean Plot", "Dataset number", "Mean RMSE", dataSet);
    rmseCharts.add(rmseChart);
    File file = FileNameGenerator.getNewFile(directory, ".pdf", "RMSE-Sum");
    chartTool.writeChartAsPDF(file, rmseCharts);
    resultFiles.add(file.getPath());
    // Set output
    this.setOutputAsStringList(resultFiles, this.OUTPUT_PORTS[0]);
}

From source file:org.pdfsam.plugin.coverfooter.listeners.RunButtonActionListener.java

public void actionPerformed(ActionEvent e) {

    if (WorkExecutor.getInstance().getRunningThreads() > 0 || panel.getSelectionPanel().isAdding()) {
        DialogUtility.showWarningAddingDocument(panel);
        return;/*from  w  w w. ja v  a2s. co m*/
    }
    PdfSelectionTableItem[] items = panel.getSelectionPanel().getTableRows();
    if (ArrayUtils.isEmpty(items)) {
        DialogUtility.showWarningNoDocsSelected(panel, DialogUtility.AT_LEAST_ONE_DOC);
        return;
    }

    LinkedList<String> args = new LinkedList<String>();
    LinkedList<String> args1 = new LinkedList<String>();
    LinkedList<String> argsFooter = new LinkedList<String>();
    // validation and permission check are demanded
    try {
        if (panel.getOutputCompressedCheck().isSelected()) {
            args.add("-" + ConcatParsedCommand.COMPRESSED_ARG);
        }
        if (panel.getMergeTypeCheck().isSelected()) {
            args.add("-" + ConcatParsedCommand.COPYFIELDS_ARG);
        }

        args.add("-" + ConcatParsedCommand.PDFVERSION_ARG);
        args.add(((StringItem) panel.getVersionCombo().getSelectedItem()).getId());

        PdfSelectionTableItem[] coveritems = panel.getCoverSelectionPanel().getTableRows();
        PdfSelectionTableItem[] footeritems = panel.getFooterSelectionPanel().getTableRows();
        String coverSelectionString = "";
        // manage cover
        if ((coveritems == null || coveritems.length != 1)
                && (footeritems == null || footeritems.length != 1)) {
            JOptionPane.showMessageDialog(panel,
                    GettextResource.gettext(Configuration.getInstance().getI18nResourceBundle(),
                            "Select at least one cover or one footer"),
                    GettextResource.gettext(Configuration.getInstance().getI18nResourceBundle(), "Warning"),
                    JOptionPane.WARNING_MESSAGE);
        } else {

            // overwrite confirmation
            if (panel.getOverwriteCheckbox().isSelected()
                    && Configuration.getInstance().isAskOverwriteConfirmation()) {
                int dialogRet = DialogUtility.askForOverwriteConfirmation(panel);
                if (JOptionPane.NO_OPTION == dialogRet) {
                    panel.getOverwriteCheckbox().setSelected(false);
                } else if (JOptionPane.CANCEL_OPTION == dialogRet) {
                    return;
                }
            }
            if (panel.getOverwriteCheckbox().isSelected()) {
                args.add("-" + ConcatParsedCommand.OVERWRITE_ARG);
            }

            if ((coveritems != null && coveritems.length == 1)) {
                PdfSelectionTableItem coveritem = coveritems[0];
                String coverSelection = (coveritem.getPageSelection() != null
                        && coveritem.getPageSelection().length() > 0) ? coveritem.getPageSelection()
                                : CoverFooterMainGUI.ALL_STRING;
                if (coverSelection.trim().length() > 0 && coverSelection.indexOf(",") != 0) {
                    String[] selectionsArray = coverSelection.split(",");
                    for (int j = 0; j < selectionsArray.length; j++) {
                        String tmpString = selectionsArray[j].trim();
                        if ((tmpString != null) && (!tmpString.equals(""))) {
                            args.add("-" + ConcatParsedCommand.F_ARG);
                            String f = coveritem.getInputFile().getAbsolutePath();
                            if ((coveritem.getPassword()) != null && (coveritem.getPassword()).length() > 0) {
                                log.debug(GettextResource.gettext(
                                        Configuration.getInstance().getI18nResourceBundle(),
                                        "Found a password for input file."));
                                f += ":" + coveritem.getPassword();
                            }
                            args.add(f);
                            coverSelectionString += (tmpString.matches("[\\d]+"))
                                    ? tmpString + "-" + tmpString + ":"
                                    : tmpString + ":";
                        }
                    }

                } else {
                    args.add("-" + ConcatParsedCommand.F_ARG);
                    String f = coveritem.getInputFile().getAbsolutePath();
                    if ((coveritem.getPassword()) != null && (coveritem.getPassword()).length() > 0) {
                        log.debug(GettextResource.gettext(Configuration.getInstance().getI18nResourceBundle(),
                                "Found a password for input file."));
                        f += ":" + coveritem.getPassword();
                    }
                    args.add(f);
                    coverSelectionString += (coverSelection.matches("[\\d]+"))
                            ? coverSelection + "-" + coverSelection + ":"
                            : coverSelection + ":";
                }
            }
            String footerSelectionString = "";
            // manage footer
            if ((footeritems != null && footeritems.length == 1)) {
                PdfSelectionTableItem footeritem = footeritems[0];
                String footerSelection = (footeritem.getPageSelection() != null
                        && footeritem.getPageSelection().length() > 0) ? footeritem.getPageSelection()
                                : CoverFooterMainGUI.ALL_STRING;
                if (footerSelection.trim().length() > 0 && footerSelection.indexOf(",") != 0) {
                    String[] selectionsArray = footerSelection.split(",");
                    for (int j = 0; j < selectionsArray.length; j++) {
                        String tmpString = selectionsArray[j].trim();
                        if ((tmpString != null) && (!tmpString.equals(""))) {
                            argsFooter.add("-" + ConcatParsedCommand.F_ARG);
                            String footerItem = footeritem.getInputFile().getAbsolutePath();
                            if ((footeritem.getPassword()) != null && (footeritem.getPassword()).length() > 0) {
                                log.debug(GettextResource.gettext(
                                        Configuration.getInstance().getI18nResourceBundle(),
                                        "Found a password for input file."));
                                footerItem += ":" + footeritem.getPassword();
                            }
                            argsFooter.add(footerItem);
                            footerSelectionString += (tmpString.matches("[\\d]+"))
                                    ? tmpString + "-" + tmpString + ":"
                                    : tmpString + ":";
                        }
                    }

                } else {
                    argsFooter.add("-" + ConcatParsedCommand.F_ARG);
                    String footerItem = footeritem.getInputFile().getAbsolutePath();
                    if ((footeritem.getPassword()) != null && (footeritem.getPassword()).length() > 0) {
                        log.debug(GettextResource.gettext(Configuration.getInstance().getI18nResourceBundle(),
                                "Found a password for input file."));
                        footerItem += ":" + footeritem.getPassword();
                    }
                    argsFooter.add(footerItem);
                    footerSelectionString += (footerSelection.matches("[\\d]+"))
                            ? footerSelection + "-" + footerSelection + ":"
                            : footerSelection + ":";
                }
            }
            // selection page
            PdfSelectionTableItem item = null;
            for (int i = 0; i < items.length; i++) {
                String pageSelectionString = coverSelectionString;
                try {
                    args1.clear();
                    args1.addAll(args);

                    item = items[i];
                    String pageSelection = (item.getPageSelection() != null
                            && item.getPageSelection().length() > 0) ? item.getPageSelection()
                                    : CoverFooterMainGUI.ALL_STRING;
                    if (pageSelection.trim().length() > 0 && pageSelection.indexOf(",") != 0) {
                        String[] selectionsArray = pageSelection.split(",");
                        for (int j = 0; j < selectionsArray.length; j++) {
                            String tmpString = selectionsArray[j].trim();
                            if ((tmpString != null) && (!tmpString.equals(""))) {
                                args1.add("-" + ConcatParsedCommand.F_ARG);
                                String f = item.getInputFile().getAbsolutePath();
                                if ((item.getPassword()) != null && (item.getPassword()).length() > 0) {
                                    log.debug(GettextResource.gettext(
                                            Configuration.getInstance().getI18nResourceBundle(),
                                            "Found a password for input file."));
                                    f += ":" + item.getPassword();
                                }
                                args1.add(f);
                                pageSelectionString += (tmpString.matches("[\\d]+"))
                                        ? tmpString + "-" + tmpString + ":"
                                        : tmpString + ":";
                            }
                        }

                    } else {
                        args1.add("-" + ConcatParsedCommand.F_ARG);
                        String f = item.getInputFile().getAbsolutePath();
                        if ((item.getPassword()) != null && (item.getPassword()).length() > 0) {
                            log.debug(
                                    GettextResource.gettext(Configuration.getInstance().getI18nResourceBundle(),
                                            "Found a password for input file."));
                            f += ":" + item.getPassword();
                        }
                        args1.add(f);
                        pageSelectionString += (pageSelection.matches("[\\d]+"))
                                ? pageSelection + "-" + pageSelection + ":"
                                : pageSelection + ":";
                    }

                    args1.addAll(argsFooter);
                    args1.add("-" + ConcatParsedCommand.U_ARG);
                    args1.add(pageSelectionString + footerSelectionString);

                    // manage output destination option
                    args1.add("-" + ConcatParsedCommand.O_ARG);
                    if (StringUtils.isEmpty(panel.getDestinationTextField().getText())) {
                        String suggestedDir = getSuggestedDestinationDirectory(items[items.length - 1]);
                        int chosenOpt = DialogUtility.showConfirmOuputLocationDialog(panel, suggestedDir);
                        if (JOptionPane.YES_OPTION == chosenOpt) {
                            panel.getDestinationTextField().setText(suggestedDir);
                        } else if (JOptionPane.CANCEL_OPTION == chosenOpt) {
                            return;
                        }
                    }
                    if (panel.getDestinationTextField().getText().length() > 0) {
                        args1.add(panel.getDestinationTextField().getText() + File.separator
                                + item.getInputFile().getName());
                    }

                    args1.add(AbstractParsedCommand.COMMAND_CONCAT);

                    WorkExecutor.getInstance().execute(new WorkThread(args1.toArray(new String[args1.size()])));
                } catch (Exception ex) {
                    log.error(GettextResource.gettext(Configuration.getInstance().getI18nResourceBundle(),
                            "Error: "), ex);
                }
            }
        }
    } catch (Exception ex) {
        log.error(GettextResource.gettext(Configuration.getInstance().getI18nResourceBundle(), "Error: "), ex);
        SoundPlayer.getInstance().playErrorSound();
    }

}

From source file:org.opendaylight.vtn.manager.it.northbound.VtnNorthboundIT.java

/**
 * Test case for MAC mapping APIs./*from  w  ww  .  j  av  a 2  s  . c  o  m*/
 *
 * <p>
 *   This method is called by {@link #testVBridgeAPI(String, String)}.
 * </p>
 *
 * @param tname   The name of existing virtual tenant.
 * @param bname1  The name of existing vBridge.
 * @param bname2  The name of existing vBridge.
 * @throws JSONException  An error occurred.
 */
private void testMacMappingAPI(String tname, String bname1, String bname2) throws JSONException {
    LOG.info("Starting MAC Mapping JAX-RS client.");

    String qparam = "?param1=1&param2=2";
    String mapUri = createURI("default/vtns", tname, "vbridges", bname1, "macmap");
    String mapUri2 = createURI("default/vtns", tname, "vbridges", bname2, "macmap");

    // Ensure that no MAC mapping is configured.
    assertNoMacMapping(mapUri);
    assertNoMacMapping(mapUri2);

    LinkedList<String> allowedHosts = new LinkedList<String>();
    allowedHosts.add(null);
    allowedHosts.add(null);

    byte[] allowedAddr = { (byte) 0x10, (byte) 0x20, (byte) 0x30, (byte) 0x40, (byte) 0x50, (byte) 0x00, };

    for (int i = 0; i < 20; i++) {
        String mac;
        if ((i & 1) == 0) {
            mac = null;
        } else {
            allowedAddr[5] = (byte) i;
            mac = ByteUtils.toHexString(allowedAddr);
        }

        String vlan = (i == 0) ? "4095" : String.valueOf(i);
        allowedHosts.add(mac);
        allowedHosts.add(vlan);
    }

    LinkedList<String> deniedHosts = new LinkedList<String>();
    byte[] deniedAddr = { (byte) 0xf0, (byte) 0xf1, (byte) 0xf2, (byte) 0xf3, (byte) 0x00, (byte) 0xf5, };

    for (int i = 0; i < 20; i++) {
        deniedAddr[4] = (byte) i;
        String mac = ByteUtils.toHexString(deniedAddr);
        String vlan = String.valueOf(i + 100);
        deniedHosts.add(mac);
        deniedHosts.add(vlan);
    }
    deniedHosts.add("00:00:ff:ff:ff:0f");
    deniedHosts.add(null);

    // Install MAC mapping configuration.
    JSONObject config = createMacMapConfig(allowedHosts, deniedHosts);
    JSONObject configExpected = completeMacMapConfig(config);

    String cf = config.toString();
    getJsonResult(mapUri + qparam, HTTP_PUT, cf);
    assertResponse(HTTP_CREATED);
    Assert.assertEquals(mapUri, httpLocation);

    for (String method : new String[] { HTTP_PUT, HTTP_POST }) {
        getJsonResult(mapUri, method, cf);
        assertResponse(HTTP_NO_CONTENT);
    }

    assertMacMapping(mapUri, configExpected);

    // Try to create MAC mapping with specifying invalid MAC address.
    String[] badMacs = {
            // broken
            "invalid_mac_address",
            // zero
            "00:00:00:00:00:00",
            // broadcast
            "ff:ff:ff:ff:ff:ff",
            // multicast
            "81:00:11:22:33:44", };

    String[] acls = { "allow", "deny" };
    for (String mac : badMacs) {
        JSONObject machost = new JSONObject();
        machost.put("address", mac);
        machost.put("vlan", 1);

        JSONArray maclist = new JSONArray();
        maclist.put(machost);

        JSONObject set = new JSONObject();
        set.put("machost", maclist);

        for (String acl : acls) {
            String uri = createRelativeURI(mapUri, acl, mac, "1");
            getJsonResult(uri, HTTP_PUT);
            assertResponse(HTTP_BAD_REQUEST);

            for (String method : new String[] { HTTP_PUT, HTTP_POST }) {
                JSONObject conf = new JSONObject();
                conf.put(acl, set);

                getJsonResult(mapUri, method, conf.toString());
                assertResponse(HTTP_BAD_REQUEST);

                uri = createRelativeURI(mapUri, acl);
                getJsonResult(uri, method, set.toString());
                assertResponse(HTTP_BAD_REQUEST);
            }
        }
    }

    // Try to create MAC mapping with specifying invalid VLAN ID.
    int[] badVlans = { -1, 4096, 10000, };

    for (int vlan : badVlans) {
        String mac = "00:00:00:00:00:10";
        JSONObject machost = new JSONObject();
        machost.put("address", mac);
        machost.put("vlan", vlan);

        JSONArray maclist = new JSONArray();
        maclist.put(machost);

        JSONObject set = new JSONObject();
        set.put("machost", maclist);

        for (String acl : acls) {
            String uri = createRelativeURI(mapUri, acl, mac, String.valueOf(vlan));
            getJsonResult(uri, HTTP_PUT);
            assertResponse(HTTP_BAD_REQUEST);

            for (String method : new String[] { HTTP_PUT, HTTP_POST }) {
                JSONObject conf = new JSONObject();
                conf.put(acl, set);

                getJsonResult(mapUri, method, conf.toString());
                assertResponse(HTTP_BAD_REQUEST);

                uri = createRelativeURI(mapUri, acl);
                getJsonResult(uri, method, set.toString());
                assertResponse(HTTP_BAD_REQUEST);
            }
        }
    }

    // Try to register NULL address to deny set.
    for (String method : new String[] { HTTP_POST, HTTP_PUT }) {
        String acl = "deny";
        JSONObject set = createMacHostSet(null, "110");
        JSONObject conf = new JSONObject();
        conf.put(acl, set);

        getJsonResult(mapUri, method, conf.toString());
        assertResponse(HTTP_BAD_REQUEST);

        String uri = createRelativeURI(mapUri, acl);
        getJsonResult(uri, method, set.toString());
        assertResponse(HTTP_BAD_REQUEST);
    }

    // Try to remove hosts that are not registered.
    String remove = "?action=remove";
    LinkedList<String> allowedHosts1 = new LinkedList<String>();
    for (int i = 0; i < 5; i++) {
        String mac;
        if ((i & 1) == 0) {
            mac = null;
        } else {
            allowedAddr[5] = (byte) i;
            mac = ByteUtils.toHexString(allowedAddr);
        }

        String vlan = String.valueOf(i + 100);
        allowedHosts1.add(mac);
        allowedHosts1.add(vlan);
    }

    for (int i = 5; i < 10; i++) {
        String mac;
        if ((i & 1) == 0) {
            allowedAddr[5] = (byte) (i + 1);
            mac = ByteUtils.toHexString(allowedAddr);
        } else {
            mac = null;
        }

        String vlan = String.valueOf(i);
        allowedHosts1.add(mac);
        allowedHosts1.add(vlan);
    }

    LinkedList<String> deniedHosts1 = new LinkedList<String>();
    for (int i = 0; i < 5; i++) {
        deniedAddr[4] = (byte) (i + 1);
        String mac = ByteUtils.toHexString(deniedAddr);
        String vlan = String.valueOf(i + 100);
        deniedHosts1.add(mac);
        deniedHosts1.add(vlan);
    }
    for (int i = 5; i < 10; i++) {
        deniedAddr[4] = (byte) i;
        String mac = ByteUtils.toHexString(deniedAddr);
        String vlan = String.valueOf(i + 1000);
        deniedHosts1.add(mac);
        deniedHosts1.add(vlan);
    }

    JSONObject allow1 = createMacHostSet(allowedHosts1);
    JSONObject deny1 = createMacHostSet(deniedHosts1);
    config = new JSONObject();
    config.put("allow", allow1).put("deny", deny1);
    getJsonResult(createRelativeURI(mapUri + remove), HTTP_POST, config.toString());
    assertResponse(HTTP_NO_CONTENT);
    for (String acl : acls) {
        JSONObject set;
        LinkedList<String> hostList;
        if (acl.equals("allow")) {
            set = allow1;
            hostList = allowedHosts1;
        } else {
            set = deny1;
            hostList = deniedHosts1;
        }

        getJsonResult(createRelativeURI(mapUri, acl + remove), HTTP_POST, set.toString());
        assertResponse(HTTP_NO_CONTENT);

        Iterator<String> it = hostList.iterator();
        while (it.hasNext()) {
            String m = it.next();
            String v = it.next();
            String uri = createRelativeURI(mapUri, acl, (m == null) ? "ANY" : m, (v == null) ? "0" : v);
            getJsonResult(uri, HTTP_DELETE);
            assertResponse(HTTP_NO_CONTENT);
        }
    }

    String[] allowedArray = allowedHosts.toArray(new String[0]);
    for (int i = 0; i < allowedArray.length; i += 2) {
        String acl = "allow";
        String mac = allowedArray[i];
        String vlan = allowedArray[i + 1];

        // Try to map MAC addresses which are already mapped by another
        // vBridge.
        String uri = createRelativeURI(mapUri2, acl, (mac == null) ? "ANY" : mac, (vlan == null) ? "0" : vlan);
        getJsonResult(uri, HTTP_PUT);
        assertResponse(HTTP_CONFLICT);

        JSONObject set = createMacHostSet(mac, vlan);
        JSONObject conf = new JSONObject();
        conf.put(acl, set);

        for (String method : new String[] { HTTP_POST, HTTP_PUT }) {
            getJsonResult(mapUri2, method, conf.toString());
            assertResponse(HTTP_CONFLICT);

            uri = createRelativeURI(mapUri2, acl);
            getJsonResult(uri, method, set.toString());
            assertResponse(HTTP_CONFLICT);
        }

        if (mac == null) {
            continue;
        }

        // Try to register duplicate MAC address.
        uri = createRelativeURI(mapUri, acl, mac, "1000");
        getJsonResult(uri, HTTP_PUT);
        assertResponse(HTTP_CONFLICT);

        set = createMacHostSet(mac, "1000");
        conf = new JSONObject();
        conf.put(acl, set);

        String method = HTTP_POST;
        getJsonResult(mapUri, method, conf.toString());
        assertResponse(HTTP_CONFLICT);

        uri = createRelativeURI(mapUri, acl);
        getJsonResult(uri, method, set.toString());
        assertResponse(HTTP_CONFLICT);
    }

    // Duplicate MAC address in allow set.
    String acl = "allow";
    String mac = "00:11:22:33:55:88";
    JSONObject set = createMacHostSet(mac, "1000", mac, "1001");
    for (String method : new String[] { HTTP_POST, HTTP_PUT }) {
        JSONObject conf = new JSONObject();
        conf.put(acl, set);

        getJsonResult(mapUri, method, conf.toString());
        assertResponse(HTTP_BAD_REQUEST);

        String uri = createRelativeURI(mapUri, acl);
        getJsonResult(uri, method, set.toString());
        assertResponse(HTTP_BAD_REQUEST);
    }

    // Configuration should not be affected.
    assertMacMapping(mapUri, configExpected);

    // Remove 2 hosts from both list.
    for (int i = 0; i < 4; i++) {
        allowedHosts.removeFirst();
        deniedHosts.removeFirst();
    }

    config = createMacMapConfig(allowedHosts, deniedHosts);
    getJsonResult(mapUri, HTTP_PUT, config.toString());
    assertResponse(HTTP_OK);

    configExpected = completeMacMapConfig(config);
    assertMacMapping(mapUri, configExpected);

    for (String acl1 : acls) {
        LinkedList<String> hostList = (acl1.equals("allow")) ? allowedHosts : deniedHosts;

        // Remove 2 hosts by specifying the list.
        String mac1 = hostList.removeFirst();
        String vlan1 = hostList.removeFirst();
        String mac2 = hostList.removeFirst();
        String vlan2 = hostList.removeFirst();
        JSONObject set1 = createMacHostSet(mac1, vlan1, mac2, vlan2);

        String uri = createRelativeURI(mapUri, acl1 + remove);
        getJsonResult(uri, HTTP_POST, set1.toString());
        assertResponse(HTTP_OK);
        assertMacMapping(mapUri, allowedHosts, deniedHosts);
    }

    // Remove 2 hosts from both lists.
    config = new JSONObject();
    for (String acl1 : acls) {
        LinkedList<String> hostList = (acl1.equals("allow")) ? allowedHosts : deniedHosts;
        String mac1 = hostList.removeFirst();
        String vlan1 = hostList.removeFirst();
        String mac2 = hostList.removeFirst();
        String vlan2 = hostList.removeFirst();
        JSONObject set1 = createMacHostSet(mac1, vlan1, mac2, vlan2);
        config.put(acl1, set1);
    }
    getJsonResult(mapUri + remove, HTTP_POST, config.toString());
    assertResponse(HTTP_OK);
    assertMacMapping(mapUri, allowedHosts, deniedHosts);

    // Remove 3 hosts by DELETE.
    for (String acl1 : acls) {
        LinkedList<String> hostList = (acl1.equals("allow")) ? allowedHosts : deniedHosts;

        for (int i = 0; i < 3; i++) {
            String m = hostList.removeFirst();
            String v = hostList.removeFirst();
            String uri = createRelativeURI(mapUri, acl1, (m == null) ? "ANY" : m, (v == null) ? "0" : v);
            getJsonResult(uri, HTTP_DELETE);
            assertResponse(HTTP_OK);
        }
    }
    assertMacMapping(mapUri, allowedHosts, deniedHosts);

    // Remove 3 hosts, and add 4 hosts by PUT.
    byte[] base = { (byte) 0xa0, (byte) 0xa1, (byte) 0xa2, (byte) 0x00, (byte) 0xa4, (byte) 0xa5, };
    for (String acl1 : acls) {
        LinkedList<String> hostList = (acl1.equals("allow")) ? allowedHosts : deniedHosts;
        for (int i = 0; i < 6; i++) {
            hostList.removeFirst();
        }

        for (int i = 0; i < 4; i++) {
            base[3] = (byte) i;
            hostList.add(ByteUtils.toHexString(base));
            hostList.add(String.valueOf(i + 500));
        }
    }

    config = createMacMapConfig(allowedHosts, deniedHosts);
    configExpected = completeMacMapConfig(config);
    getJsonResult(mapUri, HTTP_PUT, config.toString());
    assertResponse(HTTP_OK);
    assertMacMapping(mapUri, allowedHosts, deniedHosts);

    for (String acl1 : acls) {
        LinkedList<String> hostList = (acl1.equals("allow")) ? allowedHosts : deniedHosts;
        for (int i = 0; i < 6; i++) {
            hostList.removeFirst();
        }

        for (int i = 20; i < 24; i++) {
            base[3] = (byte) i;
            hostList.add(ByteUtils.toHexString(base));
            hostList.add(String.valueOf(i + 500));
        }

        JSONObject set1 = createMacHostSet(hostList);
        getJsonResult(createRelativeURI(mapUri, acl1), HTTP_PUT, set1.toString());
        assertResponse(HTTP_OK);
        assertMacMapping(mapUri, allowedHosts, deniedHosts);
    }

    // Remove MAC mapping by specifying host list.
    LinkedList<String> saveAllowed = new LinkedList<String>(allowedHosts);
    LinkedList<String> saveDenied = new LinkedList<String>(deniedHosts);
    for (int i = 0; i < acls.length; i++) {
        String acl1 = acls[i];
        LinkedList<String> hostList = (acl1.equals("allow")) ? allowedHosts : deniedHosts;
        hostList.clear();

        String uri = createRelativeURI(mapUri, acl1);
        getJsonResult(uri, HTTP_DELETE);
        assertResponse(HTTP_OK);

        if (i == acls.length - 1) {
            assertNoMacMapping(mapUri);
        } else {
            assertMacMapping(mapUri, allowedHosts, deniedHosts);
        }
    }

    // Install the same MAC mapping to another vBridge.
    config = createMacMapConfig(saveAllowed, saveDenied);
    configExpected = completeMacMapConfig(config);
    getJsonResult(mapUri2, HTTP_PUT, config.toString());
    assertResponse(HTTP_CREATED);
    assertMacMapping(mapUri2, configExpected);

    getJsonResult(mapUri2, HTTP_DELETE);
    assertResponse(HTTP_OK);
    assertNoMacMapping(mapUri2);

    // Create MAC mapping by installing a host to the specific URI.
    mac = "00:11:22:33:44:55";
    String vlan = "4095";
    JSONObject hostSet = createMacHostSet(mac, vlan);
    List<String> empty = new LinkedList<String>();

    for (String acl1 : acls) {
        JSONObject set1;
        if (acl1.equals("allow")) {
            set1 = createMacHostSet(saveAllowed);
            config = createMacMapConfig(saveAllowed, empty);
        } else {
            set1 = createMacHostSet(saveDenied);
            config = createMacMapConfig(empty, saveDenied);
        }

        configExpected = completeMacMapConfig(config);
        String uri = createRelativeURI(mapUri2, acl1);
        for (String method : new String[] { HTTP_PUT, HTTP_POST }) {
            getJsonResult(uri + qparam, method, set1.toString());
            assertResponse(HTTP_CREATED);
            Assert.assertEquals(uri, httpLocation);
            assertMacMapping(mapUri2, configExpected);

            getJsonResult(uri, HTTP_DELETE);
            assertResponse(HTTP_OK);
            assertNoMacMapping(mapUri2);
        }

        config = new JSONObject();
        config.put(acl1, hostSet);
        String hostUri = createRelativeURI(uri, mac, vlan);
        getJsonResult(hostUri + qparam, HTTP_PUT);
        assertResponse(HTTP_CREATED);
        Assert.assertEquals(hostUri, httpLocation);
        assertMacMapping(mapUri2, config);

        getJsonResult(hostUri, HTTP_DELETE);
        assertResponse(HTTP_OK);
        assertNoMacMapping(mapUri2);
    }
}