Example usage for java.util HashSet toArray

List of usage examples for java.util HashSet toArray

Introduction

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

Prototype

<T> T[] toArray(T[] a);

Source Link

Document

Returns an array containing all of the elements in this set; the runtime type of the returned array is that of the specified array.

Usage

From source file:com.activecq.samples.workflow.impl.TagExplosionProcessWorkflow.java

/**
 * Work flow execute method *//w  w w .ja  va  2s  .com
 */

@Override
public void execute(WorkItem workItem, WorkflowSession workflowSession, MetaDataMap args)
        throws WorkflowException {
    log.debug("TAG EXPLODE");
    final WorkflowData workflowData = workItem.getWorkflowData();
    final String type = workflowData.getPayloadType();

    // Check if the payload is a path in the JCR
    if (!StringUtils.equals(type, "JCR_PATH")) {
        return;
    }

    Session session = workflowSession.getSession();
    // Get the path to the JCR resource from the payload
    String path = workflowData.getPayload().toString();

    // Get a ResourceResolver using the same permission set as the Workflow's executing Session
    ResourceResolver resolver = null;
    Map<String, Object> authInfo = new HashMap<String, Object>();
    authInfo.put(JcrResourceConstants.AUTHENTICATION_INFO_SESSION, session);

    // Initialize some variables
    final HashSet<String> newExplodedTags = new HashSet<String>();

    try {
        // Get the Workflow Sessions' resource resolver using the authInfo created above
        resolver = resourceResolverFactory.getResourceResolver(authInfo);

        // Get the Resource representing the WF payload
        final Resource resource = resolver.getResource(path);

        // Get the TagManager (using the same permission level as the Workflow's Session)
        final TagManager tagManager = resolver.adaptTo(TagManager.class);

        // Use custom implementation to find the resource to look for cq:tags and write the
        // custom property "tag-titles" to
        final Resource contentResource = getContentResource(resource);

        if (contentResource == null) {
            log.error("Could not find a valid content resource node for payload: {}", resource.getPath());
            return;
        }

        // Gain access to the content resource's properties
        final ValueMap properties = contentResource.adaptTo(ValueMap.class);

        // Get the full tag paths (namespace:path/to/tag) from the content resource
        // This only works on the cq:tags property
        final List<Tag> tags = getStringPropertyToTag(contentResource, FROM_PROPERTY, tagManager);

        // Get any previously applied Localized Tag Titles.
        // This is used to determine if changes if any updates are needed to this node.
        final String[] previousExplodedTags = properties.get(TO_PROPERTY, new String[] {});

        if (!tags.isEmpty()) {
            newExplodedTags.addAll(getExplodedTags(tags, newExplodedTags));
        }

        try {
            // Get the node in the JCR the payload points to
            final Node node = session.getNode(contentResource.getPath());

            // If the currently applied Tag Titles are the same as the derived Tag titles then skip!
            if (!isSame(newExplodedTags.toArray(new String[] {}), previousExplodedTags)) {
                // If changes have been made to the Tag Names, then apply to the tag-titles property
                // on the content resource.
                node.setProperty(TO_PROPERTY, newExplodedTags.toArray(new String[] {}));
            } else {
                log.debug("No change in Tags. Do not update this content resource.");
            }

        } catch (PathNotFoundException ex) {
            log.error(ex.getMessage());
        } catch (RepositoryException ex) {
            log.error(ex.getMessage());
        }
    } catch (LoginException ex) {
        log.error(ex.getMessage());
    } finally {
        // Clean up after yourself please!!!
        if (resolver != null) {
            resolver.close();
            resolver = null;
        }
    }
}

From source file:org.sakaiproject.evaluation.logic.EvalAuthoringServiceImpl.java

/**
 * Internal method: allows us to get to the set of all copies
 * @return the set of copies of the items
 *//*from  w ww.  jav a2s. c  om*/
private Set<EvalItem> copyItemsInternal(Long[] itemIds, String ownerId, boolean hidden,
        boolean includeChildren) {
    if (ownerId == null || ownerId.length() == 0) {
        throw new IllegalArgumentException("Invalid ownerId, cannot be null or empty string");
    }

    Set<EvalItem> copiedItems = new HashSet<>();
    if (itemIds != null && itemIds.length > 0) {
        itemIds = ArrayUtils.unique(itemIds);
        List<EvalItem> items = dao.findBySearch(EvalItem.class, new Search("id", itemIds));
        if (items.size() != itemIds.length) {
            throw new IllegalArgumentException("Invalid itemIds in array: " + itemIds);
        }

        for (EvalItem original : items) {
            EvalItem copy = new EvalItem(ownerId, original.getItemText(), original.getDescription(),
                    EvalConstants.SHARING_PRIVATE, original.getClassification(), false, null,
                    original.getScale(), null, original.getUsesNA(), original.getUsesComment(), false,
                    original.getDisplayRows(), original.getScaleDisplaySetting(), original.getCategory(),
                    false);
            // NOTE: no longer copying scales here - EVALSYS-689
            copy.setCopyOf(original.getId());
            copy.setHidden(hidden);
            copy.setCompulsory(original.isCompulsory());
            copiedItems.add(copy);
        }

        if (includeChildren) {
            // make a copy of all Scales and put them into the Items to replace the originals
            HashSet<Long> scaleIdSet = new HashSet<>();
            for (EvalItem item : copiedItems) {
                if (item.getScale() != null) {
                    Long scaleId = item.getScale().getId();
                    scaleIdSet.add(scaleId);
                }
            }
            Long[] scaleIds = scaleIdSet.toArray(new Long[scaleIdSet.size()]);
            // do the scales copy
            // https://bugs.caret.cam.ac.uk/browse/CTL-1531 - hide all the internal things which are copied (do not pass through the hidden variable)
            Set<EvalScale> copiedScales = copyScalesInternal(scaleIds, null, ownerId, true);
            HashMap<Long, EvalScale> originalIdToCopy = new HashMap<>(copiedItems.size());
            for (EvalScale scale : copiedScales) {
                originalIdToCopy.put(scale.getCopyOf(), scale);
            }
            // insert the copied items into the copied template items (update the foreign keys when we save)
            for (EvalItem item : copiedItems) {
                if (item.getScale() != null) {
                    Long scaleId = item.getScale().getId(); // original id
                    EvalScale copy = originalIdToCopy.get(scaleId);
                    if (copy != null) {
                        item.setScale(copy);
                    }
                }
            }
        }
        dao.saveSet(copiedItems);
    }
    return copiedItems;
}

From source file:org.sakaiproject.evaluation.logic.EvalAuthoringServiceImpl.java

public Long[] copyTemplateItems(Long[] templateItemIds, String ownerId, boolean hidden, Long toTemplateId,
        boolean includeChildren) {
    if (ownerId == null || ownerId.length() == 0) {
        throw new IllegalArgumentException("Invalid ownerId, cannot be null or empty string");
    }//from ww  w . j  a va  2  s.c om
    if (templateItemIds == null || templateItemIds.length == 0) {
        throw new IllegalArgumentException("Invalid templateItemIds array, cannot be null or empty");
    }

    templateItemIds = ArrayUtils.unique(templateItemIds);
    EvalTemplate toTemplate = null;
    if (toTemplateId != null) {
        toTemplate = getTemplateById(toTemplateId);
        if (toTemplate == null) {
            throw new IllegalArgumentException(
                    "Invalid toTemplateId, cannot find the template by this id: " + toTemplateId);
        }
    }

    List<EvalTemplateItem> templateItemsList = dao.findBySearch(EvalTemplateItem.class,
            new Search("id", templateItemIds));
    if (templateItemsList.size() != templateItemIds.length) {
        throw new IllegalArgumentException("Invalid templateItemIds in array: " + templateItemIds);
    }

    // now we check that copying into the originating template is correct and ensure the toTemplate is set
    if (toTemplate == null) {
        // all templateItems must be from the same template if this is the case
        for (EvalTemplateItem templateItem : templateItemsList) {
            Long templateId = templateItem.getTemplate().getId();
            if (toTemplate == null) {
                toTemplate = getTemplateById(templateId);
            } else {
                if (!toTemplate.getId().equals(templateId)) {
                    throw new IllegalArgumentException(
                            "All templateItems must be from the same template when doing a copy within a template, "
                                    + "if you want to copy templateItems from multiple templates into the same templates they are currently in you must "
                                    + "do it in batches where each set if from one template");
                }
            }
        }
    }

    // sort the list of template items
    templateItemsList = TemplateItemUtils.orderTemplateItems(templateItemsList, false);

    int itemCount = 1; // start at display order 1
    if (toTemplateId == null && toTemplate != null) {
        // copying inside one template so start at the item count + 1
        // get the count of items in the destination template so we know where to start displayOrder from
        itemCount = getItemCountForTemplate(toTemplate.getId()) + 1;
    }

    /* http://bugs.sakaiproject.org/jira/browse/EVALSYS-689
     * need to track the copied items and scales to avoid copying them more than once
     */
    LinkedHashSet<EvalTemplateItem> copiedTemplateItems = new LinkedHashSet<>(templateItemsList.size());

    // shallow copy all block parents first so we can know their new IDs, then later we will update them
    List<EvalTemplateItem> parentItems = TemplateItemUtils.getParentItems(templateItemsList);
    HashMap<Long, EvalTemplateItem> parentIdToCopy = new HashMap<>(parentItems.size());
    if (!parentItems.isEmpty()) {
        for (EvalTemplateItem original : parentItems) {
            Long originalBlockParentId = original.getId();
            List<EvalTemplateItem> childItems = TemplateItemUtils.getChildItems(templateItemsList,
                    originalBlockParentId);
            if (childItems.size() > 0) {
                // only copy this if it has children, lone parents do not get copied
                EvalTemplateItem copy = copyTemplateItem(original, toTemplate, ownerId, hidden);
                parentIdToCopy.put(originalBlockParentId, copy);
            }
        }
        HashSet<EvalTemplateItem> parentItemsToSave = new HashSet<>(parentIdToCopy.values());
        dao.saveSet(parentItemsToSave);
    }

    // check for block items
    List<EvalTemplateItem> nonChildItems = TemplateItemUtils.getNonChildItems(templateItemsList);

    // iterate though in display order and copy the template items
    int displayOrder = 0;
    for (EvalTemplateItem original : nonChildItems) {
        templateItemsList.remove(original); // take this out of the list
        if (TemplateItemUtils.isBlockParent(original)) {
            // this is a block parent so copy it and its children
            Long originalBlockParentId = original.getId();
            if (parentIdToCopy.containsKey(originalBlockParentId)) {
                EvalTemplateItem copyParent = parentIdToCopy.get(originalBlockParentId);
                copyParent.setDisplayOrder(itemCount + displayOrder); // fix up display order
                copyParent.setBlockId(null);
                copyParent.setBlockParent(true);
                //dao.save(copyParent);
                copiedTemplateItems.add(copyParent);
                Long blockParentId = copyParent.getId();

                // loop through and copy all the children and assign them to the parent
                List<EvalTemplateItem> childItems = TemplateItemUtils.getChildItems(templateItemsList,
                        originalBlockParentId);
                for (int j = 0; j < childItems.size(); j++) {
                    EvalTemplateItem child = childItems.get(j);
                    templateItemsList.remove(child); // take this out of the list
                    // copy the child item
                    EvalTemplateItem copy = copyTemplateItem(child, toTemplate, ownerId, hidden);
                    copy.setDisplayOrder(j); // fix up display order
                    copy.setBlockId(blockParentId);
                    copy.setBlockParent(false);
                    //dao.save(copy);
                    copiedTemplateItems.add(copy);
                }
            }
        } else {
            // not a block parent
            EvalTemplateItem copy = copyTemplateItem(original, toTemplate, ownerId, hidden);
            copy.setDisplayOrder(itemCount + displayOrder); // fix up display order
            //dao.save(copy);
            copiedTemplateItems.add(copy);
        }
        displayOrder++;
    }

    // now copy any remaining orphaned block children into normal items
    for (EvalTemplateItem original : templateItemsList) {
        displayOrder++;
        EvalTemplateItem copy = copyTemplateItem(original, toTemplate, ownerId, hidden);
        copy.setDisplayOrder(itemCount + displayOrder); // fix up display order
        //dao.save(copy);
        copiedTemplateItems.add(copy);
    }

    if (includeChildren) {
        // make a copy of all items and put them into the TIs to replace the originals
        HashSet<Long> itemIdSet = new HashSet<>();
        for (EvalTemplateItem eti : copiedTemplateItems) {
            if (eti.getItem() != null) {
                Long itemId = eti.getItem().getId();
                itemIdSet.add(itemId);
            }
        }
        Long[] itemIds = itemIdSet.toArray(new Long[itemIdSet.size()]);
        // do the items copy
        Set<EvalItem> copiedItems = copyItemsInternal(itemIds, ownerId, hidden, includeChildren);
        HashMap<Long, EvalItem> originalIdToCopy = new HashMap<>(copiedItems.size());
        for (EvalItem evalItem : copiedItems) {
            originalIdToCopy.put(evalItem.getCopyOf(), evalItem);
        }
        // insert the copied items into the copied template items (update the foreign keys when we save)
        for (EvalTemplateItem eti : copiedTemplateItems) {
            if (eti.getItem() != null) {
                Long itemId = eti.getItem().getId(); // original id
                EvalItem copy = originalIdToCopy.get(itemId);
                if (copy != null) {
                    eti.setItem(copy);
                }
            }
        }
    }
    // save the template items
    dao.saveSet(copiedTemplateItems);

    Long[] copiedIds = new Long[copiedTemplateItems.size()];
    int counter = 0;
    for (EvalTemplateItem copiedTemplateItem : copiedTemplateItems) {
        copiedIds[counter] = copiedTemplateItem.getId();
        counter++;
    }
    return copiedIds;
}

From source file:org.getobjects.ofs.OFSFileContainerChildInfo.java

protected Exception load() {
    // IMPORTANT: object must be threadsafe after the load! Its cached in a
    //            global map
    if (this.fileNames != null)
        return null; /* already loaded */

    /* load subfiles */

    this.timestamp = this.fileInfo.lastModified();
    this.fileNames = this.fileManager.childNamesAtPath(this.fileInfo.getPath());

    if (this.fileNames == null) {
        log().warn("directory returned no files: " + this);
        return new GoInternalErrorException("could not list directory: " + this.fileInfo.getName());
    }/*from ww w  .  j av  a2s.c  om*/

    /* check if its empty */

    if (this.fileNames.length == 0) {
        this.fileIds = emptyStringArray;
        this.ids = this.fileIds;
        return null;
    }

    /* extract file information */

    final HashSet<String> idUniquer = new HashSet<String>(this.fileNames.length);
    this.fileIds = new String[this.fileNames.length];
    this.fileTypes = new String[this.fileNames.length];

    int removeCount = 0;
    for (int i = (this.fileNames.length - 1); i >= 0; i--) {
        String fn = this.fileNames[i];
        int dotIdx = fn != null ? fn.lastIndexOf('.') : -1;

        if (!this.accept(fn)) {
            this.fileNames[i] = null;
            removeCount += 1;
            continue;
        }

        if (dotIdx == -1) /* not recommended, file has no extension (README) */
            this.fileIds[i] = fn;
        else {
            this.fileIds[i] = fn.substring(0, dotIdx);
            this.fileTypes[i] = fn.substring(dotIdx + 1);
        }

        if (this.fileIds[i] != null && !(fn.startsWith(this.fileIds[i]))) {
            System.err.println("map: " + fn);
            System.err.println(" to: " + this.fileIds[i]);
        }

        if (this.fileIds[i] != null)
            idUniquer.add(this.fileIds[i]);
    }

    if (removeCount > 0) {
        int len = this.fileNames.length - removeCount;
        if (len == 0) {
            this.fileNames = emptyStringArray;
            this.fileIds = this.fileNames;
            this.ids = this.fileIds;
            this.fileTypes = this.ids;
            return null;
        }
        String[] censoredFileNames = new String[len];
        String[] censoredFileIds = new String[len];
        String[] censoredFileTypes = new String[len];
        int dstIdx = 0;
        for (int i = 0; i < this.fileNames.length; i++) {
            if (this.fileNames[i] != null) {
                censoredFileNames[dstIdx] = this.fileNames[i];
                censoredFileIds[dstIdx] = this.fileIds[i];
                censoredFileTypes[dstIdx] = this.fileTypes[i];
                dstIdx++;
            }
        }
        this.fileNames = censoredFileNames;
        this.fileIds = censoredFileIds;
        this.fileTypes = censoredFileTypes;
    }

    /* check whether all files where unique and included */

    if (this.fileNames.length == idUniquer.size()) {
        /* all IDs were unique */
        this.ids = this.fileIds;
    } else {
        /* we found DUPs */
        this.ids = idUniquer.toArray(emptyStringArray);
    }
    if (this.ids != null) {
        if (this.ids == this.fileIds) {
            /* Note: if we don't do this, both array will be sorted, because they
             *       share the same pointer ...
             */
            this.ids = new String[this.fileIds.length];
            System.arraycopy(this.fileIds, 0, this.ids, 0, this.fileIds.length);
        }
        Arrays.sort(this.ids);
    }

    /* debug */
    if (false) {
        for (int j = 0; j < this.fileNames.length; j++) {
            System.err.println("  id: " + this.fileIds[j]);
            System.err.println("  =>: " + this.fileNames[j]);
        }
    }
    return null; /* everything is awesome */
}

From source file:org.gcaldaemon.gui.config.MainConfig.java

public final String[] getCalendarPaths() {
    try {/*from   w w  w . j ava 2s  . c o  m*/
        HashSet set = new HashSet();
        FileSync[] configs = getFileSyncConfigs();

        // Scan directories
        HashSet dirs = new HashSet();
        int i;
        FileSync config;
        File file, dir;
        for (i = 0; i < configs.length; i++) {
            config = configs[i];
            if (config.icalPath != null && config.icalPath.endsWith(".ics")) {
                if (config.icalPath.indexOf("*.ics") != -1) {
                    continue;
                }
                if (config.icalPath.indexOf("Application Support") != -1) {
                    continue;
                }
                file = new File(config.icalPath);
                dir = file.getParentFile();
                if (dir.isDirectory() && dir.canRead() && !dirs.contains(dir)) {
                    dirs.add(dir);
                    getCalendarPaths(set, dir, true);
                }
            }
        }

        // Scan folders of iCal3
        getICalendar3Paths(set, dirs);

        // Scan folders of iCal4
        getICalendar4Paths(set, dirs);

        // Scan folders of Evolution
        getEvolutionPaths(set, dirs);

        // Add configured paths
        for (i = 0; i < configs.length; i++) {
            config = configs[i];
            if (config.icalPath != null && config.icalPath.endsWith(".ics")
                    && !containsPath(set, config.icalPath)) {
                set.add(config.icalPath);
            }
        }
        String[] array = new String[set.size()];
        set.toArray(array);
        Arrays.sort(array, String.CASE_INSENSITIVE_ORDER);
        return array;
    } catch (Exception anyException) {
    }
    return null;
}

From source file:org.ramadda.geodata.cdmdata.CdmDataOutputHandler.java

/**
 * Get the grid dates/*w w w.  jav  a 2 s.c o m*/
 *
 * @param dataset  the dataset
 *
 * @return  the dates or null
 */
private List<Date> getGridDates(GridDataset dataset) {
    List<Date> gridDates = null;
    List<GridDatatype> grids = dataset.getGrids();
    HashSet<Date> dateHash = new HashSet<Date>();
    List<CoordinateAxis1DTime> timeAxes = new ArrayList<CoordinateAxis1DTime>();

    for (GridDatatype grid : grids) {
        GridCoordSystem gcs = grid.getCoordinateSystem();
        CoordinateAxis1DTime timeAxis = gcs.getTimeAxis1D();
        if ((timeAxis != null) && !timeAxes.contains(timeAxis)) {
            timeAxes.add(timeAxis);

            Date[] timeDates = timeAxis.getTimeDates();
            for (Date timeDate : timeDates) {
                dateHash.add(timeDate);
            }
        }
    }
    if (!dateHash.isEmpty()) {
        gridDates = Arrays.asList(dateHash.toArray(new Date[dateHash.size()]));
        Collections.sort(gridDates);
    }

    return gridDates;
}

From source file:org.gbif.ipt.task.Eml2Rtf.java

/**
 * Add authors section./*from w  ww  . j  ava  2s  .co m*/
 * 
 * @param doc Document
 * @param eml EML
 * @throws DocumentException if problem occurs during add
 */
private void addAuthors(Document doc, Eml eml) throws DocumentException {
    // Creating set of authors with different names. (first names + last names).
    HashSet<Agent> tempAgents = new LinkedHashSet<Agent>();
    if (exists(eml.getResourceCreator()) && exists(eml.getResourceCreator().getLastName())) {
        tempAgents.add(eml.getResourceCreator());
    }
    if (exists(eml.getMetadataProvider()) && exists(eml.getMetadataProvider().getLastName())) {
        tempAgents.add(eml.getMetadataProvider());
    }
    tempAgents.addAll(eml.getAssociatedParties());

    // comparing and removing those repeated agents with same name and same address.
    Collection<Integer> toRemove = new ArrayList<Integer>();
    int counter = 0;
    for (Iterator<Agent> i = tempAgents.iterator(); i.hasNext(); counter++) {
        if (toRemove.contains(counter)) {
            i.next();
            i.remove();
        } else {
            Agent agentA = i.next();
            // when second iterator should be start
            boolean flag = false;
            int countTemp = 0;
            for (Iterator<Agent> j = tempAgents.iterator(); j.hasNext(); countTemp++) {
                Agent agentB = j.next();
                if (flag) {
                    if (equal(agentA.getLastName(), agentB.getLastName())
                            && equal(agentA.getFirstName(), agentB.getFirstName())
                            && equal(agentA.getAddress(), agentB.getAddress())) {
                        toRemove.add(countTemp);
                    }
                } else if (agentA.equals(agentB)) {
                    flag = true;
                }
            }
        }
    }

    Agent[] agentsArray = new Agent[tempAgents.size()];
    tempAgents.toArray(agentsArray);
    // Adding authors
    Paragraph p = new Paragraph();
    p.setFont(font);
    p.setAlignment(Element.ALIGN_CENTER);
    java.util.List<Agent> affiliations = new ArrayList<Agent>();
    int superScriptCounter = 1;
    for (int c = 0; c < agentsArray.length; c++) {
        if (exists(agentsArray[c].getLastName())) {
            if (c != 0) {
                p.add(", ");
            }
            // First Name and Last Name
            if (exists(agentsArray[c].getFirstName())) {
                p.add(agentsArray[c].getFirstName() + " ");
            }
            p.add(agentsArray[c].getLastName());
            // Looking for addresses and organisations of other authors
            // (superscripts should not be repeated).
            boolean isRepeated = false;
            // look into the affiliations array to find any previous repeated agent info.
            for (int index = 0; index < affiliations.size(); index++) {
                if (equal(agentsArray[c].getAddress(), affiliations.get(index).getAddress())
                        && equal(agentsArray[c].getOrganisation(), affiliations.get(index).getOrganisation())) {
                    p.add(createSuperScript(String.valueOf(index + 1)));
                    isRepeated = true;
                    break;
                }
            }
            // if the agent is not repeated.
            if (!isRepeated) {
                p.add(createSuperScript(String.valueOf(superScriptCounter)));
                affiliations.add(agentsArray[c]);
                superScriptCounter++;
            }
        }
    }
    doc.add(p);
    p.clear();
    doc.add(Chunk.NEWLINE);
    tempAgents.clear();
    // <AFFILIATIONS>
    p = new Paragraph();
    p.setFont(font);
    p.setAlignment(Element.ALIGN_JUSTIFIED);
    for (int c = 0; c < affiliations.size(); c++) {
        if (c != 0) {
            p.add("; ");
        }
        p.add((c + 1) + " ");
        if (exists(affiliations.get(c).getOrganisation())) {
            p.add(affiliations.get(c).getOrganisation() + ", ");
        }
        if (exists(affiliations.get(c).getAddress().getAddress())) {
            p.add(affiliations.get(c).getAddress().getAddress() + ", ");
        }
        if (exists(affiliations.get(c).getAddress().getPostalCode())) {
            p.add(affiliations.get(c).getAddress().getPostalCode() + ", ");
        }
        if (exists(affiliations.get(c).getAddress().getCity())) {
            p.add(affiliations.get(c).getAddress().getCity());
        }
        if (exists(affiliations.get(c).getAddress().getCountry())) {
            VocabularyConcept concept = vocabManager.get(Constants.VOCAB_URI_COUNTRY)
                    .findConcept(affiliations.get(c).getAddress().getCountry());
            // write country in default language as matched from vocabulary or original value
            if (exists(concept)) {
                p.add(", " + WordUtils.capitalizeFully(concept.getPreferredTerm(DEFAULT_LANGUAGE).getTitle()));
            } else {
                p.add(", " + WordUtils.capitalizeFully(affiliations.get(c).getAddress().getCountry()));
            }
        }
    }
    doc.add(p);
    p.clear();
    doc.add(Chunk.NEWLINE);
    // <Corresponding Authors>
    p = new Paragraph();
    p.setAlignment(Element.ALIGN_JUSTIFIED);
    p.add(new Phrase(getText("rtf.authors") + ": ", fontTitle));
    p.setFont(font);
    boolean isFirst = true;
    if (exists(eml.getResourceCreator())) {
        if (exists(eml.getResourceCreator().getFirstName())) {
            p.add(eml.getResourceCreator().getFirstName() + " ");
        }
        p.add(eml.getResourceCreator().getLastName());
        if (exists(eml.getResourceCreator().getEmail())) {
            p.add(" (" + eml.getResourceCreator().getEmail() + ")");
        }
        isFirst = false;
    }
    if (exists(eml.getMetadataProvider())) {
        boolean sameAsCreator = false;
        if (!isFirst) {
            sameAsCreator = equal(eml.getMetadataProvider().getAddress(), eml.getResourceCreator().getAddress())
                    && equal(eml.getMetadataProvider().getEmail(), eml.getResourceCreator().getEmail());
        }
        if (!sameAsCreator) {
            p.add(", ");
            if (exists(eml.getMetadataProvider().getFirstName())) {
                p.add(eml.getMetadataProvider().getFirstName() + " ");
            }
            p.add(eml.getMetadataProvider().getLastName());
            if (exists(eml.getMetadataProvider().getEmail())) {
                p.add(" (" + eml.getMetadataProvider().getEmail() + ")");
            }
        }
    }
    p.add(Chunk.NEWLINE);
    doc.add(p);
    p.clear();
}

From source file:admixture.parameter.Parameter.java

public void commandListenor(String[] args) {
    CommandLine cl = null;//  ww w. j av a  2s .  c  o m
    try {
        cl = parser.parse(ops, args);
    } catch (ParseException E) {
        System.err.println(E.getMessage());
        System.exit(0);
    }
    if (cl.hasOption(cmd_help)) {
        help = true;
    }
    if (cl.hasOption(cmd_trans)) {
        transFlag = true;
    }
    if (cl.hasOption(cmd_out)) {
        out = cl.getOptionValue(cmd_out);
    }

    if (cl.hasOption(cmd_collapse)) {
        collapseFlag = true;
    }

    if (cl.hasOption(cmd_cc)) {
        ccFlag = true;

        piFlag = false;
        piiFlag = false;
        uiFlag = false;
        uiiFlag = false;
    }
    if (cl.hasOption(cmd_pi)) {
        piFlag = true;

        ccFlag = false;
        piiFlag = false;
        uiFlag = false;
        uiiFlag = false;
    }
    if (cl.hasOption(cmd_pii)) {
        piiFlag = true;

        ccFlag = false;
        piFlag = false;
        uiFlag = false;
        uiiFlag = false;
    }
    if (cl.hasOption(cmd_ui)) {
        uiFlag = true;

        ccFlag = false;
        piFlag = false;
        piiFlag = false;
        uiiFlag = false;
    }
    if (cl.hasOption(cmd_uii)) {
        uiiFlag = true;

        ccFlag = false;
        piFlag = false;
        piiFlag = false;
        uiFlag = false;
    }

    // file
    if (cl.hasOption(cmd_file)) {
        StringBuffer sb1 = new StringBuffer();
        StringBuffer sb2 = new StringBuffer();
        sb1.append(cl.getOptionValue(cmd_file));
        sb1.append(".ped");

        sb2.append(cl.getOptionValue(cmd_file));
        sb2.append(".map");

        ped = sb1.toString();
        map = sb2.toString();
    }
    //      if (cl.hasOption(cmd_ped)) {
    //         ped = cl.getOptionValue(cmd_ped);
    //      }
    //      if (cl.hasOption(cmd_map)) {
    //         map = cl.getOptionValue(cmd_map);
    //      }
    if (ped != null && map != null) {
        File fped = new File(ped);
        if (!fped.exists()) {
            System.err.println("could not open " + ped + ".");
            Test.LOG.append("could not open " + ped + ".\n");
            Test.printLog();
            System.exit(0);
        }
        File fmap = new File(map);
        if (!fmap.exists()) {
            System.err.println("could not open " + map + ".");
            Test.LOG.append("could not open " + map + ".\n");
            Test.printLog();
            System.exit(0);
        }
        fileFlag = true;
    }

    // bfile
    if (cl.hasOption(cmd_bfile)) {
        StringBuffer sb1 = new StringBuffer();
        StringBuffer sb2 = new StringBuffer();
        StringBuffer sb3 = new StringBuffer();
        sb1.append(cl.getOptionValue(cmd_bfile));
        sb1.append(".bed");

        sb2.append(cl.getOptionValue(cmd_bfile));
        sb2.append(".bim");

        sb3.append(cl.getOptionValue(cmd_bfile));
        sb3.append(".fam");

        bed = sb1.toString();
        bim = sb2.toString();
        fam = sb3.toString();
    }
    //      if (cl.hasOption(cmd_bed)) {
    //         bed = cl.getOptionValue(cmd_bed);
    //      }
    //      if (cl.hasOption(cmd_bim)) {
    //         bim = cl.getOptionValue(cmd_bim);
    //      }
    //      if (cl.hasOption(cmd_fam)) {
    //         fam = cl.getOptionValue(cmd_fam);
    //      }
    if (bed != null && bim != null && fam != null) {
        File fbed = new File(bed);
        if (!fbed.exists()) {
            System.err.println("could not open " + bed + ".");
            Test.LOG.append("could not open " + bed + ".\n");
            Test.printLog();
            System.exit(0);
        }
        File fbim = new File(bim);
        if (!fbim.exists()) {
            System.err.println("could not open " + bim + ".");
            Test.LOG.append("could not open " + bim + ".\n");
            Test.printLog();
            System.exit(0);
        }
        File ffam = new File(fam);
        if (!ffam.exists()) {
            System.err.println("could not open " + fam + ".");
            Test.LOG.append("could not open " + fam + ".\n");
            Test.printLog();
            System.exit(0);
        }
        bfileFlag = true;
    }

    if (cl.hasOption(cmd_covar)) {
        pheno = cl.getOptionValue(cmd_covar);
        File fpheno = new File(pheno);
        if (!fpheno.exists()) {
            System.err.println("could not open " + fpheno + ".");
            Test.LOG.append("could not open " + fpheno + ".\n");
            Test.printLog();
            System.exit(0);
        }
    }

    if (cl.hasOption(cmd_covar_header)) {
        covar_header_flag = true;
    }

    if (cl.hasOption(cmd_header)) {
        header = true;
    }

    if (cl.hasOption(cmd_linear)) {
        linkfunction = 0;
    }

    if (cl.hasOption(cmd_logistic)) {
        linkfunction = 1;
    }
    if (cl.hasOption(cmd_pheno_number)) {
        response = Integer.parseInt(cl.getOptionValue(cmd_pheno_number)) - 1;
        if (response < -1) {
            System.err.println("bad parameter for --" + cmd_pheno_number_long + ": " + (response + 1) + ".");
            Test.LOG.append("bad parameter for --" + cmd_pheno_number_long + ": " + (response + 1) + ".\n");
            Test.printLog();
            System.exit(0);
        }
    }

    if (cl.hasOption(cmd_covar_number)) {
        String[] p = cl.getOptionValues(cmd_covar_number);
        HashSet<Integer> idx = NewIt.newHashSet();
        for (int i = 0, len = p.length; i < len; i++) {
            if (p[i].contains("-")) {
                String[] pp = p[i].split("-");
                if (pp.length != 2) {
                    System.err
                            .println("bad parameter for option --" + cmd_covar_number_long + ": " + p[i] + ".");
                    Test.LOG.append(
                            "bad parameter for option --" + cmd_covar_number_long + ": " + p[i] + ".\n");
                    Test.printLog();
                    System.exit(0);
                }
                for (int j = Integer.parseInt(pp[0]); j <= Integer.parseInt(pp[1]); j++) {
                    idx.add(new Integer(j));
                }
            } else {
                idx.add(new Integer(Integer.parseInt(p[i])));
            }
        }
        predictor = new int[idx.size()];
        int c = 0;
        for (Iterator<Integer> e = idx.iterator(); e.hasNext();) {
            predictor[c] = e.next().intValue() - 1;
            if (predictor[c] < 0) {
                System.err.println(
                        "bad parameter for option --" + cmd_covar_number_long + ": " + predictor[c] + ".");
                Test.LOG.append(
                        "bad parameter for option --" + cmd_covar_number_long + ": " + predictor[c] + ".\n");
                Test.printLog();
                System.exit(0);
            }
            c++;
        }
    }

    //      if (cl.hasOption(cmd_covar_name)) {
    //         HashSet<String> cn = NewIt.newHashSet();
    //         String[] p = cl.getOptionValues(cmd_covar_name);
    //         for (int i = 0; i < p.length; i++) {
    //            if (p[i].contains("-")) {
    //               String[] pp = predictor_name[i].split("-");
    //               if (pp.length != 2) {
    //                  System.err.println("bad parameter for option --" + cmd_covar_name_long + ": " + p[i] + ".");
    //                  Test.LOG.append("bad parameter for option --" + cmd_covar_name_long + ": " + p[i] + ".\n");
    //                  Test.printLog();
    //                  System.exit(0);
    //               }
    //               for (int j = 0; j < pp.length; j++) {
    //                  cn.add(pp[j]);
    //               }
    //            } else {
    //               cn.add(p[i]);
    //            }
    //         }
    //         predictor_name = (String[]) cn.toArray(new String[0]);
    //      }

    if (cl.hasOption(cmd_bgsnp)) {
        String[] bg = cl.getOptionValues(cmd_bgsnp);
        HashSet<String> bgSet = NewIt.newHashSet();
        for (int i = 0; i < bg.length; i++) {
            bgSet.add(bg[i]);
        }
        if (bgSet.size() != bg.length) {
            System.err.println("bad parameter for --" + cmd_bgsnp + ".");
            Test.LOG.append("bad parameter for --" + cmd_bgsnp + ".\n");
            Test.printLog();
            System.exit(0);
        }
        bgsnp = cl.getOptionValues(cmd_bgsnp);
        bgsnpFlag = true;
    }

    if (cl.hasOption(cmd_hg18)) {
        hg18Flag = true;
        hg19Flag = false;
        hgFile = "/gene36.txt";
    }

    if (cl.hasOption(cmd_hg19)) {
        hg19Flag = true;
        hg18Flag = false;
        hgFile = "/gene37.txt";
    }

    if (cl.hasOption(cmd_hg)) {
        hg19Flag = false;
        hg18Flag = false;
        hgFile = cl.getOptionValue(cmd_hg);
    }

    if (cl.hasOption(cmd_snp2genelist)) {
        snp2genefileFlag = true;
    }

    if (cl.hasOption(cmd_snp2genemlist)) {
        snp2genefilesFlag = true;
    }

    if (cl.hasOption(cmd_region)) {
        String[] r = cl.getOptionValues(cmd_region);
        ArrayList<String> chr = NewIt.newArrayList();
        ArrayList<String> b = NewIt.newArrayList();
        ArrayList<String> e = NewIt.newArrayList();

        for (int i = 0; i < r.length; i++) {
            String[] s = r[i].split(",");
            if (s.length != 3) {
                System.err.println("bad parameter for --" + cmd_region + ": " + r[i] + ".");
                Test.LOG.append("bad parameter for --" + cmd_region + ": " + r[i] + ".\n");
                Test.printLog();
                System.exit(0);
            }
            chr.add(s[0]);
            b.add(s[1]);
            e.add(s[2]);
        }
        chr_reg = (String[]) chr.toArray(new String[0]);
        begin = new double[b.size()];
        end = new double[e.size()];
        for (int i = 0; i < r.length; i++) {
            begin[i] = Double.parseDouble(b.get(i));
            end[i] = Double.parseDouble(e.get(i));
        }
        regionFlag = true;
    }

    if (cl.hasOption(cmd_gene_list)) {
        String gl = cl.getOptionValue(cmd_gene_list);

        File f = new File(gl);
        if (!f.exists()) {
            System.err.println("could not find file for --option " + cmd_gene_list_long + ": " + gl + ".");
            Test.LOG.append("could not find file for --option " + cmd_gene_list_long + ": " + gl + ".\n");
            Test.printLog();
            System.exit(0);
        }
        BufferedReader reader0 = null;
        try {
            reader0 = new BufferedReader(new FileReader(f));
        } catch (IOException E) {
            System.err.println("could not open gene list " + gl + ".");
            Test.LOG.append("could not open gene list " + gl + ".\n");
            Test.printLog();
            System.exit(0);
        }
        String line0 = null;
        HashSet<String> gSet = NewIt.newHashSet();
        try {
            while ((line0 = reader0.readLine()) != null) {
                String[] gn = line0.split(delim);
                gSet.add(gn[0]);
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        String[] g = (String[]) gSet.toArray(new String[0]);
        boolean[] gflag = new boolean[gSet.size()];
        Arrays.fill(gflag, false);
        ArrayList<String> ge = NewIt.newArrayList();
        ArrayList<String> g_chr = NewIt.newArrayList();
        ArrayList<String> g_begin = NewIt.newArrayList();
        ArrayList<String> g_end = NewIt.newArrayList();

        BufferedReader reader = null;
        if (hg18Flag || hg19Flag) {
            InputStream is = getClass().getResourceAsStream(hgFile);
            DataInputStream in = new DataInputStream(is);
            reader = new BufferedReader(new InputStreamReader(in));
        } else {
            File fhg = new File(hgFile);
            if (!fhg.exists()) {
                System.err.println("could not find file for --option " + cmd_hg + ": " + hgFile + ".");
                Test.LOG.append("could not find file for --option " + cmd_hg + ": " + hgFile + ".\n");
                Test.printLog();
                System.exit(0);
            }

            try {
                reader = new BufferedReader(new FileReader(fhg));
            } catch (IOException E) {
                System.err.println("could not open gene list " + hgFile + ".");
                Test.LOG.append("could not open gene list " + hgFile + ".\n");
                Test.printLog();
                System.exit(0);
            }

        }

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {

                String[] s = line.split("\\s+");
                //               System.err.println(line);
                if (s.length != 4) {
                    continue;
                }

                for (int i = 0; i < g.length; i++) {
                    if (s[0].compareTo(g[i]) == 0) {
                        ge.add(s[0]);
                        g_chr.add(s[1]);
                        g_begin.add(s[2]);
                        g_end.add(s[3]);
                        gflag[i] = true;
                    }
                }
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        boolean flag = true;
        int count = 0;
        for (int i = 0; i < gflag.length; i++) {
            if (!gflag[i]) {
                System.err.println("could not fine gene " + g[i] + ".");
                Test.LOG.append("could not find gene " + g[i] + ".\n");
                flag = false;
                count++;
            }
        }

        System.err.println("of " + gflag.length + " genes " + (gflag.length - count) + " was found.");
        Test.LOG.append("of " + gflag.length + " genes " + (gflag.length - count) + " was found.\n");

        if (!snp2genefileFlag && !snp2genefilesFlag) {
            if (!flag) {
                Test.printLog();
                System.exit(0);
            }
        }

        gene = (String[]) ge.toArray(new String[0]);
        gene_chr = (String[]) g_chr.toArray(new String[0]);
        gene_begin = new double[gene_chr.length];
        gene_end = new double[gene_chr.length];

        for (int i = 0; i < gene_chr.length; i++) {
            gene_begin[i] = Double.parseDouble(g_begin.get(i)) / 1000;
            gene_end[i] = Double.parseDouble(g_end.get(i)) / 1000;
            System.err.println(
                    gene[i] + ": chr" + gene_chr[i] + " " + gene_begin[i] + "k ~ " + gene_end[i] + "k.");
            Test.LOG.append(
                    gene[i] + ": chr" + gene_chr[i] + " " + gene_begin[i] + "k ~ " + gene_end[i] + "k.\n");
        }
        geneFlag = true;
    }

    if (cl.hasOption(cmd_gene_window)) {
        double gw = Double.parseDouble(cl.getOptionValue(cmd_gene_window));
        if (gw < 0) {
            System.err.println("bad parameter for option --" + cmd_gene_window_long + ": " + gw + ".");
            Test.LOG.append("bad parameter for option --" + cmd_gene_window_long + ": " + gw + ".\n");
            Test.printLog();
            System.exit(0);
        }
        genewindow = gw;
    }

    //      if (cl.hasOption(cmd_gene)) {
    //         String[] g = cl.getOptionValues(cmd_gene);
    //         boolean[] gflag = new boolean[g.length];
    //         Arrays.fill(gflag, false);
    //         ArrayList<String> ge = NewIt.newArrayList();
    //         ArrayList<String> g_chr = NewIt.newArrayList();
    //         ArrayList<String> g_begin = NewIt.newArrayList();
    //         ArrayList<String> g_end = NewIt.newArrayList();
    //         
    //         BufferedReader reader = null;
    //         if(hg18Flag || hg19Flag) {
    //            InputStream is = getClass().getResourceAsStream(hgFile);
    //            DataInputStream in = new DataInputStream(is);
    //            reader = new BufferedReader(new InputStreamReader(in));
    //         } else {
    //            File fhg = new File(hgFile);
    //            if (!fhg.exists()) {
    //               System.err.println("could not find file for --option " + cmd_hg + ": " + hgFile +".");
    //               Test.LOG.append("could not find file for --option " + cmd_hg + ": " + hgFile + ".\n");
    //               Test.printLog();
    //               System.exit(0);
    //            }
    //            try {
    //               reader = new BufferedReader(new FileReader(fhg));
    //            } catch (IOException E) {
    //               System.err.println("could not open gene list " + hgFile + ".");
    //               Test.LOG.append("could not open gene list " + hgFile + ".\n");
    //               Test.printLog();
    //               System.exit(0);
    //            }
    //
    //         }
    //
    //         String line = null;
    //         try {
    //            while ((line = reader.readLine()) != null) {
    //
    //               String[] s = line.split("\\s+");
    ////               System.err.println(line);
    //               if (s.length != 4) {
    //                  continue;
    //               }
    //
    //               for (int i = 0; i < g.length; i++) {
    //                  if (s[0].compareTo(g[i]) == 0) {
    //                     ge.add(s[0]);
    //                     g_chr.add(s[1]);
    //                     g_begin.add(s[2]);
    //                     g_end.add(s[3]);
    //                     gflag[i] = true;
    //                  }
    //               }
    //
    //            }
    //            reader.close();
    //         } catch (IOException e) {
    //            e.printStackTrace();
    //         }
    //         boolean flag = true;
    //         int count = 0;
    //         for(int i = 0; i < gflag.length; i++) {
    //            if(!gflag[i]) {
    //               System.err.println("could not find gene " + g[i] + ".");
    //               Test.LOG.append("could not find gene " + g[i] + ".\n");
    //               flag = false;
    //               count++;
    //            }
    //         }
    //         System.err.println("of " + gflag.length + " genes " + (gflag.length - count) + " was found.");
    //         Test.LOG.append("of " + gflag.length + " genes " + (gflag.length - count) + " was found.\n");
    //         if (!snp2genefileFlag && !snp2genefilesFlag) {
    //            if(!flag) {
    //               Test.printLog();
    //               System.exit(0);
    //            }
    //         }
    //
    //         gene = (String[]) ge.toArray(new String[0]);
    //         gene_chr = (String[]) g_chr.toArray(new String[0]);
    //         gene_begin = new double[gene_chr.length];
    //         gene_end = new double[gene_chr.length];
    //
    //         for (int i = 0; i < gene_chr.length; i++) {
    //            gene_begin[i] = Double.parseDouble(g_begin.get(i)) / 1000;
    //            gene_end[i] = Double.parseDouble(g_end.get(i)) / 1000;
    //            System.err.println(gene[i] + ": chr" + gene_chr[i] + " " +gene_begin[i] + "k ~ " + gene_end[i] + "k");
    //            Test.LOG.append(gene[i] + ": chr" + gene_chr[i] + " " +gene_begin[i] + "k ~ " + gene_end[i] + "k.\n");
    //         }
    //         geneFlag = true;
    //      }

    if (cl.hasOption(cmd_extract)) {

        if (!transFlag) {
            includesnpFile = cl.getOptionValues(cmd_extract);
            ArrayList<String> includesnpList = NewIt.newArrayList();
            for (int h = 0; h < includesnpFile.length; h++) {
                File f = new File(includesnpFile[h]);
                if (!f.exists()) {
                    System.err.println("could not find --" + cmd_extract + ": " + includesnpFile[h] + ".");
                    Test.LOG.append("could not fine --" + cmd_extract + ": " + includesnpFile[h] + ".\n");
                    Test.printLog();
                    System.exit(0);
                }
                BufferedReader reader = null;
                try {
                    reader = new BufferedReader(new FileReader(f));
                } catch (IOException E) {
                    System.err.println("could not read --" + cmd_extract + ": " + includesnpFile[h] + ".");
                    Test.LOG.append("could not read --" + cmd_extract + ": " + includesnpFile[h] + ".\n");
                    Test.printLog();
                    System.exit(0);
                }
                ArrayList<String> snp = NewIt.newArrayList();
                String line = null;
                try {
                    while ((line = reader.readLine()) != null) {
                        String[] s = line.split(delim);
                        snp.add(s[0]);
                    }
                    reader.close();
                } catch (IOException E) {
                    System.err.println("bad lines in " + includesnpFile[h] + ".");
                    Test.LOG.append("bad lines in " + includesnpFile[h] + ".\n");
                    Test.printLog();
                    System.exit(0);
                }
                if (snp.size() > 0) {
                    ArrayList<String> insnp = NewIt.newArrayList();
                    for (int i = 0; i < snp.size(); i++) {
                        String subSNP = snp.get(i);
                        insnp.add(subSNP);
                    }

                    if (insnp.size() > 0) {
                        includesnpList.addAll(insnp);
                        snpFlag = true;
                    }
                }
                if (includesnpList.size() > 0) {
                    includesnp = (String[]) includesnpList.toArray(new String[0]);
                }

            }
        } else {
            includesnpFile = cl.getOptionValues(cmd_extract);
            xincludesnp = new String[includesnpFile.length][];
            for (int h = 0; h < includesnpFile.length; h++) {
                File f = new File(includesnpFile[h]);
                if (!f.exists()) {
                    System.err.println("could not find " + includesnpFile[h] + ".");
                    Test.LOG.append("could not find " + includesnpFile[h] + ".\n");
                    Test.printLog();
                    System.exit(0);
                }
                BufferedReader reader = null;
                try {
                    reader = new BufferedReader(new FileReader(f));
                } catch (IOException E) {

                    System.err.println("could not read " + includesnpFile[h] + ".");
                    Test.LOG.append("could not read " + includesnpFile[h] + ".\n");
                    Test.printLog();
                    System.exit(0);
                }
                ArrayList<String> snp = NewIt.newArrayList();
                String line = null;
                try {
                    while ((line = reader.readLine()) != null) {
                        String[] s = line.split(delim);
                        snp.add(s[0]);
                    }
                    reader.close();
                } catch (IOException E) {

                    System.err.println("bad lines in " + includesnpFile[h] + ".");
                    Test.LOG.append("bad lines in " + includesnpFile[h] + ".\n");
                    Test.printLog();
                    System.exit(0);
                }
                if (snp.size() > 0) {
                    ArrayList<String> insnp = NewIt.newArrayList();

                    for (int i = 0; i < snp.size(); i++) {
                        String subSNP = snp.get(i);
                        insnp.add(subSNP);
                    }
                    if (insnp.size() > 0) {
                        xincludesnp[h] = (String[]) insnp.toArray(new String[0]);
                        snpFlag = true;
                    }
                }
            }
        }
    }

    if (cl.hasOption(cmd_exclude)) {

        if (!transFlag) {
            String snps_file = cl.getOptionValue(cmd_exclude);
            ArrayList<String> excludesnpList = NewIt.newArrayList();
            for (int h = 0; h < 1; h++) {
                File f = new File(snps_file);
                if (!f.exists()) {
                    System.err.println("could not find --" + cmd_extract + ": " + snps_file + ".");
                    Test.LOG.append("could not fine --" + cmd_extract + ": " + snps_file + ".\n");
                    Test.printLog();
                    System.exit(0);
                }
                BufferedReader reader = null;
                try {
                    reader = new BufferedReader(new FileReader(f));
                } catch (IOException E) {
                    System.err.println("could not read --" + cmd_extract + ": " + snps_file + ".");
                    Test.LOG.append("could not read --" + cmd_extract + ": " + snps_file + ".\n");
                    Test.printLog();
                    System.exit(0);
                }
                ArrayList<String> snp = NewIt.newArrayList();
                String line = null;
                try {
                    while ((line = reader.readLine()) != null) {
                        String[] s = line.split(delim);
                        snp.add(s[0]);
                    }
                    reader.close();
                } catch (IOException E) {
                    System.err.println("bad lines in " + snps_file + ".");
                    Test.LOG.append("bad lines in " + snps_file + ".\n");
                    Test.printLog();
                    System.exit(0);
                }
                if (snp.size() > 0) {
                    ArrayList<String> exsnp = NewIt.newArrayList();
                    for (int i = 0; i < snp.size(); i++) {
                        String subSNP = snp.get(i);
                        exsnp.add(subSNP);
                    }
                    if (exsnp.size() > 0) {
                        excludesnpList.addAll(exsnp);
                        snpFlag = true;
                    }
                }
                if (excludesnpList.size() > 0) {
                    excludesnp = (String[]) excludesnpList.toArray(new String[0]);
                }
            }
        }

    }

    if (cl.hasOption(cmd_keep_male)) {
        keep_maleFlag = true;
    }
    if (cl.hasOption(cmd_keep_female)) {
        keep_femaleFlag = true;
    }
    if (cl.hasOption(cmd_ex_nosex)) {
        ex_nosexFlag = true;
    }
    if (cl.hasOption(cmd_remove)) {
        String file = cl.getOptionValue(cmd_remove);
        File f = new File(file);
        if (!f.exists()) {
            System.err.println("could not open " + file + ".");
            Test.LOG.append("could not open " + file + ".\n");
            Test.printLog();
            System.exit(0);
        }
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(new File(file)));
        } catch (IOException E) {
            System.err.println("could not read " + file + ".");
            Test.LOG.append("coudl not read " + file + ".\n");
            Test.printLog();
            System.exit(0);
        }
        ArrayList<String> famList = NewIt.newArrayList();
        ArrayList<String> indList = NewIt.newArrayList();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                String[] l = line.split(MDRConstant.delim);
                if (l.length < 2)
                    continue;
                famList.add(l[0]);
                indList.add(l[1]);
            }
        } catch (IOException e) {
            e.printStackTrace(System.err);
            System.exit(0);
        }
        ex_family = new String[2][];
        ex_family[0] = (String[]) famList.toArray(new String[0]);
        ex_family[1] = (String[]) indList.toArray(new String[0]);
        removeFlag = true;
    }

    if (cl.hasOption(cmd_keep)) {
        String file = cl.getOptionValue(cmd_keep);
        File f = new File(file);
        if (!f.exists()) {
            System.err.println("could not open " + file + ".");
            Test.LOG.append("could not open " + file + ".\n");
            Test.printLog();
            System.exit(0);
        }
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(new File(file)));
        } catch (IOException E) {
            System.err.println("could not read " + file + ".");
            Test.LOG.append("coudl not read " + file + ".\n");
            Test.printLog();
            System.exit(0);
        }
        ArrayList<String> famList = NewIt.newArrayList();
        ArrayList<String> indList = NewIt.newArrayList();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                String[] l = line.split(MDRConstant.delim);
                if (l.length < 2)
                    continue;
                famList.add(l[0]);
                indList.add(l[1]);
            }
        } catch (IOException e) {
            e.printStackTrace(System.err);
            System.exit(0);
        }
        indKeep = new String[2][];
        indKeep[0] = (String[]) famList.toArray(new String[0]);
        indKeep[1] = (String[]) indList.toArray(new String[0]);
        keepFlag = true;
    }

    if (cl.hasOption(cmd_chr)) {

        String[] chr = cl.getOptionValues(cmd_chr);
        HashSet<String> chrSet = NewIt.newHashSet();
        HashSet<String> exSet = NewIt.newHashSet();
        for (int i = 0; i < chr.length; i++) {
            if (chr[i].startsWith("-")) {
                exSet.add(chr[i].substring(1, chr[i].length()));
            } else {
                chrSet.add(chr[i]);
            }
        }
        if (chr.length != chrSet.size() + exSet.size()) {
            System.err.println("bad parameter for optin --" + cmd_chr + ".");
            Test.LOG.append("bad parameter for option --" + cmd_chr + ".\n");
            Test.printLog();
            System.exit(0);
        }
        if (chrSet.size() > 0) {
            in_chr = (String[]) chrSet.toArray(new String[0]);
            inchrFlag = true;
        }
        if (exSet.size() > 0) {
            ex_chr = (String[]) exSet.toArray(new String[0]);
            exchrFlag = true;
        }
    }

    if (cl.hasOption(cmd_snpwindow)) {
        String[] s = cl.getOptionValues(cmd_snpwindow);
        snpwindow = new String[s.length];
        snp_window = new double[s.length][2];
        for (int i = 0; i < s.length; i++) {
            String[] ss = s[i].split(incommand_separator);
            if (ss.length != 3) {
                System.err.println("bad parameter for optin --" + cmd_snpwindow_long + " " + s[i] + ".");
                Test.LOG.append("bad parameter for option --" + cmd_snpwindow_long + " " + s[i] + ".\n");
                Test.printLog();
                System.exit(0);
            }
            snpwindow[i] = ss[0];
            snp_window[i][0] = Double.parseDouble(ss[1]) * -1000;
            if (Double.parseDouble(ss[2]) > 0) {
                snp_window[i][1] = Double.parseDouble(ss[2]) * 1000;
            } else {
                snp_window[i][1] = Double.MAX_VALUE;
            }
        }
        snpwindowFlag = true;
    }

    if (cl.hasOption(cmd_maf)) {
        maf = Double.parseDouble(cl.getOptionValue(cmd_maf));
        if (maf < 0) {

            System.err.println("bad parameter for optin --" + cmd_maf + " " + maf + ".");
            Test.LOG.append("bad parameter for option --" + cmd_maf + " " + maf + ".\n");
            Test.printLog();
            System.exit(0);
        }
        mafFlag = true;
    }

    if (cl.hasOption(cmd_max_maf)) {
        max_maf = Double.parseDouble(cl.getOptionValue(cmd_max_maf));
        if (max_maf < 0) {
            System.err.println("bad parameter for optin --" + cmd_max_maf_long + " " + max_maf + ".");
            Test.LOG.append("bad parameter for option --" + cmd_max_maf_long + " " + max_maf + ".\n");
            Test.printLog();
            System.exit(0);
        }
        maxmafFlag = true;
    }

    if (cl.hasOption(cmd_geno)) {
        geno = Double.parseDouble(cl.getOptionValue(cmd_geno));
        if (geno < 0) {

            System.err.println("bad parameter for optin --" + cmd_geno + " " + geno + ".");
            Test.LOG.append("bad parameter for option --" + cmd_geno + " " + geno + ".\n");
            Test.printLog();
            System.exit(0);
        }
        genoFlag = true;
    }
    //
    // if (cl.hasOption(cmd_hwe)) {
    // hwe = Double.parseDouble(cl.getOptionValue(cmd_hwe));
    // if (hwe < 0) {
    // throw new IllegalArgumentException("bad parameter for --hwe: " +
    // hwe);
    // }
    // hweFlag = true;
    // }

    //      if (cl.hasOption(cmd_reg)) {
    //         linkfunction = Integer.parseInt(cl.getOptionValue(cmd_reg));
    //      }
    if (cl.hasOption(cmd_cv)) {
        cv = Integer.parseInt(cl.getOptionValue(cmd_cv));
        if (cv < 2) {

            System.err.println("bad parameter for optin --" + cmd_cv + " " + cv + ".");
            Test.LOG.append("bad parameter for option --" + cmd_cv + " " + cv + ".\n");
            Test.printLog();
            System.exit(0);
        }
        cvFlag = true;
    }
    // if (cl.hasOption(cmd_trgroup)) {
    // trgroup = Double.parseDouble(cl.getOptionValue(cmd_trgroup));
    // trgroupFlag = true;
    // }
    // if (cl.hasOption(cmd_trsex)) {
    // trsex = Integer.parseInt(cl.getOptionValue(cmd_trsex));
    // if (trsex != 1 && trsex != 2) {
    // throw new
    // IllegalArgumentException("unknown value for option --trsex.");
    // }
    // trsexFlag = true;
    // }
    // if (cl.hasOption(cmd_ttfile)) {
    // String tf = cl.getOptionValue(cmd_ttfile);
    // File ttfile = new File(tf);
    // if (!ttfile.exists()) {
    // throw new IllegalArgumentException("could not open ttfile " + tf);
    // }
    //
    // ArrayList<String> Farray = NewIt.newArrayList();
    // ArrayList<String> Iarray = NewIt.newArrayList();
    // BufferedReader reader = null;
    // try {
    // reader = new BufferedReader(new FileReader(new File(tf)));
    // } catch (IOException E) {
    // throw new IllegalArgumentException("failed in reading " + tf);
    // }
    // String line = null;
    // try {
    // while ((line = reader.readLine()) != null) {
    // String[] l = line.split(delim);
    // Farray.add(l[0]);
    // Iarray.add(l[1]);
    // }
    // } catch (IOException e) {
    // e.printStackTrace();
    // }
    //
    // ttArray = new String[2][Farray.size()];
    // ttArray[0] = (String[]) Farray.toArray(new String[0]);
    // ttArray[1] = (String[]) Iarray.toArray(new String[0]);
    // ttfileFlag = true;
    // }
    // if (cl.hasOption(cmd_border)) {
    // String[] h = cl.getOptionValues(cmd_border);
    // if (h.length != 2) {
    // throw new
    // IllegalArgumentException("bad parameter for option --border.");
    // }
    // boolean rflag = false;
    // if (h[0].startsWith("-")) {
    // border_fid = h[0].substring(1, h[0].length());
    // rflag = true;
    // } else {
    // border_fid = h[0];
    // }
    // if (h[1].startsWith("-")) {
    // border_iid = h[1].substring(1, h[1].length());
    // rflag = true;
    // } else {
    // border_iid = h[1];
    // }
    // borderFlag = true;
    // reverseborderFlag = rflag;
    // }
    if (cl.hasOption(cmd_seed)) {
        seed = Integer.parseInt(cl.getOptionValue(cmd_seed));
    }
    if (cl.hasOption(cmd_tie)) {
        String t = cl.getOptionValue(cmd_tie);
        if (t.compareTo("h") == 0) {
            tie = 1;
        } else if (t.compareTo("l") == 0) {
            tie = 0;
        } else {
            tie = -1;
        }
    }
    // if (cl.hasOption(cmd_simu)) {
    // simu = Integer.parseInt(cl.getOptionValue(cmd_simu));
    // }
    if (cl.hasOption(cmd_perm)) {
        perm = Integer.parseInt(cl.getOptionValue(cmd_perm));
        permFlag = true;
    }
    /*
    if (cl.hasOption(cmd_ep)) {
       ep = Double.parseDouble(cl.getOptionValue(cmd_ep));
       if (ep >= 1 || ep < 0) {
            
    System.err.println("bad parameter for optin --" + ep + " " + ep + ".");
    Test.LOG.append("bad parameter for option --" + ep + " " + ep + ".\n");
    Test.printLog();
    System.exit(0);
       }
       epFlag = true;
    }
    */
    // if (cl.hasOption(cmd_perm_scheme)) {
    // permu_scheme = true;
    // }
    // if (cl.hasOption(cmd_unrelated_only)) {
    // unrelated_only = true;
    // }
    if (cl.hasOption(cmd_order)) {
        order = Integer.parseInt(cl.getOptionValue(cmd_order));
    }
    if (cl.hasOption(cmd_thin)) {
        thin = Double.parseDouble(cl.getOptionValue(cmd_thin));
        if (thin < 0) {

            System.err.println("bad parameter for optin --" + cmd_thin + " " + thin + ".");
            Test.LOG.append("bad parameter for option --" + cmd_thin + " " + thin + ".\n");
            Test.printLog();
            System.exit(0);
        }
    }
    if (cl.hasOption(cmd_slice)) {
        String[] s = cl.getOptionValue(cmd_slice).split("/");
        slice = Integer.parseInt(s[0]);
        sliceN = Integer.parseInt(s[1]);
        if (slice <= 0 || sliceN <= 0 || slice > sliceN) {

            System.err.println("bad parameter for optin --" + cmd_slice + " " + slice + ".");
            Test.LOG.append("bad parameter for option --" + cmd_slice + " " + slice + ".\n");
            Test.printLog();
            System.exit(0);
        }
        sliceFlag = true;
    }
    if (cl.hasOption(cmd_missing_phenotype)) {
        String[] s = cl.getOptionValues(cmd_missing_phenotype);
        na = s;
        //         missing_phenotype = cl.getOptionValue(cmd_missing_phenotype);
    }
    // if (cl.hasOption(cmd_missing_genotype)) {
    // missing_genotype = cl.getOptionValue(cmd_missing_genotype);
    // }
    if (cl.hasOption(cmd_missing_allele)) {
        missing_allele = cl.getOptionValue(cmd_missing_allele);
    }
    if (cl.hasOption(cmd_status_shift)) {
        status_shift = 0;
        status_shiftFlag = true;
    }
    /*
    if (cl.hasOption(cmd_Vc)) {
       vc = Double.parseDouble(cl.getOptionValue(cmd_Vc));
       vcFlag = true;
    }
    if (cl.hasOption(cmd_training)) {
       threshold_training = Double.parseDouble(cl
       .getOptionValue(cmd_training));
       trainingFlag = true;
    }
    if (cl.hasOption(cmd_testing)) {
       threshold_testing = Double.parseDouble(cl
       .getOptionValue(cmd_testing));
       testingFlag = true;
    }
    */
    if (cl.hasOption(cmd_version)) {
        System.err.println();
        Test.printLog();
        System.exit(1);
    }
    if (cl.hasOption(cmd_testdrive)) {
        testdrive = true;
    }
    if (cl.hasOption(cmd_node)) {
        node = Integer.parseInt(cl.getOptionValue(cmd_node));
        nodeFlag = true;
        clusterFlag = true;
    }
    if (cl.hasOption(cmd_email)) {
        email = cl.getOptionValue(cmd_email);
        emailFlag = true;
        clusterFlag = true;
    }
    if (cl.hasOption(cmd_memory)) {
        memory = cl.getOptionValue(cmd_memory);
        memoryFlag = true;
        clusterFlag = true;
    }
    if (cl.hasOption(cmd_walltime)) {
        walltime = Integer.parseInt(cl.getOptionValue(cmd_walltime));
        walltimeFlag = true;
        clusterFlag = true;
    }
    if (cl.hasOption(cmd_submit)) {
        submit = true;
        clusterFlag = true;
    }
    if (help) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("UGMDR", ops);
        System.exit(1);
    }

}