Example usage for java.util ArrayList remove

List of usage examples for java.util ArrayList remove

Introduction

In this page you can find the example usage for java.util ArrayList remove.

Prototype

public boolean remove(Object o) 

Source Link

Document

Removes the first occurrence of the specified element from this list, if it is present.

Usage

From source file:com.concursive.connect.cms.portal.actions.ProjectManagement.java

/**
 * Description of the Method//ww  w.j  ava2s.co m
 *
 * @param context Description of Parameter
 * @return Description of the Returned Value
 */
public String executeCommandProjectCenter(ActionContext context) {
    Connection db = null;
    Project thisProject = null;
    // Parameters
    String projectId = context.getRequest().getParameter("portlet-pid");
    if (projectId == null) {
        projectId = context.getRequest().getParameter("pid");
    }
    if (projectId == null) {
        projectId = (String) context.getRequest().getAttribute("pid");
    }
    // Determine the section to display
    String section = context.getRequest().getParameter("portlet-section");
    if (section == null && context.getRequest().getParameter("portlet-pid") == null) {
        section = context.getRequest().getParameter("section");
    }
    if (section == null || section.equals("")) {
        section = "Profile";
        // Reset any pagedListInfo objects for this new project
        deletePagedListInfo(context, "projectNewsInfo");
        deletePagedListInfo(context, "projectRequirementsInfo");
        deletePagedListInfo(context, "projectAssignmentsInfo");
        deletePagedListInfo(context, "projectIssueCategoryInfo");
        deletePagedListInfo(context, "projectIssuesInfo");
        deletePagedListInfo(context, "projectTicketsInfo");
        deletePagedListInfo(context, "projectTeamInfo");
        deletePagedListInfo(context, "projectAdsInfo");
        deletePagedListInfo(context, "projectClassifiedsInfo");
        deletePagedListInfo(context, "projectEmployeeTeamInfo");
        deletePagedListInfo(context, "projectAccountContactTeamInfo");
        deletePagedListInfo(context, "projectDocumentsGalleryInfo");
        deletePagedListInfo(context, "projectAccountsInfo");
        deletePagedListInfo(context, "projectBadgeInfo");
    }

    // The old URLs may have been bookmarked or indexed, so redirect to new URLs
    String redirect = null;
    // Determine if a redirect is needed
    if ("News".equals(section)) {
        // ProjectManagement.do?command=ProjectCenter&section=News&pid=175 /show/xyz/blog
        redirect = "/show/" + ProjectUtils.loadProject(Integer.parseInt(projectId)).getUniqueId() + "/blog";
    } else if ("Wiki".equals(section)) {
        // ProjectManagement.do?command=ProjectCenter&section=Wiki&pid=175
        // ProjectManagement.do?command=ProjectCenter&section=Wiki&pid=139&subject=Getting+Started+With+Centric+Team+Elements
        String subject = context.getRequest().getParameter("subject");
        redirect = "/show/" + ProjectUtils.loadProject(Integer.parseInt(projectId)).getUniqueId() + "/wiki"
                + (subject != null ? "/" + StringUtils.replace(StringUtils.jsEscape(subject), "%20", "+") : "");
    } else if ("Calendar".equals(section)) {
        // ProjectManagement.do?command=ProjectCenter&section=Calendar&source=Calendar&pid=161&reloadCalendarDetails=true
        redirect = "/show/" + ProjectUtils.loadProject(Integer.parseInt(projectId)).getUniqueId() + "/calendar";
    } else if ("Issues_Categories".equals(section)) {
        // ProjectManagement.do?command=ProjectCenter&section=Issues_Categories&pid=175
        redirect = "/show/" + ProjectUtils.loadProject(Integer.parseInt(projectId)).getUniqueId()
                + "/discussion";
    } else if ("Issues".equals(section)) {
        // ProjectManagement.do?command=ProjectCenter&section=Issues&pid=139&cid=174&resetList=true
        String id = context.getRequest().getParameter("cid");
        redirect = "/show/" + ProjectUtils.loadProject(Integer.parseInt(projectId)).getUniqueId() + "/forum/"
                + id;
    } else if ("File_Library".equals(section)) {
        // ProjectManagement.do?command=ProjectCenter&section=File_Library&pid=175
        // ProjectManagement.do?command=ProjectCenter&section=File_Library&pid=139&folderId=486
        String folderId = context.getRequest().getParameter("folderId");
        if (folderId == null || "-1".equals(folderId)) {
            redirect = "/show/" + ProjectUtils.loadProject(Integer.parseInt(projectId)).getUniqueId()
                    + "/documents";
        } else {
            redirect = "/show/" + ProjectUtils.loadProject(Integer.parseInt(projectId)).getUniqueId()
                    + "/folder/" + folderId;
        }
    } else if ("Team".equals(section)) {
        // ProjectManagement.do?command=ProjectCenter&section=Team&pid=139
        redirect = "/show/" + ProjectUtils.loadProject(Integer.parseInt(projectId)).getUniqueId() + "/members";
        //} else if ("Lists_Categories".equals(section)) {
        // ProjectManagement.do?command=ProjectCenter&section=Lists_Categories&pid=195
        //redirect = "/show/" + ProjectUtils.loadProject(Integer.parseInt(projectId)).getUniqueId() + "/lists";
        //} else if ("Lists".equals(section)) {
        //  // ProjectManagement.do?command=ProjectCenter&section=Lists&pid=195&cid=168
        //  redirect = "/show/" + ProjectUtils.loadProject(Integer.parseInt(projectId)).getUniqueId() + "/list/" + id;
        //} else if ("Requirements".equals(section)) {
        // ProjectManagement.do?command=ProjectCenter&section=Requirements&pid=175
        //  redirect = "/show/" + ProjectUtils.loadProject(Integer.parseInt(projectId)).getUniqueId() + "/plans";
        //} else if ("Assignments".equals(section)) {
        // ProjectManagement.do?command=ProjectCenter&section=Assignments&rid=435&pid=139
        //String id = context.getRequest().getParameter("rid");
        //redirect = "/show/" + ProjectUtils.loadProject(Integer.parseInt(projectId)).getUniqueId() + "/plan/" + id;
        //} else if ("Tickets".equals(section)) {
        // ProjectManagement.do?command=ProjectCenter&section=Tickets&pid=175
        //redirect = "/show/" + ProjectUtils.loadProject(Integer.parseInt(projectId)).getUniqueId() + "/issues";
    }
    // Perform the redirect
    if (redirect != null) {
        context.getRequest().setAttribute("redirectTo", redirect);
        context.getRequest().removeAttribute("PageLayout");
        return "Redirect301";
    }

    try {
        // Determine the project
        thisProject = retrieveAuthorizedProject(Integer.parseInt(projectId), context);

        // Determine the user viewing this page
        User thisUser = getUser(context);

        // If this project requires membership, and guests are not allowed, then show an information page...
        if (!thisProject.getProfile() && !thisUser.getAccessAdmin()
                && thisProject.getFeatures().getMembershipRequired()
                && !thisProject.getFeatures().getAllowGuests()) {
            // Check the status of this user...
            if (!thisProject.getTeam().hasUserId(thisUser.getId())) {
                // You must ask to join
                redirect = "/ProjectManagementTeam.do?command=ConfirmAskToBecomeMember&pid="
                        + thisProject.getId();
                context.getRequest().setAttribute("redirectTo", redirect);
                context.getRequest().removeAttribute("PageLayout");
                return "Redirect301";
            } else if (thisProject.getTeam().getTeamMember(thisUser.getId())
                    .getStatus() != TeamMember.STATUS_ADDED) {
                // Your request is pending...
                return "ConfirmationPendingOK";
            }
        }

        // Determine the database connection to use
        db = getConnection(context);

        // Get this project's badges
        ProjectBadgeList projectBadgeList = new ProjectBadgeList();
        projectBadgeList.setProjectId(thisProject.getId());
        projectBadgeList.buildList(db);
        context.getRequest().setAttribute(Constants.REQUEST_PROJECT_BADGE_LIST, projectBadgeList);

        // Determine the first tab that has permission to
        if ("Profile".equals(section) && (!thisProject.getFeatures().getShowProfile())
                && thisProject.getFeatures().getShowDashboard()) {
            section = "Dashboard";
        }

        // Note: these will be removed and made default once all modules are converted to portal pages
        if ("Profile".equals(section)) {

            LOG.debug("section=" + section);

            // Turn the URL into a ProjectPortalBean
            ProjectPortalBean portalBean = new ProjectPortalBean(context.getRequest());
            if (LOG.isTraceEnabled()) {
                LOG.trace(portalBean.toString());
            }

            // Get the dashboard page with the portlets
            DashboardPage page = ProjectPortalUtils.retrieveDashboardPage(portalBean);
            if (page == null) {
                LOG.warn("Page could not be found for: " + portalBean.getDomainObject());
                return "404Error";
            }
            // Determine the current module
            String tabName = StringUtils.capitalize(portalBean.getModule());

            if (LOG.isDebugEnabled()) {
                LOG.debug("Checking permission... " + page.getPermission() + " and module " + tabName);
                LOG.debug("  Has permission? "
                        + ProjectUtils.hasAccess(portalBean.getProjectId(), thisUser, page.getPermission()));
                LOG.debug("  Tab enabled? "
                        + ObjectUtils.getObject(page.getProject().getFeatures(), "show" + tabName));
            }

            // Make sure the user has access to the page before showing it
            if ((page.getPermission() != null
                    && !ProjectUtils.hasAccess(portalBean.getProjectId(), thisUser, page.getPermission()))
                    || (tabName != null && !(Boolean) ObjectUtils.getObject(page.getProject().getFeatures(),
                            "show" + tabName))) {
                // The module needs permissions...
                if (thisUser.getId() > -1) {
                    // Since the user is logged in, redirect to a permission error page
                    LOG.debug("User is logged in, but doesn't have permission to this module");
                    return "PermissionError";
                } else {
                    // Since the user is not logged in, redirect to a login page
                    LOG.debug("User needs to be logged in for this module and have permission to: "
                            + page.getPermission());
                    String requestedURL = (String) context.getRequest().getAttribute("requestedURL");
                    boolean sslEnabled = "true".equals(getPref(context, "SSL"));
                    ApplicationPrefs prefs = getApplicationPrefs(context);
                    String url = ("http" + (sslEnabled ? "s" : "") + "://"
                            + RequestUtils.getServerUrl(context.getRequest())) + "/login?redirectTo="
                            + requestedURL;
                    context.getRequest().setAttribute("redirectTo", url);
                    return "Redirect301";
                }
            }

            LOG.debug("dashboardPage: " + page.getName());
            // Allow access
            context.getRequest().setAttribute("dashboardPage", page);

            // Set team member info
            TeamMember teamMember = ProjectUtils.retrieveTeamMember(thisProject.getId(), thisUser);
            context.getRequest().setAttribute("currentMember", teamMember);

            // Set shared project searcher
            IIndexerSearch projectSearcher = null;
            if ("true"
                    .equals(context.getServletContext().getAttribute(Constants.DIRECTORY_INDEX_INITIALIZED))) {
                // Search public projects only
                LOG.debug("Using directory index...");
                projectSearcher = SearchUtils.retrieveSearcher(Constants.INDEXER_DIRECTORY);
            } else {
                // Use the full index because the directory hasn't loaded
                LOG.debug("Using full index...");
                projectSearcher = SearchUtils.retrieveSearcher(Constants.INDEXER_FULL);
            }
            // Search public projects only
            String queryString = "(approved:1) " + "AND (guests:1) " + "AND (closed:0) " + "AND (website:0) ";
            // project searcher
            context.getRequest().setAttribute("projectSearcher", projectSearcher);
            context.getRequest().setAttribute("baseQueryString", queryString);

            // Set shared values
            context.getRequest().setAttribute("portletAction", portalBean.getAction());
            context.getRequest().setAttribute("portletDomainObject", portalBean.getDomainObject());
            context.getRequest().setAttribute("portletView", portalBean.getObjectValue());
            context.getRequest().setAttribute("portletParams", portalBean.getParams());

            boolean isAction = PortletManager.processPage(context, db, page);
            if (LOG.isDebugEnabled()) {
                if (context.getResponse().getContentType() != null) {
                    LOG.debug("Content type: " + context.getResponse().getContentType());
                }
            }
            if (isAction) {
                return "-none-";
            }

            // Show the portal
            context.getRequest().setAttribute("includePortal", "portal");

            // Set the portal's tab to the corresponding module
            section = portalBean.getModule();

            if (section == null) {
                LOG.warn("Section is null after processing page");
            }

            if ("text".equals(context.getRequest().getParameter("out"))) {
                return ("ProjectCenterPortalOK");
            }

        } else if ("Dashboard".equals(section)) {
            if (!hasProjectAccess(context, thisProject.getId(), "project-dashboard-view")) {
                return "PermissionError";
            }
            int dashboardId = -1;
            String dashboardValue = context.getRequest().getParameter("dash");
            if (dashboardValue != null) {
                dashboardId = Integer.parseInt(dashboardValue);
            }

            // Get the dashboards for this project for menu
            DashboardList dashboards = new DashboardList();
            dashboards.setProjectId(thisProject.getId());
            dashboards.buildList(db);
            context.getRequest().setAttribute("dashboardList", dashboards);

            // Get the selected dashboard
            Dashboard thisDashboard = dashboards.getSelectedFromId(dashboardId);
            if (thisDashboard != null) {
                context.getRequest().setAttribute("dashboard", thisDashboard);
            }
            // Process this page's portlets
            DashboardPage page = null;

            if (thisDashboard != null) {
                page = new DashboardPage(db, DashboardPage.queryIdFromDashboardId(db, thisDashboard.getId()));
                page.setProjectId(thisProject.getId());
                page.getPortletList().setPageId(page.getId());
                page.getPortletList().buildList(db);
                page.setObjectType(DashboardTemplateList.TYPE_PROJECT_TEMPLATES);
            } else {
                page = new DashboardPage();
                page.setProjectId(thisProject.getId());
                page.setObjectType(DashboardTemplateList.TYPE_PROJECT_TEMPLATES);
                DashboardPortlet contentPortlet = new DashboardPortlet();
                contentPortlet.setName("ContentPortlet");
                contentPortlet.setId(0);
                page.getPortletList().add(contentPortlet);
            }

            // Ready to handle local context
            boolean isAction = PortletManager.processPage(context, db, page);
            if (isAction) {
                return ("-none-");
            }
            context.getRequest().setAttribute("dashboardPage", page);
        } else if ("Requirements".equals(section)) {
            context.getSession().removeAttribute("projectAssignmentsInfo");
            if (!hasProjectAccess(context, thisProject.getId(), "project-plan-view")) {
                return "PermissionError";
            }
            PagedListInfo requirementsInfo = this.getPagedListInfo(context, "projectRequirementsInfo", 50);
            requirementsInfo.setLink(context, ctx(context) + "/show/" + thisProject.getUniqueId() + "/plans");
            // Load the requirements
            RequirementList requirements = new RequirementList();
            requirements.setProjectId(thisProject.getId());
            requirements.setPagedListInfo(requirementsInfo);
            requirements.setBuildAssignments(false);
            if (requirementsInfo.getInitializationLevel() == PagedListInfo.LEVEL_INITIALIZED) {
                requirementsInfo.setListView("open");
            }
            if ("all".equals(requirementsInfo.getListView())) {

            } else if ("closed".equals(requirementsInfo.getListView())) {
                requirements.setClosedOnly(true);
            } else if ("open".equals(requirementsInfo.getListView())) {
                requirements.setOpenOnly(true);
            }
            requirements.buildList(db);
            requirements.buildPlanActivityCounts(db);
            context.getRequest().setAttribute("requirements", requirements);
        } else if ("Assignments".equals(section)) {
            if (!hasProjectAccess(context, thisProject.getId(), "project-plan-view")) {
                return "PermissionError";
            }
            // Configure paged list for handling the list view
            PagedListInfo projectAssignmentsInfo = this.getPagedListInfo(context, "projectAssignmentsInfo");
            projectAssignmentsInfo.setItemsPerPage(0);
            projectAssignmentsInfo.setLink(context,
                    ctx(context) + "/ProjectManagement.do?command=ProjectCenter&section=Assignments&pid="
                            + thisProject.getId());
            //Variables that can be used
            //String folderId = context.getRequest().getParameter("fid");
            String expand = context.getRequest().getParameter("expand");
            String contract = context.getRequest().getParameter("contract");
            String requirementId = context.getRequest().getParameter("rid");
            //Build the requirement and the assignments
            Requirement thisRequirement = new Requirement(db, Integer.parseInt(requirementId));
            context.getRequest().setAttribute("requirement", thisRequirement);
            if ("open".equals(projectAssignmentsInfo.getListView())) {
                thisRequirement.getAssignments().setIncompleteOnly(true);
            } else if ("closed".equals(projectAssignmentsInfo.getListView())) {
                thisRequirement.getAssignments().setClosedOnly(true);
            } else {
                //All
            }
            //HashMap that contains folder state info
            HashMap<Integer, ArrayList> folderState = (HashMap) context.getSession()
                    .getAttribute("AssignmentsFolderState");
            if (folderState == null) {
                folderState = new HashMap<Integer, ArrayList>();
                context.getSession().setAttribute("AssignmentsFolderState", folderState);
            }
            ArrayList<Integer> thisFolderState = folderState.get(thisRequirement.getId());
            if (thisFolderState == null) {
                thisFolderState = new ArrayList<Integer>();
                folderState.put(thisRequirement.getId(), thisFolderState);
            }
            if (expand != null) {
                thisFolderState.add(Integer.parseInt(expand));
            }
            if (contract != null) {
                thisFolderState.remove(new Integer(Integer.parseInt(contract)));
            }
            //thisRequirement.buildPlan(db, thisFolderState);
            //Load the map for displaying in order
            RequirementMapList map = new RequirementMapList();
            map.setProjectId(thisProject.getId());
            map.setRequirementId(thisRequirement.getId());
            map.buildList(db);
            context.getRequest().setAttribute("mapList", map);
            // Load the assignments
            AssignmentList assignments = new AssignmentList();
            assignments.setRequirementId(thisRequirement.getId());
            assignments.buildList(db);
            context.getRequest().setAttribute("assignments", assignments);
            //Filter the maplist
            map.filter(assignments, RequirementMapList.FILTER_PRIORITY,
                    projectAssignmentsInfo.getFilterValue("listFilter1"));
            if ("open".equals(projectAssignmentsInfo.getListView())) {
                map.filterAssignments(assignments, "incompleteOnly");
            } else if ("closed".equals(projectAssignmentsInfo.getListView())) {
                map.filterAssignments(assignments, "closedOnly");
            } else {
                //All
            }
            // Load the assignment folders
            AssignmentFolderList folders = new AssignmentFolderList();
            folders.setRequirementId(thisRequirement.getId());
            folders.buildList(db);
            context.getRequest().setAttribute("folders", folders);
            // Load the Priority Lookup for displaying values
            LookupList priorityList = new LookupList(db, "lookup_project_priority");
            context.getRequest().setAttribute("PriorityList", priorityList);
        } else if ("Lists_Categories".equals(section)) {
            if (!hasProjectAccess(context, thisProject.getId(), "project-lists-view")) {
                return "PermissionError";
            }
            TaskCategoryList categoryList = new TaskCategoryList();
            categoryList.setProjectId(thisProject.getId());
            //Check the pagedList filter
            PagedListInfo projectListsCategoriesInfo = this.getPagedListInfo(context,
                    "projectListsCategoriesInfo");
            projectListsCategoriesInfo.setLink(context,
                    ctx(context) + "/show/" + thisProject.getUniqueId() + "/lists");
            projectListsCategoriesInfo.setItemsPerPage(0);
            //Generate the list
            categoryList.setPagedListInfo(projectListsCategoriesInfo);
            categoryList.buildList(db);
            context.getRequest().setAttribute("categoryList", categoryList);
        } else if ("Lists".equals(section)) {
            if (!hasProjectAccess(context, thisProject.getId(), "project-lists-view")) {
                return "PermissionError";
            }
            String categoryId = context.getRequest().getParameter("cid");
            if (categoryId == null) {
                categoryId = context.getRequest().getParameter("categoryId");
            }
            // Add the category to the request
            LookupElement thisCategory = new LookupElement(db, Integer.parseInt(categoryId),
                    "lookup_task_category");
            context.getRequest().setAttribute("category", thisCategory);

            // Make the filters available
            ProjectItemList functionalAreaList = new ProjectItemList();
            functionalAreaList.setProjectId(projectId);
            //functionalAreaList.setEnabled(Constants.TRUE);
            functionalAreaList.buildList(db, ProjectItemList.LIST_FUNCTIONAL_AREA);
            HtmlSelect functionalAreaSelect = functionalAreaList.getHtmlSelect();
            functionalAreaSelect.addItem(-1, "Any", 0);
            functionalAreaSelect.addItem(0, "Unset", 1);
            context.getRequest().setAttribute("functionalAreaList", functionalAreaSelect);

            ProjectItemList complexityList = new ProjectItemList();
            complexityList.setProjectId(projectId);
            //complexityList.setEnabled(Constants.TRUE);
            complexityList.buildList(db, ProjectItemList.LIST_COMPLEXITY);
            HtmlSelect complexitySelect = complexityList.getHtmlSelect();
            complexitySelect.addItem(-1, "Any", 0);
            complexitySelect.addItem(0, "Unset", 1);
            context.getRequest().setAttribute("complexityList", complexitySelect);

            ProjectItemList businessValueList = new ProjectItemList();
            businessValueList.setProjectId(projectId);
            //businessValueList.setEnabled(Constants.TRUE);
            businessValueList.buildList(db, ProjectItemList.LIST_VALUE);
            HtmlSelect businessValueSelect = businessValueList.getHtmlSelect();
            businessValueSelect.addItem(-1, "Any", 0);
            businessValueSelect.addItem(0, "Unset", 1);
            context.getRequest().setAttribute("businessValueList", businessValueSelect);

            ProjectItemList targetSprintList = new ProjectItemList();
            targetSprintList.setProjectId(projectId);
            //targetSprintList.setEnabled(Constants.TRUE);
            targetSprintList.buildList(db, ProjectItemList.LIST_TARGET_SPRINT);
            HtmlSelect targetSprintSelect = targetSprintList.getHtmlSelect();
            targetSprintSelect.addItem(-1, "Any", 0);
            targetSprintSelect.addItem(0, "Unset", 1);
            context.getRequest().setAttribute("targetSprintList", targetSprintSelect);

            ProjectItemList targetReleaseList = new ProjectItemList();
            targetReleaseList.setProjectId(projectId);
            //targetReleaseList.setEnabled(Constants.TRUE);
            targetReleaseList.buildList(db, ProjectItemList.LIST_TARGET_RELEASE);
            HtmlSelect targetReleaseSelect = targetReleaseList.getHtmlSelect();
            targetReleaseSelect.addItem(-1, "Any", 0);
            targetReleaseSelect.addItem(0, "Unset", 1);
            context.getRequest().setAttribute("targetReleaseList", targetReleaseSelect);

            ProjectItemList statusList = new ProjectItemList();
            statusList.setProjectId(projectId);
            //statusList.setEnabled(Constants.TRUE);
            statusList.buildList(db, ProjectItemList.LIST_STATUS);
            HtmlSelect statusSelect = statusList.getHtmlSelect();
            statusSelect.addItem(-1, "Any", 0);
            statusSelect.addItem(0, "Unset", 1);
            context.getRequest().setAttribute("statusList", statusSelect);

            ProjectItemList loeRemainingList = new ProjectItemList();
            loeRemainingList.setProjectId(projectId);
            //loeRemainingList.setEnabled(Constants.TRUE);
            loeRemainingList.buildList(db, ProjectItemList.LIST_LOE_REMAINING);
            HtmlSelect loeRemainingSelect = loeRemainingList.getHtmlSelect();
            loeRemainingSelect.addItem(-1, "Any", 0);
            loeRemainingSelect.addItem(0, "Unset", 1);
            context.getRequest().setAttribute("loeRemainingList", loeRemainingSelect);

            ProjectItemList assignedPriorityList = new ProjectItemList();
            assignedPriorityList.setProjectId(projectId);
            //priorityList.setEnabled(Constants.TRUE);
            assignedPriorityList.buildList(db, ProjectItemList.LIST_ASSIGNED_PRIORITY);
            HtmlSelect assignedPrioritySelect = assignedPriorityList.getHtmlSelect();
            assignedPrioritySelect.addItem(-1, "Any", 0);
            assignedPrioritySelect.addItem(0, "Unset", 1);
            context.getRequest().setAttribute("assignedPriorityList", assignedPrioritySelect);

            // Make the users that own tasks available
            TeamMemberList tmpTeamList = new TeamMemberList();
            tmpTeamList.setProjectId(thisProject.getId());
            tmpTeamList.buildList(db);
            Map<Integer, TeamMember> teamMap = new HashMap<Integer, TeamMember>();
            for (TeamMember tm : tmpTeamList) {
                teamMap.put(tm.getUserId(), tm);
            }
            TeamMemberList teamMemberList = new TeamMemberList();
            TaskList allTaskList = new TaskList();
            allTaskList.setProjectId(thisProject.getId());
            allTaskList.setCategoryId(Integer.parseInt(categoryId));
            allTaskList.buildList(db);
            for (Task t : allTaskList) {
                TeamMember tm = teamMap.get(t.getOwner());
                if (tm != null) {
                    teamMap.remove(t.getOwner()); //remove so teammembers are not added more than once
                    teamMemberList.add(tm);
                }
            }
            context.getRequest().setAttribute("teamMemberList", teamMemberList);

            // Build the list items
            TaskList outlineList = new TaskList();
            outlineList.setProjectId(thisProject.getId());
            outlineList.setCategoryId(Integer.parseInt(categoryId));
            // Check the pagedList filter
            PagedListInfo projectListsInfo = this.getPagedListInfo(context, "projectListsInfo");
            projectListsInfo.setLink(context, ctx(context) + "/show/" + thisProject.getUniqueId() + "/list/"
                    + Integer.parseInt(categoryId));
            projectListsInfo.setItemsPerPage(0);
            if ("open".equals(projectListsInfo.getListView())) {
                outlineList.setComplete(Constants.FALSE);
            } else if ("closed".equals(projectListsInfo.getListView())) {
                outlineList.setComplete(Constants.TRUE);
            } else {
                outlineList.setComplete(Constants.UNDEFINED);
            }
            if (projectListsInfo.hasListFilter("listFilter1")) {
                outlineList.setFunctionalArea(projectListsInfo.getFilterValueAsInt("listFilter1"));
            }
            if (projectListsInfo.hasListFilter("listFilter2")) {
                outlineList.setComplexity(projectListsInfo.getFilterValueAsInt("listFilter2"));
            }
            if (projectListsInfo.hasListFilter("listFilter3")) {
                outlineList.setBusinessValue(projectListsInfo.getFilterValueAsInt("listFilter3"));
            }
            if (projectListsInfo.hasListFilter("listFilter4")) {
                outlineList.setTargetSprint(projectListsInfo.getFilterValueAsInt("listFilter4"));
            }
            if (projectListsInfo.hasListFilter("listFilter5")) {
                outlineList.setTargetRelease(projectListsInfo.getFilterValueAsInt("listFilter5"));
            }
            if (projectListsInfo.hasListFilter("listFilter6")) {
                outlineList.setStatus(projectListsInfo.getFilterValueAsInt("listFilter6"));
            }
            if (projectListsInfo.hasListFilter("listFilter7")) {
                outlineList.setLoeRemaining(projectListsInfo.getFilterValueAsInt("listFilter7"));
            }
            if (projectListsInfo.hasListFilter("listFilter8")) {
                outlineList.setOwner(projectListsInfo.getFilterValueAsInt("listFilter8"));
            }
            if (projectListsInfo.hasListFilter("listFilter9")) {
                outlineList.setAssignedPriority(projectListsInfo.getFilterValueAsInt("listFilter9"));
            }
            // Generate the list
            outlineList.setPagedListInfo(projectListsInfo);
            outlineList.buildList(db);
            HashMap<Integer, String> taskUrlMap = new HashMap<Integer, String>();
            for (Task t : outlineList) {
                //@TODO move this into TaskList to reduce overhead
                t.buildOwnerLinkedItemRating(db);
                String linkItemUrl = TaskUtils.getLinkItemUrl(thisUser, ctx(context), t);
                if (linkItemUrl != null) {
                    taskUrlMap.put(t.getId(), linkItemUrl);
                }
            }
            context.getRequest().setAttribute("taskUrlMap", taskUrlMap);
            context.getRequest().setAttribute("outlineList", outlineList);
        } else if ("Tickets".equals(section)) {
            if (!hasProjectAccess(context, thisProject.getId(), "project-tickets-view")) {
                return "PermissionError";
            }
            TicketList tickets = new TicketList();
            PagedListInfo projectTicketsInfo = this.getPagedListInfo(context, "projectTicketsInfo");
            projectTicketsInfo.setLink(context,
                    ctx(context) + "/show/" + thisProject.getUniqueId() + "/issues");
            projectTicketsInfo.setMode(PagedListInfo.LIST_VIEW);
            if (projectTicketsInfo.getListView() == null) {
                projectTicketsInfo.setListView("open");
                // Categories
                projectTicketsInfo.addFilter(1, "-1");
            }
            tickets.setPagedListInfo(projectTicketsInfo);
            tickets.setProjectId(thisProject.getId());
            if (!hasProjectAccess(context, thisProject.getId(), "project-tickets-other")) {
                tickets.setOwnTickets(getUser(context).getId());
            }
            if ("all".equals(projectTicketsInfo.getListView())) {

            } else if ("review".equals(projectTicketsInfo.getListView())) {
                tickets.setOnlyOpen(true);
                tickets.setForReview(Constants.TRUE);
            } else if ("closed".equals(projectTicketsInfo.getListView())) {
                tickets.setOnlyClosed(true);
            } else {
                tickets.setOnlyOpen(true);
            }
            tickets.setCatCode(projectTicketsInfo.getFilterValueAsInt("listFilter1"));
            tickets.buildList(db);
            context.getRequest().setAttribute("ticketList", tickets);

            // Prepare the list of categories to display, based on categories used
            TicketCategoryList categoryList = new TicketCategoryList();
            categoryList.setProjectId(thisProject.getId());
            categoryList.setEnabledState(Constants.TRUE);
            categoryList.setCatLevel(0);
            categoryList.buildList(db);
            HtmlSelect thisSelect = categoryList.getHtmlSelect();
            thisSelect.addItem(-1, "All Categories", 0);
            context.getRequest().setAttribute("ticketCategoryList", thisSelect);
            // Try out the YUI list
            // TODO: Make a generic method for using JSON and YUI
            /*
            if ("json".equals(context.getRequest().getParameter("format"))) {
              section += "_json";
            } else {
              section = "tickets_yui";
            }
            */
        } else {
            // Just looking at the details
            if (!hasProjectAccess(context, thisProject.getId(), "project-details-view")) {
                return "PermissionError";
            }
            // Prepare the list of categories to display
            ProjectCategoryList categoryList = new ProjectCategoryList();
            if (thisProject.getCategoryId() > -1) {
                categoryList.setCategoryId(thisProject.getCategoryId());
                categoryList.buildList(db);
            }
            context.getRequest().setAttribute("projectCategoryList", categoryList);
        }
        context.getRequest().setAttribute("project", thisProject);
        context.getRequest().setAttribute("IncludeSection", section.toLowerCase(Locale.ENGLISH));
        // The user has access, so show that they accessed the project
        TeamMember.updateLastAccessed(db, thisProject.getId(), getUser(context));
        // This project is being accessed so trigger the view hook
        processSelectHook(context, thisProject);
        return ("ProjectCenterOK");
    } catch (Exception errorMessage) {
        context.getRequest().setAttribute("Error", errorMessage);
        LOG.error("error", errorMessage);
        return "404Error";
    } finally {
        if (db != null) {
            freeConnection(context, db);
        }
    }
}

From source file:hu.sztaki.ilab.bigdata.common.tools.InputSampler.java

/**
 * Driver for InputSampler from the command line.
 * Configures a JobConf instance and calls {@link #writePartitionFile}.
 */// w w w. j  av  a 2 s .  c  om
public int run(String[] args) throws Exception {
    Job job = new Job(getConf());
    ArrayList<String> otherArgs = new ArrayList<String>();
    Sampler<K, V> sampler = null;
    for (int i = 0; i < args.length; ++i) {
        try {
            if ("-r".equals(args[i])) {
                job.setNumReduceTasks(Integer.parseInt(args[++i]));
            } else if ("-inFormat".equals(args[i])) {
                job.setInputFormatClass(Class.forName(args[++i]).asSubclass(InputFormat.class));
            } else if ("-keyClass".equals(args[i])) {
                job.setMapOutputKeyClass(Class.forName(args[++i]).asSubclass(WritableComparable.class));
            } else if ("-splitSample".equals(args[i])) {
                int numSamples = Integer.parseInt(args[++i]);
                int maxSplits = Integer.parseInt(args[++i]);
                if (0 >= maxSplits)
                    maxSplits = Integer.MAX_VALUE;
                sampler = new SplitSampler<K, V>(numSamples, maxSplits);
            } else if ("-splitRandom".equals(args[i])) {
                double pcnt = Double.parseDouble(args[++i]);
                int numSamples = Integer.parseInt(args[++i]);
                int maxSplits = Integer.parseInt(args[++i]);
                if (0 >= maxSplits)
                    maxSplits = Integer.MAX_VALUE;
                sampler = new RandomSampler<K, V>(pcnt, numSamples, maxSplits);
            } else if ("-splitInterval".equals(args[i])) {
                double pcnt = Double.parseDouble(args[++i]);
                int maxSplits = Integer.parseInt(args[++i]);
                if (0 >= maxSplits)
                    maxSplits = Integer.MAX_VALUE;
                sampler = new IntervalSampler<K, V>(pcnt, maxSplits);
            } else {
                otherArgs.add(args[i]);
            }
        } catch (NumberFormatException except) {
            System.out.println("ERROR: Integer expected instead of " + args[i]);
            return printUsage();
        } catch (ArrayIndexOutOfBoundsException except) {
            System.out.println("ERROR: Required parameter missing from " + args[i - 1]);
            return printUsage();
        }
    }
    if (job.getNumReduceTasks() <= 1) {
        System.err.println("Sampler requires more than one reducer");
        return printUsage();
    }
    if (otherArgs.size() < 2) {
        System.out.println("ERROR: Wrong number of parameters: ");
        return printUsage();
    }
    if (null == sampler) {
        sampler = new RandomSampler<K, V>(0.1, 10000, 10);
    }

    Path outf = new Path(otherArgs.remove(otherArgs.size() - 1));
    TotalOrderPartitioner.setPartitionFile(getConf(), outf);
    for (String s : otherArgs) {
        FileInputFormat.addInputPath(job, new Path(s));
    }
    InputSampler.<K, V>writePartitionFile(job, sampler);

    return 0;
}

From source file:com.ntua.cosmos.hackathonplanneraas.Planner.java

public ArrayList<ArrayList<String>> searchIotService(String domain) {
    ArrayList<ArrayList<String>> solution = new ArrayList<>();
    int i = 0;//w ww. j a  v a  2 s  . c o m
    String servicename;
    String prevser = "";
    String prevURI = "";
    String URI;
    ArrayList<String> paramname = new ArrayList<>();
    ArrayList<String> respname = new ArrayList<>();
    StoredPaths pan = new StoredPaths();
    OntModel m = createModel(StoredPaths.servicepath);
    //begin building query string.
    String queryString = pan.prefixrdf + pan.prefixowl + pan.prefixxsd + pan.prefixrdfs + pan.prefixServicePath;
    queryString += "\nselect distinct ?service ?URI ?namep ?namer " + "where{?service base:isServiceOf base:"
            + domain + " . " + "?service base:usesComponent ?comp . ?comp base:hasRESTParameter ?param . "
            + "?comp base:hasRESTResponce ?resp . ?comp base:accessURI ?URI . "
            + "?param base:hasName ?namep . ?resp base:hasName ?namer} order by ?service ?namer";
    System.out.println(queryString);
    try {
        Query query = QueryFactory.create(queryString);
        QueryExecution qe = QueryExecutionFactory.create(query, m);
        ResultSet results = qe.execSelect();
        for (; results.hasNext();) {
            QuerySolution soln = results.nextSolution();
            // Access variables: soln.get("x");
            Resource res = soln.getResource("service");
            Literal lit = soln.getLiteral("URI");
            Literal lit2 = soln.getLiteral("namep");
            Literal lit3 = soln.getLiteral("namer");
            servicename = res.getURI().substring(res.getURI().indexOf('#') + 1);
            URI = lit.getString();

            if (prevser.equalsIgnoreCase("") && prevURI.equalsIgnoreCase("")) {
                prevser = servicename;
                prevURI = URI;
                respname.add(lit3.getString());
                respname.add("^");
                paramname.add(lit2.getString());
                paramname.add("^");
            }
            if (!servicename.equalsIgnoreCase(prevser)) {
                solution.add(new ArrayList<>(Arrays.asList(prevser, "^", prevURI)));
                solution.add(new ArrayList<>(Arrays.asList("&")));
                paramname.remove(paramname.size() - 1);
                solution.add(new ArrayList<>(paramname));
                solution.add(new ArrayList<>(Arrays.asList("&")));
                respname.remove(respname.size() - 1);
                solution.add(new ArrayList<>(respname));
                solution.add(new ArrayList<>(Arrays.asList("&")));
                prevser = servicename;
                prevURI = URI;
                paramname.clear();
                respname.clear();
            }
            if (!paramname.contains(lit2.getString())) {
                paramname.add(lit2.getString());
                paramname.add("^");
            }
            if (!lit3.getString().equalsIgnoreCase(respname.get(i))) {
                respname.add(lit3.getString());
                respname.add("^");
                //paramname.clear();
                i++;
                i++;
            }
        }
        solution.add(new ArrayList<>(Arrays.asList(prevser, "^", prevURI)));
        solution.add(new ArrayList<>(Arrays.asList("&")));
        paramname.remove(paramname.size() - 1);
        solution.add(new ArrayList<>(paramname));
        solution.add(new ArrayList<>(Arrays.asList("&")));
        respname.remove(respname.size() - 1);
        solution.add(new ArrayList<>(respname));
        //solution.add(new ArrayList<>(Arrays.asList("&")));
        qe.close();
    } catch (NumberFormatException e) {
        System.out.println("Query not valid.");
    }
    m.close();
    return solution;
}

From source file:ComRoughSetApproInputSampler.java

/**
 * Driver for InputSampler from the command line.
 * Configures a JobConf instance and calls {@link #writePartitionFile}.
 */// w  ww .ja v  a  2 s.  co m
public int run(String[] args) throws Exception {
    Job job = new Job(getConf());
    ArrayList<String> otherArgs = new ArrayList<String>();
    Sampler<K, V> sampler = null;
    for (int i = 0; i < args.length; ++i) {
        try {
            if ("-r".equals(args[i])) {
                job.setNumReduceTasks(Integer.parseInt(args[++i]));
            } else if ("-inFormat".equals(args[i])) {
                job.setInputFormatClass(Class.forName(args[++i]).asSubclass(InputFormat.class));
            } else if ("-keyClass".equals(args[i])) {
                job.setMapOutputKeyClass(Class.forName(args[++i]).asSubclass(WritableComparable.class));
            } else if ("-splitSample".equals(args[i])) {
                int numSamples = Integer.parseInt(args[++i]);
                int maxSplits = Integer.parseInt(args[++i]);
                if (0 >= maxSplits)
                    maxSplits = Integer.MAX_VALUE;
                sampler = new SplitSampler<K, V>(numSamples, maxSplits);
            } else if ("-splitRandom".equals(args[i])) {
                double pcnt = Double.parseDouble(args[++i]);
                int numSamples = Integer.parseInt(args[++i]);
                int maxSplits = Integer.parseInt(args[++i]);
                if (0 >= maxSplits)
                    maxSplits = Integer.MAX_VALUE;
                sampler = new RandomSampler<K, V>(pcnt, numSamples, maxSplits);
            } else if ("-splitInterval".equals(args[i])) {
                double pcnt = Double.parseDouble(args[++i]);
                int maxSplits = Integer.parseInt(args[++i]);
                if (0 >= maxSplits)
                    maxSplits = Integer.MAX_VALUE;
                sampler = new IntervalSampler<K, V>(pcnt, maxSplits);
            } else {
                otherArgs.add(args[i]);
            }
        } catch (NumberFormatException except) {
            System.out.println("ERROR: Integer expected instead of " + args[i]);
            return printUsage();
        } catch (ArrayIndexOutOfBoundsException except) {
            System.out.println("ERROR: Required parameter missing from " + args[i - 1]);
            return printUsage();
        }
    }
    if (job.getNumReduceTasks() <= 1) {
        System.err.println("Sampler requires more than one reducer");
        return printUsage();
    }
    if (otherArgs.size() < 2) {
        System.out.println("ERROR: Wrong number of parameters: ");
        return printUsage();
    }
    if (null == sampler) {
        sampler = new RandomSampler<K, V>(0.1, 10000, 10);
    }

    Path outf = new Path(otherArgs.remove(otherArgs.size() - 1));
    TotalOrderPartitioner.setPartitionFile(getConf(), outf);
    for (String s : otherArgs) {
        FileInputFormat.addInputPath(job, new Path(s));
    }
    ComRoughSetApproInputSampler.<K, V>writePartitionFile(job, sampler);

    return 0;
}

From source file:ch.epfl.lsir.xin.algorithm.core.BiasedMF.java

/**
 * SGD learning /*w ww .j  av a 2 s.co m*/
 * */
public void buildSGD() {
    double preError = Double.MAX_VALUE;
    for (int i = 0; i < this.iterations; i++) {
        System.out.println("Iteration: " + i);
        ArrayList<MatrixEntry2D> entries = this.ratingMatrix.getValidEntries();
        double error = 0; //overall error of this iteration
        while (entries.size() > 0) {
            //find a random entry
            int r = new Random().nextInt(entries.size());
            MatrixEntry2D entry = entries.get(r);
            double prediction = predict(entry.getRowIndex(), entry.getColumnIndex(), false);
            if (prediction > this.maxRating)
                prediction = this.maxRating;
            if (prediction < this.minRating)
                prediction = this.minRating;
            double difference = entry.getValue() - prediction;

            //update user bias
            double newUserBias = this.userBias[entry.getRowIndex()] + this.biasLearningRate
                    * (difference - this.biasUserReg * this.userBias[entry.getRowIndex()]);
            this.userBias[entry.getRowIndex()] = newUserBias;
            //update item bias
            double newItemBias = this.itemBias[entry.getColumnIndex()] + this.biasLearningRate
                    * (difference - this.biasItemReg * this.itemBias[entry.getColumnIndex()]);
            this.itemBias[entry.getColumnIndex()] = newItemBias;

            //update user and item latent factors
            for (int j = 0; j < this.latentFactors; j++) {
                //update user factors
                double newUserFactors = this.userMatrix.get(entry.getRowIndex(), j)
                        + this.learningRate * (difference * this.itemMatrix.get(entry.getColumnIndex(), j)
                                - this.userReg * this.userMatrix.get(entry.getRowIndex(), j));
                //update item factors
                double newItemFactors = this.itemMatrix.get(entry.getColumnIndex(), j)
                        + this.learningRate * (difference * this.userMatrix.get(entry.getRowIndex(), j)
                                - this.itemReg * this.itemMatrix.get(entry.getColumnIndex(), j));
                this.userMatrix.set(entry.getRowIndex(), j, newUserFactors);
                this.itemMatrix.set(entry.getColumnIndex(), j, newItemFactors);
            }

            //one rating is only processed once in an iteration
            entries.remove(r);
        }
        //error
        entries = this.ratingMatrix.getValidEntries();
        for (int k = 0; k < entries.size(); k++) {
            MatrixEntry2D entry = entries.get(k);
            double prediction = predict(entry.getRowIndex(), entry.getColumnIndex(), false);
            if (prediction > this.maxRating)
                prediction = this.maxRating;
            if (prediction < this.minRating)
                prediction = this.minRating;
            error = error + Math.abs(entry.getValue() - prediction);
            //            for( int j = 0 ; j < this.latentFactors ; j++ )
            //            {
            //               error = error + this.regUser/2 * Math.pow(this.userMatrix.get(entry.getRowIndex(), j), 2) + 
            //                     this.regItem/2 * Math.pow(this.itemMatrix.get(entry.getColumnIndex(), j), 2);
            //            }      
        }
        this.logger.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " Iteration " + i
                + " : Error ~ " + error);
        this.logger.flush();
        //check for convergence
        if (Math.abs(error - preError) <= this.convergence && error <= preError) {
            logger.println("The algorithm convergences.");
            this.logger.flush();
            break;
        }
        // learning rate update strategy 
        updateLearningRate(error, preError);

        preError = error;
        logger.flush();
    }
}

From source file:co.paralleluniverse.galaxy.core.Cache.java

private void removePendingOp(CacheLine line, Op op) {
    ArrayList<Op> ops = pendingOps.get(op.line);
    if (ops == null)
        return;//from   w w  w  .  j  av  a 2 s .co m
    ops.remove(op);
    if (ops.isEmpty())
        pendingOps.remove(op.line);
}

From source file:edu.mayo.informatics.lexgrid.convert.directConversions.hl7.HL7MapToLexGrid.java

void loadArtificialTopNodes(CodingScheme csclass, Entities concepts, Connection c) {
    messages_.info("Processing code systems into top nodes");
    ResultSet topNode_results = null;
    try {/*from w  ww.j a v  a  2 s. c o m*/
        // Create an "@" top node.
        Entity rootNode = new Entity();

        // Create and set the concept code for "@"
        String topNodeDesignation = "@";
        rootNode.setEntityCode(topNodeDesignation);
        rootNode.setEntityCodeNamespace(csclass.getCodingSchemeName());
        rootNode.setIsAnonymous(Boolean.TRUE);
        EntityDescription enDesc = new EntityDescription();
        enDesc.setContent("Root node for subclass relations.");
        rootNode.setEntityDescription(enDesc);
        concepts.addEntity(rootNode);

        AssociationSource ai = new AssociationSource();
        ai.setSourceEntityCode(rootNode.getEntityCode());
        ai.setSourceEntityCodeNamespace(csclass.getCodingSchemeName());
        AssociationPredicate parent_assoc = (AssociationPredicate) RelationsUtil
                .resolveAssociationPredicates(csclass, HL72LGConstants.ASSOCIATION_HAS_SUBTYPE).get(0);
        ai = RelationsUtil.subsume(parent_assoc, ai);

        // Get all the code systems except the
        // legacy code system coding scheme in HL7
        PreparedStatement getArtificialTopNodeData = c
                .prepareStatement("select cs.*, code.internalId FROM VCS_code_system AS cs "
                        + "LEFT JOIN  VCS_concept_code_xref AS code "
                        + "ON cs.codeSystemName= code.conceptCode2 "
                        + "where (code.codeSystemId2 = ? OR code.codeSystemId2 is null) AND cs.codesystemid <> ?");
        getArtificialTopNodeData.setString(1, HL72LGConstants.CODE_SYSTEM_OID);
        getArtificialTopNodeData.setString(2, HL72LGConstants.CODE_SYSTEM_OID);
        ResultSet dataResults = getArtificialTopNodeData.executeQuery();
        while (dataResults.next()) {
            Entity topNode = new Entity();
            String nodeName = dataResults.getString("codeSystemName");
            String entityDescription = dataResults.getString("fullName");
            String oid = dataResults.getString("codeSystemId");
            String def = dataResults.getString("description");
            String internalId = dataResults.getString("internalId");
            if (StringUtils.isNotBlank(def)) {
                int begin = def.lastIndexOf("<p>");
                int end = def.lastIndexOf("</p>");
                if (begin > -1) {
                    if (begin + 3 < end)
                        def = def.substring(begin + 3, end);
                }
            }

            if (StringUtils.isNotBlank(internalId)) {
                topNode.setEntityCode(internalId + ":" + nodeName);
            } else {
                topNode.setEntityCode(nodeName + ":" + nodeName);
            }
            topNode.setEntityCodeNamespace(csclass.getCodingSchemeName());

            EntityDescription enD = new EntityDescription();
            enD.setContent(entityDescription);
            topNode.setEntityDescription(enD);
            topNode.setIsActive(true);

            // Set presentation so it's a full fledged concept
            Presentation p = new Presentation();
            Text txt = new Text();
            txt.setContent((String) entityDescription);
            p.setValue(txt);
            p.setIsPreferred(Boolean.TRUE);
            p.setPropertyName(HL72LGConstants.PROPERTY_PRINTNAME);
            p.setPropertyId("T1");
            p.setLanguage(HL72LGConstants.DEFAULT_LANGUAGE_EN);
            topNode.addPresentation(p);

            // Set definition
            if (StringUtils.isNotBlank(def)) {
                Definition definition = new Definition();
                Text defText = new Text();
                defText.setContent(def);
                definition.setValue(defText);
                definition.setPropertyName(HL72LGConstants.PROPERTY_DEFINITION);
                definition.setPropertyId("D1");
                definition.setIsActive(Boolean.TRUE);
                definition.setIsPreferred(Boolean.TRUE);
                definition.setLanguage(HL72LGConstants.DEFAULT_LANGUAGE_EN);
                topNode.addDefinition(definition);
            }

            topNode.addEntityType(EntityTypes.CONCEPT.toString());
            concepts.addEntity(topNode);

            // This coding scheme is attached to an artificial root.
            AssociationTarget at = new AssociationTarget();
            at.setTargetEntityCode(topNode.getEntityCode());
            at.setTargetEntityCodeNamespace(csclass.getCodingSchemeName());
            RelationsUtil.subsume(ai, at);

            // Now find the top nodes of the scheme and subsume them to this
            // scheme's artificial top node.
            // First get a list of all nodes in the scheme.
            // but again exclude the code system nodes.
            ArrayList<String> topNodes = new ArrayList<String>();
            PreparedStatement getSystemCodes = c.prepareStatement(
                    "SELECT DISTINCT (internalId), conceptCode2 FROM VCS_concept_code_xref WHERE codeSystemId2 =? AND codeSystemId2 <> ?");
            getSystemCodes.setString(1, oid);
            getSystemCodes.setString(2, HL72LGConstants.CODE_SYSTEM_OID);
            ResultSet systemCodes = getSystemCodes.executeQuery();
            while (systemCodes.next()) {
                String testCode = systemCodes.getString("internalId");
                if (testCode != null)
                    topNodes.add(testCode);
            }
            if (systemCodes != null)
                systemCodes.close();
            if (getSystemCodes != null)
                getSystemCodes.close();

            // Drop any from the list that aren't top nodes.
            ArrayList<String> nodesToRemove = new ArrayList<String>();
            PreparedStatement checkForTopNode = null;
            for (int i = 0; i < topNodes.size(); i++) {
                checkForTopNode = c.prepareStatement(
                        "SELECT targetInternalId FROM VCS_concept_relationship WHERE targetInternalId =?");
                checkForTopNode.setString(1, (String) topNodes.get(i));
                topNode_results = checkForTopNode.executeQuery();
                if (topNode_results.next()) {
                    if (topNodes.get(i).equals(topNode_results.getString(1))) {
                        nodesToRemove.add(topNodes.get(i));
                    }
                }
                if (topNode_results != null)
                    topNode_results.close();
                if (checkForTopNode != null)
                    checkForTopNode.close();
            }

            for (int i = 0; i < nodesToRemove.size(); i++) {
                topNodes.remove(nodesToRemove.get(i));
            }
            // Get the full concept code for each.
            PreparedStatement getconceptSuffix = null;
            ResultSet conceptCode = null;
            for (int i = 0; i < topNodes.size(); i++) {
                getconceptSuffix = c.prepareStatement(
                        "SELECT conceptCode2 FROM VCS_concept_code_xref where internalId = ?");

                getconceptSuffix.setString(1, (String) topNodes.get(i));
                conceptCode = getconceptSuffix.executeQuery();
                conceptCode.next();
                topNodes.set(i, topNodes.get(i) + ":" + conceptCode.getString(1));
                if (conceptCode != null)
                    conceptCode.close();
                if (getconceptSuffix != null)
                    getconceptSuffix.close();
            }

            // For each top node subsume to the current artificial node for
            // the scheme.
            for (int j = 0; j < topNodes.size(); j++) {
                try {
                    AssociationSource atn = new AssociationSource();
                    atn.setSourceEntityCode(topNode.getEntityCode());
                    atn.setSourceEntityCodeNamespace(csclass.getCodingSchemeName());
                    atn = RelationsUtil.subsume(parent_assoc, atn);

                    AssociationTarget atopNode = new AssociationTarget();
                    atopNode.setTargetEntityCode((String) topNodes.get(j));
                    atopNode.setTargetEntityCodeNamespace(csclass.getCodingSchemeName());
                    RelationsUtil.subsume(atn, atopNode);
                } catch (Exception e) {
                    messages_.error("Failed while processing HL7 psuedo top node hierarchy", e);
                    e.printStackTrace();
                }
            }
        }
        dataResults.close();
        messages_.info("Top node processing complete");
    } catch (Exception e) {
        messages_.error("Top node processing failed", e);
        e.printStackTrace();
    }

}

From source file:es.pode.empaquetador.negocio.servicio.SrvGestorManifestServiceImpl.java

/**
 * Elimina un submanifiesto del ODE en que se esta trabajando. No elimina
 * los archivos, ya que esta funcionalidad se puede realizar desde el gestor
 * de archivos.//from  ww w.  j a  va2 s  .  c o m
 * 
 * @param identificador
 *            Identificador del ODE en que estamos trabajando.
 * @param submanifiestoId
 *            Identificador del submanifiesto que se desea eliminar.
 * @param idSubmanifestPadre
 *            Identificador del submanifiesto en que estamos navegando, y
 *            que es el padre del submanifiesto a eliminar. Si estamos
 *            navegando en el manifiesto principal, idSUbmanifestPadre =
 *            null
 * @return Ode modificado
 * @throws Exception
 */
@Override
protected String handleEliminarSubmanifiesto(String identificador, String submanifiestoId,
        String idSubmanifestPadre) throws Exception {

    Manifest manifest = null;
    String nombreSubmanifiestoEliminar = VACIA;
    String idPadre = idSubmanifestPadre == null ? identificador : idSubmanifestPadre;
    Object obj = cacheEmpaquetacion.get(idPadre);
    OdeVO ode = null;

    if (obj instanceof es.pode.parseadorXML.castor.Manifest) {
        logger.debug("El ode " + ode + " es de tipo manifest");
        manifest = (Manifest) obj;
        Manifest[] arrayManifest = manifest.getManifest();
        ArrayList tempList = new ArrayList();
        tempList.addAll(Arrays.asList(arrayManifest));

        for (int i = 0; i < tempList.size(); i++) {
            if (((Manifest) tempList.get(i)).getIdentifier().equals(submanifiestoId)) {
                //Submanifiesto a eliminar
                nombreSubmanifiestoEliminar = ((Manifest) tempList.get(i)).getBase();
                tempList.remove(i);
            }
        }
        logger.debug("voy a insertar en el manifest el nuevo array de Submanifest sin el que quiero borrar");
        manifest.setManifest((Manifest[]) tempList.toArray(new Manifest[tempList.size()]));

        //Hallar la carpeta padre
        Manifest principal = (Manifest) cacheEmpaquetacion.get(identificador);
        String path = null;
        for (int i = 0; i < principal.getManifestCount() && path == null; i++) {
            // llamada recursiva a obtenerSubm devuelve el path completo
            path = obtenerSubm(principal.getManifest(i), idSubmanifestPadre);
        }
        if (logger.isDebugEnabled())
            logger.debug("Ruta relativa del submanifiesto " + idSubmanifestPadre + " : " + path);
        //         rutaSubmanifest = crearRuta(manifest, idSubmanifestPadre, null, this.getSrvLocalizadorService().consultaLocalizador(identificador));
        //Se elimina los recursos      
        ArchivoVO ficheros = new ArchivoVO();
        ficheros.setCarpetaPadre(path);
        ficheros.setEsFichero(Boolean.FALSE);
        ficheros.setNombre(nombreSubmanifiestoEliminar);
        this.getSrvGestorArchivosService().eliminar(identificador, new ArchivoVO[] { ficheros });
    } else {
        if (obj == null) {
            ode = null;
        } else {
            logger.warn("el ode " + ode + " no es de tipo manifest");
            throw new AlmacenamientoException("el ode no es de tipo manifest");
        }
    }
    cacheEmpaquetacion.put(idPadre, manifest);

    return submanifiestoId;

}

From source file:com.github.dougkelly88.FLIMPlateReaderGUI.SequencingClasses.GUIComponents.XYSequencing.java

private ArrayList<FOV> generateSpiral11(int noFOV, String wellString) {

    // cover whole well in a rectangle; remove those outwith well bounds;
    // finally trim to #fov. Deals with asymmetric FOV
    ArrayList<FOV> spiralFOVs = new ArrayList<FOV>();
    FOV fov = new FOV(wellString, pp_, 0);
    double[] centrexy = { fov.getX(), fov.getY() };
    //        double[] DXY = {sap_.getFLIMFOVSize()[0], sap_.getFLIMFOVSize()[1]};
    double[] DXY = { parent_.globalFOVset_.getWidth_(), parent_.globalFOVset_.getHeight_() };

    /*int[][] dir = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
    double[] dxy = new double[2];// w  w w. j a v a 2  s  .co  m
    int stepsInCurrentDir;*/

    spiralFOVs.add(fov);
    int fovind = 1;
    int dirind = 0;
    double nx = 1;
    double nxCount = 0;
    double ny = 1;
    double nyCount = 0;

    while (fovind < noFOV & dirind < 100) { // just in case we have a runaway case...
        //stepsInCurrentDir = (int) Math.ceil((double) (dirind) / 2);
        if (fovind % 2 == 0) {

            while (nyCount < abs(ny)) {
                centrexy[1] = centrexy[1] + (ny + nyCount) * DXY[1];
                nyCount++;

            }
            ny = -(abs(ny) + 1);
        } else {

            while (nxCount < abs(nx)) {
                centrexy[0] = centrexy[0] + (nx + nyCount) * DXY[0];
                nxCount++;

            }
            nx = -(abs(nx) + 1);
        }

        fovind++;
        fov = new FOV(centrexy[0], centrexy[1], 0, wellString, pp_);

        if (fov.isValid()) {
            spiralFOVs.add(fov);
        }

        System.out.println(fov.toString());
        dirind++;
        //    System.out.print("Dirind = " + dirind + "\n");
    }
    // trim, a bit hacky but works
    int currsize = spiralFOVs.size();
    for (int j = currsize - 1; j > noFOV - 1; j--) {
        spiralFOVs.remove(j);
    }
    return spiralFOVs;
}

From source file:de.fosd.jdime.strategy.CombinedStrategy.java

/**
 * TODO: high-level documentation/*from   w  ww. ja  v  a 2s  .  co  m*/
 * @param operation
 * @param context
 *
 * @throws IOException
 * @throws InterruptedException
 */
@Override
public final void merge(final MergeOperation<FileArtifact> operation, final MergeContext context)
        throws IOException, InterruptedException {
    assert (operation != null);
    assert (context != null);

    context.resetStreams();

    FileArtifact target = null;

    if (!context.isDiffOnly() && operation.getTarget() != null) {
        assert (operation.getTarget() instanceof FileArtifact);
        target = operation.getTarget();
        assert (!target.exists() || target.isEmpty()) : "Would be overwritten: " + target;
    }

    if (LOG.isInfoEnabled()) {
        MergeTriple<FileArtifact> triple = operation.getMergeTriple();
        assert (triple != null);
        assert (triple.isValid()) : "The merge triple is not valid!";
        LOG.info("Merging: " + triple.getLeft().getPath() + " " + triple.getBase().getPath() + " "
                + triple.getRight().getPath());
    }

    ArrayList<Long> runtimes = new ArrayList<>();
    MergeContext subContext = null;
    Stats substats = null;

    for (int i = 0; i < context.getBenchmarkRuns() + 1 && (i == 0 || context.isBenchmark()); i++) {
        long cmdStart = System.currentTimeMillis();
        subContext = (MergeContext) context.clone();
        subContext.setOutputFile(null);

        if (LOG.isInfoEnabled() && i == 0) {
            LOG.info("Trying linebased strategy.");
        }

        MergeStrategy<FileArtifact> s = new LinebasedStrategy();
        subContext.setMergeStrategy(s);
        subContext.setSaveStats(true);
        s.merge(operation, subContext);

        int conflicts = subContext.getStats().getConflicts();
        if (conflicts > 0) {
            // merge not successful. we need another strategy.
            if (LOG.isInfoEnabled() && i == 0) {
                String noun = conflicts > 1 ? "conflicts" : "conflict";
                LOG.info("Got " + conflicts + " " + noun + ". Need to use structured strategy.");
            }

            // clean target file
            if (LOG.isInfoEnabled()) {
                LOG.info("Deleting: " + target);
            }

            if (target != null) {
                boolean isLeaf = target.isLeaf();
                target.remove();
                target.createArtifact(isLeaf);
            }

            subContext = (MergeContext) context.clone();
            subContext.setOutputFile(null);

            s = new StructuredStrategy();
            subContext.setMergeStrategy(s);
            if (i == 0) {
                subContext.setSaveStats(true);
            } else {
                subContext.setSaveStats(false);
                subContext.setBenchmark(true);
                subContext.setBenchmarkRuns(0);
            }
            s.merge(operation, subContext);
        } else {
            if (LOG.isInfoEnabled() && i == 0) {
                LOG.info("Linebased strategy worked fine.");
            }
        }

        if (i == 0) {
            substats = subContext.getStats();
        }

        long runtime = System.currentTimeMillis() - cmdStart;
        runtimes.add(runtime);

        if (LOG.isInfoEnabled() && context.isBenchmark()) {
            if (i == 0) {
                LOG.info("Initial run: " + runtime + " ms");
            } else {
                LOG.info("Run " + i + " of " + context.getBenchmarkRuns() + ": " + runtime + " ms");
            }
        }
    }

    if (context.isBenchmark() && runtimes.size() > 1) {
        // remove first run as it took way longer due to all the counting
        runtimes.remove(0);
    }

    Long runtime = MergeContext.median(runtimes);
    LOG.debug("Combined merge time was " + runtime + " ms.");

    assert (subContext != null);

    if (subContext.hasOutput()) {
        context.append(subContext.getStdIn());
    }

    if (subContext.hasErrors()) {
        context.appendError(subContext.getStdErr());
    }

    // write output
    if (target != null) {
        assert (target.exists());
        target.write(context.getStdIn());
    }

    // add statistical data to context
    if (context.hasStats()) {
        assert (substats != null);

        Stats stats = context.getStats();
        substats.setRuntime(runtime);
        MergeTripleStats subscenariostats = substats.getScenariostats().remove(0);
        assert (substats.getScenariostats().isEmpty());

        if (subscenariostats.hasErrors()) {
            stats.addScenarioStats(subscenariostats);
        } else {
            MergeTripleStats scenariostats = new MergeTripleStats(subscenariostats.getTriple(),
                    subscenariostats.getConflicts(), subscenariostats.getConflictingLines(),
                    subscenariostats.getLines(), runtime, subscenariostats.getASTStats(),
                    subscenariostats.getLeftASTStats(), subscenariostats.getRightASTStats());
            stats.addScenarioStats(scenariostats);
        }

        context.addStats(substats);
    }
    System.gc();
}