Example usage for java.util TreeMap size

List of usage examples for java.util TreeMap size

Introduction

In this page you can find the example usage for java.util TreeMap size.

Prototype

int size

To view the source code for java.util TreeMap size.

Click Source Link

Document

The number of entries in the tree

Usage

From source file:com.sfs.whichdoctor.dao.RelationshipDAOImpl.java

/**
 * Generates a map of supervisors based on their hierarchy. This function
 * ensures all required supervisor positions are filled.
 *
 * @param supervisors as a collection of RelationshipBeans
 *
 * @return the tree map< integer, relationship bean>
 *//* w  w  w  .ja  v  a2s. c o  m*/
private TreeMap<Integer, RelationshipBean> buildFullSupervisorMap(
        final Collection<RelationshipBean> supervisors) {

    TreeMap<Integer, RelationshipBean> fullSupervisorMap = new TreeMap<Integer, RelationshipBean>();

    TreeMap<Integer, RelationshipBean> btSupervisorMap = new TreeMap<Integer, RelationshipBean>();

    if (supervisors != null) {
        String relationshipClass = "";
        for (RelationshipBean relationship : supervisors) {
            if (StringUtils.startsWithIgnoreCase(relationship.getRelationshipClass(), "Basic")) {
                // Only one relationship per basic training hierarchy-level is allowed
                if (dataLogger.isDebugEnabled()) {
                    dataLogger.debug("Relationship: " + relationship.getRelationshipType());
                    dataLogger.debug("Hierarchy: " + relationship.getHierarchy());
                }
                relationshipClass = relationship.getRelationshipClass();
                btSupervisorMap.put(relationship.getHierarchy(), relationship);
            }
        }

        // If a basic training supervisor exists build a full map
        if (btSupervisorMap.size() > 0) {
            dataLogger.debug("At least one basic training supervisor exists");
            dataLogger.debug("Relationship class: " + relationshipClass);
            fullSupervisorMap = buildInheritedMap(relationshipClass, btSupervisorMap);
        }

        for (RelationshipBean relationship : supervisors) {
            if (!StringUtils.startsWithIgnoreCase(relationship.getRelationshipClass(), "Basic")) {
                String heirarchy = relationship.getHierarchy() + "00" + relationship.getReferenceGUID();
                int index = Integer.parseInt(heirarchy);
                fullSupervisorMap.put(index, relationship);
            }
        }
    }

    dataLogger.debug("Supervisor map size: " + fullSupervisorMap.size());

    return fullSupervisorMap;
}

From source file:org.wso2.carbon.governance.registry.extensions.executors.ServiceVersionExecutor.java

private String reformatPath(String path, String currentExpression, String targetExpression,
        String newResourceVersion) throws RegistryException {
    TreeMap<Integer, String> indexMap = new TreeMap<Integer, String>();

    String returnPath = targetExpression;
    String prefix;/*from   w  w w .j  a v  a 2 s. c  o  m*/

    if (currentExpression.equals(targetExpression)) {
        return path;
    }
    indexMap.put(currentExpression.indexOf(RESOURCE_NAME), RESOURCE_NAME);
    indexMap.put(currentExpression.indexOf(RESOURCE_PATH), RESOURCE_PATH);
    indexMap.put(currentExpression.indexOf(RESOURCE_VERSION), RESOURCE_VERSION);

    String tempExpression = currentExpression;

    while (indexMap.lastKey() < tempExpression.lastIndexOf(RegistryConstants.PATH_SEPARATOR)) {
        tempExpression = tempExpression.substring(0,
                tempExpression.lastIndexOf(RegistryConstants.PATH_SEPARATOR));
        path = path.substring(0, path.lastIndexOf(RegistryConstants.PATH_SEPARATOR));
    }

    prefix = currentExpression.substring(0, currentExpression.indexOf(indexMap.get(indexMap.higherKey(-1))));

    if (!path.startsWith(prefix)) {
        return path;
    }
    path = path.replace(prefix, "");

    while (true) {
        if (indexMap.firstKey() < 0) {
            indexMap.pollFirstEntry();
        } else {
            break;
        }
    }

    while (true) {
        if (indexMap.size() == 0) {
            break;
        }
        Map.Entry lastEntry = indexMap.pollLastEntry();
        if (lastEntry.getValue().equals(RESOURCE_PATH)) {
            String pathValue = path;

            for (int i = 0; i < indexMap.size(); i++) {
                //                    pathValue = formatPath(pathValue.substring(path.indexOf(RegistryConstants.PATH_SEPARATOR)));
                pathValue = formatPath(
                        pathValue.substring(pathValue.indexOf(RegistryConstants.PATH_SEPARATOR)));
            }

            if (!pathValue.equals("")) {
                returnPath = returnPath.replace(RESOURCE_PATH, formatPath(pathValue));
                path = path.replace(pathValue, "");
            } else {
                returnPath = returnPath.replace("/" + lastEntry.getValue(), "");
            }

            continue;
        }
        if (lastEntry.getValue().equals(RESOURCE_VERSION)) {
            returnPath = returnPath.replace(RESOURCE_VERSION, newResourceVersion);
            if (path.contains("/")) {
                path = path.substring(0, path.lastIndexOf(RegistryConstants.PATH_SEPARATOR));
            } else {
                path = "";
            }
            continue;
        }

        String tempPath;
        if (path.contains("/")) {
            tempPath = path.substring(path.lastIndexOf(RegistryConstants.PATH_SEPARATOR) + 1);
        } else {
            tempPath = path;
        }
        if (!tempPath.equals("")) {
            returnPath = returnPath.replace((String) lastEntry.getValue(), formatPath(tempPath));
            if (path.contains("/")) {
                path = path.substring(0, path.lastIndexOf(RegistryConstants.PATH_SEPARATOR));
            } else {
                path = "";
            }
        } else {
            returnPath = returnPath.replace("/" + lastEntry.getValue(), "");
            if (path.contains("/")) {
                path = path.substring(0, path.lastIndexOf(RegistryConstants.PATH_SEPARATOR));
            }
        }

    }

    //        Adding the version validation here.
    if (!newResourceVersion.matches("^\\d+[.]\\d+[.]\\d+(-[a-zA-Z0-9]+)?$")) {
        String message = "Invalid version found for " + RegistryUtils.getResourceName(path);
        log.error(message);
        throw new RegistryException(message);
    }
    if (returnPath.contains(RESOURCE_VERSION)) {
        return returnPath.replace(RESOURCE_VERSION, newResourceVersion);
    }
    return returnPath;
}

From source file:com.sfs.whichdoctor.dao.VoteDAOImpl.java

/**
 * Loads an array of groups based on the submitted voteNumber and year.
 *
 * @param voteNumber the vote number/* w ww.j  a va 2s .c o  m*/
 * @param year the year
 *
 * @return the collection< group bean>
 *
 * @throws WhichDoctorDaoException the which doctor dao exception
 */
@SuppressWarnings("unchecked")
public final Collection<GroupBean> findElections(final int voteNumber, final int year)
        throws WhichDoctorDaoException {

    if (year == 0) {
        throw new WhichDoctorDaoException("Sorry a valid year is required");
    }

    Collection<GroupBean> elections = new ArrayList<GroupBean>();

    dataLogger.info("Loading elections for: " + voteNumber + "/" + year);

    /* Identify the referenceGUID from the vote number and year */
    int referenceGUID = PersonBean.getVoterGUID(voteNumber, year);

    TreeMap<Integer, Integer> electionList = new TreeMap<Integer, Integer>();

    try {
        Collection<Integer> guids = this.getJdbcTemplateReader().query(
                this.getSQL().getValue("vote/findPossibleElections"), new Object[] { year, referenceGUID },
                new RowMapper() {
                    public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException {
                        return rs.getInt("GUID");
                    }
                });

        for (Integer guid : guids) {
            electionList.put(guid, guid);
        }
    } catch (IncorrectResultSizeDataAccessException ie) {
        dataLogger.debug("No results found for this search: " + ie.getMessage());
    }

    try {
        Collection<Integer> guids = this.getJdbcTemplateReader().query(
                this.getSQL().getValue("vote/findVotedElections"), new Object[] { year, referenceGUID },
                new RowMapper() {
                    public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException {
                        return rs.getInt("GUID");
                    }
                });

        for (Integer guid : guids) {
            if (electionList.containsKey(guid)) {
                // This election has been voted for already, remove it from the list
                electionList.remove(guid);
            }
        }
    } catch (IncorrectResultSizeDataAccessException ie) {
        dataLogger.debug("No results found for this search: " + ie.getMessage());
    }

    if (electionList.size() > 0) {
        // An unvoted election exists in the map, perform a group search to load it
        Collection<Object> guidCollection = new ArrayList<Object>();
        for (Integer groupGUID : electionList.keySet()) {
            guidCollection.add(groupGUID);
        }
        try {
            SearchBean search = this.searchDAO.initiate("group", null);
            search.setLimit(0);
            search.setOrderColumn("groups.Weighting");
            search.setOrderColumn2("groups.Name");
            search.setSearchArray(guidCollection, "Unvoted list of elections");

            BuilderBean loadDetails = new BuilderBean();
            loadDetails.setParameter("CANDIDATES", true);

            SearchResultsBean results = this.searchDAO.search(search, loadDetails);

            if (results != null) {
                // Add each group to the election array
                for (Object result : results.getSearchResults()) {
                    GroupBean election = (GroupBean) result;
                    elections.add(election);
                }
            }
        } catch (Exception e) {
            dataLogger.error("Error performing election search: " + e.getMessage());
            throw new WhichDoctorDaoException("Error performing election search: " + e.getMessage());
        }
    }
    return elections;
}

From source file:com.ichi2.anki.DeckPicker.java

public void confirmDeckDeletion(long did) {
    Resources res = getResources();
    if (!colIsOpen()) {
        return;//www. jav  a  2s.  c  om
    }
    if (did == 1) {
        showSimpleSnackbar(R.string.delete_deck_default_deck, true);
        dismissAllDialogFragments();
        return;
    }
    // Get the number of cards contained in this deck and its subdecks
    TreeMap<String, Long> children = getCol().getDecks().children(did);
    long[] dids = new long[children.size() + 1];
    dids[0] = did;
    int i = 1;
    for (Long l : children.values()) {
        dids[i++] = l;
    }
    String ids = Utils.ids2str(dids);
    int cnt = getCol().getDb()
            .queryScalar("select count() from cards where did in " + ids + " or odid in " + ids);
    // Delete empty decks without warning
    if (cnt == 0) {
        deleteDeck(did);
        dismissAllDialogFragments();
        return;
    }
    // Otherwise we show a warning and require confirmation
    String msg;
    String deckName = "\'" + getCol().getDecks().name(did) + "\'";
    boolean isDyn = getCol().getDecks().isDyn(did);
    if (isDyn) {
        msg = String.format(res.getString(R.string.delete_cram_deck_message), deckName);
    } else {
        msg = res.getQuantityString(R.plurals.delete_deck_message, cnt, deckName, cnt);
    }
    showDialogFragment(DeckPickerConfirmDeleteDeckDialog.newInstance(msg));
}

From source file:com.sfs.whichdoctor.webservice.RotationXmlOutputImpl.java

/**
 * Builds a list of rotations in the second-gen XML format.
 *
 * @param rotations the rotation array/*from  w w w  .  ja  v a  2s  .  c o m*/
 * @param personIdentifier the person identifier
 * @param division the division
 * @param currentRotations the current rotations
 *
 * @return the rotations in XML format
 */
public final String getSecondGenRotations(final List<RotationBean> rotations, final int personIdentifier,
        final String division, final Collection<RotationBean> currentRotations) {

    Element xml = new Element("trainee");
    xml.setAttribute("MIN", String.valueOf(personIdentifier));

    // Process the current organisations
    TreeMap<String, Element> siteMap = new TreeMap<String, Element>();

    for (RotationBean rtn : currentRotations) {
        if (StringUtils.isNotBlank(rtn.getOrganisation1Name())) {
            Element site = new Element("site");
            String type = "primary";
            if (!StringUtils.equalsIgnoreCase(type, rtn.getOrganisation1TypeMapping())) {
                // If not primary set the type to training
                type = "training";
            }
            site.setAttribute("type", "current_" + type);
            site.setAttribute("state", loadOrgCity(rtn.getOrganisation1Id()));
            site.setAttribute("name", rtn.getOrganisation1Name());

            siteMap.put(type, site);
        }
        if (StringUtils.isNotBlank(rtn.getOrganisation2Name())) {
            Element site = new Element("site");
            String type = "training";
            if (siteMap.containsKey(type)) {
                // Set to primary if the training key exists
                type = "primary";
            }
            site.setAttribute("type", "current_" + type);
            site.setAttribute("state", loadOrgCity(rtn.getOrganisation2Id()));
            site.setAttribute("name", rtn.getOrganisation2Name());

            siteMap.put(type, site);
        }
    }

    if (siteMap.size() == 1) {
        for (String type : siteMap.keySet()) {
            Element site = siteMap.get(type);
            Element site2 = (Element) site.clone();

            String secondType = "training";
            if (StringUtils.equalsIgnoreCase(type, "training")) {
                secondType = "primary";
            }
            site2.setAttribute("type", "current_" + secondType);

            siteMap.put(secondType, site2);
        }
    }

    Element sitesElement = new Element("sites");

    for (String type : siteMap.keySet()) {
        Element site = siteMap.get(type);
        sitesElement.addContent(site);
    }
    xml.addContent(sitesElement);

    Element rtnsXml = new Element("rotations");
    rtnsXml.setAttribute("min", String.valueOf(personIdentifier));

    for (RotationBean rtn : rotations) {

        rtnsXml.addContent(RotationXmlHelper.getSecondGenRotationInfo(rtn, division,
                loadOrgCity(rtn.getOrganisation1Id()), loadOrgCity(rtn.getOrganisation2Id())));
    }
    xml.addContent(rtnsXml);

    XMLOutputter outputter = new XMLOutputter();
    Format format = Format.getCompactFormat();
    format.setOmitDeclaration(true);

    outputter.setFormat(format);

    return outputter.outputString(new Document(xml));
}

From source file:IndexService.Indexer.java

private List<IRecord> getRange1(String indexdir, String partname, List<IRecord.IFValue> startvalue,
        List<IRecord.IFValue> endvalue, String indexids, int limit, int fieldnum) throws IOException {
    String dir = indexdir.endsWith("/") ? indexdir : (indexdir + "/");
    Path partfile = new Path(dir + partname);

    TreeMap<String, TreeSet<Integer>> indexresult = new TreeMap<String, TreeSet<Integer>>();
    HashMap<String, Boolean> iscolumn = new HashMap<String, Boolean>();
    FileStatus[] fss = fs.listStatus(partfile);
    long time = System.currentTimeMillis();
    for (FileStatus status : fss) {
        IFormatDataFile ifdf = new IFormatDataFile(conf);
        ifdf.open(status.getPath().toString());

        if (ifdf.fileInfo().head().fieldMap().fieldtypes().size() < startvalue.size() + 2) {
            throw new IOException("input value field size is more than index can support");
        }//from   w  ww  .ja  va  2 s  .co  m
        for (int i = 0; i < startvalue.size(); i++) {
            if (ifdf.fileInfo().head().fieldMap().fieldtypes().get(i).type() != startvalue.get(i).type()
                    .type()) {
                throw new IOException("input value field type is not fit the index field type");
            }
        }

        HashMap<Integer, String> infos = ifdf.fileInfo().head().getUdi().infos();
        List<IndexValue> res = getIndexResRange(ifdf, startvalue, endvalue, limit);
        for (IndexValue iv : res) {
            int fileid = iv.getFileindex();
            String filename = infos.get(fileid);
            if (!indexresult.containsKey(filename)) {
                indexresult.put(filename, new TreeSet<Integer>());
                iscolumn.put(filename, ifdf.fileInfo().head().getUdi().infos().get(123456).equals("column"));

            }
            indexresult.get(filename).add(iv.getRowid());
        }
        ifdf.close();
    }
    System.out.println("getIndexResRange time:\t" + (System.currentTimeMillis() - time) / 1000 + "s");
    System.out.println("related file num:\t" + indexresult.size());
    return getRecord(indexresult, iscolumn, indexids, limit, fieldnum);
}

From source file:com.sec.ose.osi.thread.ui_related.UserCommandExecutionThread.java

@Override
public void run() {

    long startTime = System.currentTimeMillis();
    log.info(UserRequestHandler.getCommandName(mRequestCode) + " - start");

    isDone = false;//from  www.  j  a  va2 s.co  m

    this.mObserver.pushMessage("Preparing to request to server");
    Property prop = Property.getInstance();
    switch (mRequestCode) {

    case UserRequestHandler.DELETE_IDENTIFICATION_TABLE:
        if (IdentifyQueue.getInstance().size() > 0) {
            return;
        }

        Collection<OSIProjectInfo> infoList = OSIProjectInfoMgr.getInstance().getAllProjects();
        for (OSIProjectInfo info : infoList) {

            if (info.getProjectName().equals(IdentifyMediator.getInstance().getSelectedProjectName())) {
                continue;
            }

            if (info.isManaged() == true) {
                continue;
            }

            mObserver.setMessageHeader("Deleting identification table...\n");
            mObserver.pushMessageWithHeader(" > target project : " + info.getProjectName() + "\n");

            // Drop identification tables
            IdentificationDBManager.dropTable(info.getProjectName());

            // Remove memory
            ProjectDiscoveryControllerMap.removeProjectDiscoveryController(info.getProjectName());
        }
        break;

    case UserRequestHandler.GET_PROTEX_PROJECT_INFO:
        UEProtexProjectInfo uap = (UEProtexProjectInfo) mEntity;
        OSIProjectInfo protexProjectInfo = UISDKInterfaceManager.getSDKInterface()
                .getProjectInfoByName(uap.getProjectName());
        this.mObserver.setReturnValue(protexProjectInfo);
        this.mObserver.setResult(UIResponseObserver.RESULT_SUCCESS);

        break;

    case UserRequestHandler.LOAD_IDENTIFICATION_DATA: {
        UEComboProjectName uei = (UEComboProjectName) mEntity;

        String projectName = uei.getProjectName();
        log.info("loading project [" + projectName + "]");

        mObserver.setMessageHeader("Loading Identification Data ...\n");

        // Local Component Loading
        mObserver.pushMessageWithHeader(" > Loading local component info ...\n");
        ComponentAPIWrapper.loadLocalComponent(ProjectAPIWrapper.getProjectID(projectName), false);

        ProjectDiscoveryControllerMap.loadProjectDiscoveryController(projectName, this.mObserver);
        CodeTreeAPIWrapper.setCodeTree(projectName, this.mObserver);

        log.debug("Selected Project : " + projectName);

        mObserver.pushMessageWithHeader(" > Loading sql dat to memory ...\n");
        AbstractDiscoveryController stringMatchDiscovery = ProjectDiscoveryControllerMap
                .getDiscoveryController(projectName, IdentificationConstantValue.STRING_MATCH_TYPE);
        AbstractDiscoveryController codeMatchDiscovery = ProjectDiscoveryControllerMap
                .getDiscoveryController(projectName, IdentificationConstantValue.CODE_MATCH_TYPE);
        AbstractDiscoveryController patternMatchDiscovery = ProjectDiscoveryControllerMap
                .getDiscoveryController(projectName, IdentificationConstantValue.PATTERN_MATCH_TYPE);

        int displayedMatchedType = IdentificationConstantValue.STRING_MATCH_TYPE;

        if (stringMatchDiscovery.getNumOfPendingFiles() > 0) {
            displayedMatchedType = IdentificationConstantValue.STRING_MATCH_TYPE;
        } else if (codeMatchDiscovery.getNumOfPendingFiles() > 0) {
            displayedMatchedType = IdentificationConstantValue.CODE_MATCH_TYPE;
        } else if (patternMatchDiscovery.getNumOfPendingFiles() > 0) {
            displayedMatchedType = IdentificationConstantValue.PATTERN_MATCH_TYPE;
        } else if (stringMatchDiscovery.getNumOfDiscoveryFiles() > 0) {
            displayedMatchedType = IdentificationConstantValue.STRING_MATCH_TYPE;
        } else if (codeMatchDiscovery.getNumOfDiscoveryFiles() > 0) {
            displayedMatchedType = IdentificationConstantValue.CODE_MATCH_TYPE;
        } else if (patternMatchDiscovery.getNumOfDiscoveryFiles() > 0) {
            displayedMatchedType = IdentificationConstantValue.PATTERN_MATCH_TYPE;
        }

        mObserver.pushMessageWithHeader(" > Updating Panel ...\n");
        IdentifyMediator.getInstance().changeSelectedIdentificationPanel(displayedMatchedType);

        // Tree & List Identification
        mObserver.pushMessageWithHeader(" > Updating Tree and List ...\n");
        IdentifyMediator.getInstance().refreshIdentificationInfoForTreeListChildFrames(projectName, null,
                displayedMatchedType);

        this.mObserver.setResult(UIResponseObserver.RESULT_SUCCESS);
    }
        break;

    case UserRequestHandler.SYNC_TO_SERVER: {
        syncToServer();
    }
        break;

    case UserRequestHandler.SYNC_FROM_SERVER: {
        syncFromServer();
    }
        break;

    case UserRequestHandler.GET_ALL_PROJECT_NAMES: {
        ArrayList<String> projectNames = UISDKInterfaceManager.getSDKInterface()
                .getProjectNames(this.mObserver);
        this.mObserver.setReturnValue(projectNames);
    }
        break;

    case UserRequestHandler.LOGIN:
        UELogin ueLogin = (UELogin) mEntity;
        this.mObserver.pushMessage("Sending login request to server");

        mSDKInterface.userLogin(ueLogin.getUserID(), ueLogin.getPassword(), ueLogin.getProtexServerIP(),
                this.mObserver);

        if (this.mObserver.getResult() == UIResponseObserver.RESULT_SUCCESS) {
            IdentifyQueue.getInstance().makeBackup();
            loadMainFrame(ueLogin, this.mObserver);
        }
        break;

    case UserRequestHandler.GENERATE_BOTH_REPORT:
        generateBothReport();
        break;

    case UserRequestHandler.GENERATE_IDENTIFY_REPORT:
        generateIdentifyReport();
        break;

    case UserRequestHandler.GENERATE_SPDX_REPORT:
        generateSPDXReport();
        break;

    case UserRequestHandler.GET_BOM_LIST_FROM_SERVER: {
        UEProjectName ueProjetName = (UEProjectName) mEntity;
        String projectName = ueProjetName.getProjectName();
        UISDKInterfaceManager.getSDKInterface().getBOMListFromProjectName(projectName, this.mObserver);
    }
        break;

    case UserRequestHandler.GET_BOM_LIST_MAP_FROM_SERVER: {
        UEProjectName ueProjetName = (UEProjectName) mEntity;
        ArrayList<String> projectNames = ueProjetName.getProjectNames();
        UISDKInterfaceManager.getSDKInterface().getBOMListMapFromProjectNames(projectNames, this.mObserver);
    }
        break;

    case UserRequestHandler.PROJECT_CLONE: {
        UEProjectClone ueProjectClone = (UEProjectClone) mEntity;
        if (ueProjectClone.getOriginalProjectName() == null) {
            this.mObserver.setResult(UIResponseObserver.RESULT_FAIL);
            return;
        }
        String projectID = null;
        String newProjectName = ueProjectClone.getNewProjectName();
        String originalProjectName = ueProjectClone.getOriginalProjectName();
        projectID = SDKInterfaceImpl.getInstance().cloneProject(newProjectName, originalProjectName, mObserver);
        ArrayList<OSIProjectInfo> osiProjectInfoList = new ArrayList<OSIProjectInfo>();

        if (projectID != null) {
            String sourceLocation = ueProjectClone.getSourceLocation();
            boolean isAnalyzed = false;
            if (OSIProjectInfoMgr.getInstance().getProjectInfo(originalProjectName) != null) {
                isAnalyzed = OSIProjectInfoMgr.getInstance().getProjectInfo(originalProjectName).isAnalyzed();
            }
            OSIProjectInfo curCreateProjectInfo = createOSIProjectInfo(projectID, newProjectName,
                    sourceLocation, isAnalyzed);
            osiProjectInfoList.add(curCreateProjectInfo);
            this.mObserver.setReturnValue(osiProjectInfoList);
            this.mObserver.setResult(UIResponseObserver.RESULT_SUCCESS);
        } else {
            this.mObserver.setResult(UIResponseObserver.RESULT_FAIL);
        }
    }
        break;

    case UserRequestHandler.PROJECT_CREATE: {
        UEProjectCreate ueProjectCreate = (UEProjectCreate) mEntity;
        String projectID = null;
        TreeMap<String, ProjectSplitInfo> mapOfAnalyzeTarget = ueProjectCreate.getMapOfAnalyzeTarget();
        String newProjectName = ueProjectCreate.getProjectName();
        ArrayList<OSIProjectInfo> osiProjectInfoList = new ArrayList<OSIProjectInfo>();

        if (mapOfAnalyzeTarget == null) { // one project, no source path
            this.mObserver.pushMessage("Creating project [  " + newProjectName + "  ] ...");
            projectID = SDKInterfaceImpl.getInstance().createProject(newProjectName, null, mObserver);
            if (projectID != null) {
                String sourceLocation = "";
                boolean isAnalyzed = false;
                OSIProjectInfo curCreateProjectInfo = createOSIProjectInfo(projectID, newProjectName,
                        sourceLocation, isAnalyzed);
                osiProjectInfoList.add(curCreateProjectInfo);
                this.mObserver.setReturnValue(osiProjectInfoList);
                this.mObserver.setResult(UIResponseObserver.RESULT_SUCCESS);
            } else {
                this.mObserver.setResult(UIResponseObserver.RESULT_FAIL);
            }

        } else { // split or no split

            int curProjectNum = 0;
            int totalProjectNum = mapOfAnalyzeTarget.size();

            Iterator<Map.Entry<String, ProjectSplitInfo>> iter = mapOfAnalyzeTarget.entrySet().iterator();
            if (iter == null) {
                return;
            }

            while (iter.hasNext()) {
                String strProjectName = iter.next().getKey();
                ++curProjectNum;
                if (mapOfAnalyzeTarget.size() <= 1) {
                    this.mObserver.pushMessage("Creating project [  " + newProjectName + "  ] ...");
                } else {
                    this.mObserver.pushMessage("Creating project [  (" + curProjectNum + "/" + totalProjectNum
                            + ") " + newProjectName + "  ] ...");
                }

                String sourceLocation = mapOfAnalyzeTarget.get(strProjectName).getAnalyzeTargetPath();
                projectID = SDKInterfaceImpl.getInstance().createProject(strProjectName, sourceLocation,
                        mObserver);
                if (projectID != null) {
                    boolean isAnalyzed = false;
                    OSIProjectInfo curCreateProjectInfo = createOSIProjectInfo(projectID, strProjectName,
                            sourceLocation, isAnalyzed);
                    osiProjectInfoList.add(curCreateProjectInfo);
                    this.mObserver.setResult(UIResponseObserver.RESULT_SUCCESS);
                } else {
                    this.mObserver.setResult(UIResponseObserver.RESULT_FAIL);
                }
            }
            this.mObserver.setReturnValue(osiProjectInfoList);
        }
    }
        break;

    case UserRequestHandler.PROCESS_IDENTIFY: {
        IdentifyThread thread = BackgroundJobManager.getInstance().getIdentifyThread();
        if (thread != null)
            thread.setIsStopByUser(true);

        mObserver.setMessageHeader("Identify processing... \n");
        mObserver.pushMessageWithHeader(" > Update local database.\n");

        boolean result = ActionIdentifyOrReset.requestIdentify(mObserver, (UEIdentifyResetComment) mEntity);
        if (result) {
            mObserver.setResult(UIResponseObserver.RESULT_SUCCESS);
        } else {
            mObserver.setResult(UIResponseObserver.RESULT_FAIL);
        }

        thread.setIsStopByUser(false);
    }
        break;

    case UserRequestHandler.PROCESS_RESET: {
        IdentifyThread thread = BackgroundJobManager.getInstance().getIdentifyThread();
        if (thread != null)
            thread.setIsStopByUser(true);

        mObserver.setMessageHeader("Reset processing... \n");
        mObserver.pushMessageWithHeader(" > Update local database.\n");
        boolean result = ActionIdentifyOrReset.requestReset(mObserver, (UEIdentifyResetComment) mEntity);
        if (result) {
            mObserver.setResult(UIResponseObserver.RESULT_SUCCESS);
        } else {
            mObserver.setResult(UIResponseObserver.RESULT_FAIL);
        }

        thread.setIsStopByUser(false);
    }
        break;
    case UserRequestHandler.PROJECT_SPLIT: {
        mObserver.setMessageHeader("Assessing Project Size... \n");
        boolean result = splitProject(mObserver);
        if (result) {
            mObserver.setResult(UIResponseObserver.RESULT_SUCCESS);
            mObserver.setSuccessMessage("Complete splitting!!");
        } else {
            mObserver.setResult(UIResponseObserver.RESULT_FAIL);
            mObserver.setFailMessage("Fail splitting!!");
        }
    }
        break;

    case UserRequestHandler.PROJECT_INFO: {
        UEProjectInfo ue = (UEProjectInfo) mEntity;
        String projectName = ue.getProjectName();

        mObserver.setMessageHeader("Getting Project information... \n");
        boolean result = getProjectAnalysisInfo(projectName, mObserver);
        if (result) {
            mObserver.setResult(UIResponseObserver.RESULT_SUCCESS);
            mObserver.setSuccessMessage("Complete!!");
        } else {
            mObserver.setResult(UIResponseObserver.RESULT_FAIL);
            mObserver.setFailMessage("Fail!!");
        }
    }
        break;

    case UserRequestHandler.SPDX_AUTO_IDENTIFY: {
        mObserver.setMessageHeader("Ready to start SPDX Auto Identify ... \n");

        UESPDXAutoIdentify ue = (UESPDXAutoIdentify) mEntity;
        SPDXAutoIdentifyController controller = new SPDXAutoIdentifyController();
        AutoIdentifyResult autoIdentifyResultReport = controller.startAutoIdentifyFromSPDX(ue, mObserver);

        if (mObserver.getResult() != UIResponseObserver.RESULT_FAIL) {
            mObserver.setSuccessMessage(autoIdentifyResultReport.toString());
            mObserver.setResult(UIResponseObserver.RESULT_SUCCESS);
        } else {
            mObserver.setFailMessage(autoIdentifyResultReport.toString());
        }
        mObserver.setReturnValue(autoIdentifyResultReport);
    }
        break;

    }

    mObserver.pushMessage("Execution Thread - execution is completed");
    isDone = true;

    long finishTime = System.currentTimeMillis();
    log.info(UserRequestHandler.getCommandName(mRequestCode) + " - finish: (" + (finishTime - startTime)
            + " ms.)");

    closeAction();

}

From source file:dev.memento.MainActivity.java

@Override
protected Dialog onCreateDialog(int id) {

    Dialog dialog = null;/*from  ww w .ja  va2  s  .c o m*/
    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    switch (id) {

    case DIALOG_ERROR:
        builder.setMessage("error message").setCancelable(false).setPositiveButton("OK", null);
        dialog = builder.create();
        break;

    case DIALOG_MEMENTO_YEARS:
        builder.setTitle(R.string.select_year);
        final TreeMap<Integer, Integer> yearCount = mMementos.getAllYears();
        if (Log.LOG)
            Log.d(LOG_TAG, "Dialog: num of years = " + yearCount.size());

        // This shouldn't happen, but just in case
        if (yearCount.size() == 0) {
            showToast("There are no years to choose from... something is wrong.");
            if (Log.LOG)
                Log.d(LOG_TAG, "Num of mementos: " + mMementos.size());
            return null;
        }

        // Build a list that shows how many dates are available for each year
        final CharSequence[] yearText = new CharSequence[yearCount.size()];

        // Parallel arrays used to determine which entry was selected.
        // Could also have used a regular expression.
        final int years[] = new int[yearCount.size()];
        final int count[] = new int[yearCount.size()];

        int selectedYear = -1;
        int displayYear = mDateDisplayed.getYear();
        int i = 0;
        for (Map.Entry<Integer, Integer> entry : yearCount.entrySet()) {
            Integer year = entry.getKey();

            // Select the year of the Memento currently displayed
            if (displayYear == year)
                selectedYear = i;

            years[i] = year;
            count[i] = entry.getValue();
            yearText[i] = Integer.toString(year) + " (" + entry.getValue() + ")";
            i++;
        }

        builder.setSingleChoiceItems(yearText, selectedYear, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                dialog.dismiss();

                mSelectedYear = years[item];
                int numItems = count[item];

                if (numItems > MAX_NUM_MEMENTOS_PER_MONTH)
                    showDialog(DIALOG_MEMENTO_MONTHS);
                else
                    showDialog(DIALOG_MEMENTO_DATES);
            }
        });

        dialog = builder.create();

        // Cause the dialog to be freed whenever it is dismissed.
        // This is necessary because the items are dynamic.  
        dialog.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface arg0) {
                removeDialog(DIALOG_MEMENTO_YEARS);
            }
        });

        break;

    case DIALOG_MEMENTO_MONTHS:
        builder.setTitle(R.string.select_month);
        final LinkedHashMap<CharSequence, Integer> monthCount = mMementos.getMonthsForYear(mSelectedYear);

        // This shouldn't happen, but just in case
        if (monthCount.size() == 0) {
            showToast("There are no months to choose from... something is wrong.");
            if (Log.LOG)
                Log.d(LOG_TAG, "Num of mementos: " + mMementos.size());
            return null;
        }

        // Build a list that shows how many dates are available for each month
        final CharSequence[] monthText = new CharSequence[monthCount.size()];

        int selectedMonth = mDateDisplayed.getMonth() - 1;
        i = 0;
        for (Map.Entry<CharSequence, Integer> entry : monthCount.entrySet()) {
            CharSequence month = entry.getKey();

            monthText[i] = month + " (" + entry.getValue() + ")";
            i++;
        }

        builder.setSingleChoiceItems(monthText, selectedMonth, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                dialog.dismiss();

                // Pull out month name so we can map it back to a number.
                // This is ugly, but it's necessary because the LinkedHashMap doesn't
                // give back the order of its keys.

                Pattern r = Pattern.compile("^(.+) ");
                Matcher m = r.matcher(monthText[item]);
                if (m.find()) {
                    String month = m.group(1);

                    mSelectedMonth = Utilities.monthStringToInt(month);
                    showDialog(DIALOG_MEMENTO_DATES);
                } else {
                    if (Log.LOG)
                        Log.e(LOG_TAG, "Could not find month in [" + monthText[item] + "]");
                }
            }
        });

        dialog = builder.create();

        // Cause the dialog to be freed whenever it is dismissed.
        // This is necessary because the items are dynamic.  
        dialog.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface arg0) {
                removeDialog(DIALOG_MEMENTO_MONTHS);
            }
        });

        break;

    case DIALOG_MEMENTO_DATES:

        builder.setTitle(R.string.select_day);

        // Which radio button is selected?
        int selected = -1;

        final CharSequence[] dates;

        if (Log.LOG)
            Log.d(LOG_TAG, "mSelectedMonth = " + mSelectedMonth);
        if (Log.LOG)
            Log.d(LOG_TAG, "mSelectedYear = " + mSelectedYear);

        final Memento[] mementoList;

        // See if there is a month/year filter 
        if (mSelectedMonth != -1 || mSelectedYear != -1) {

            if (mSelectedMonth != -1)
                mementoList = mMementos.getByMonthAndYear(mSelectedMonth, mSelectedYear);
            else
                mementoList = mMementos.getByYear(mSelectedYear);

            if (Log.LOG)
                Log.d(LOG_TAG, "Number of dates = " + mementoList.length);

            // Get dates for selected mementos
            dates = new CharSequence[mementoList.length];
            i = 0;
            for (Memento m : mementoList) {
                dates[i] = m.getDateAndTimeFormatted();
                i++;
            }

            // See if any of these items match.  This could take a little while if
            // there are a large number of items unfortunately.
            Memento m = mMementos.getCurrent();
            if (m != null) {
                CharSequence searchDate = m.getDateAndTimeFormatted();
                for (i = 0; i < dates.length; i++) {
                    if (searchDate.equals(dates[i])) {
                        selected = i;
                        break;
                    }
                }
            }
        } else {
            // No filter, so get all available mementos
            dates = mMementos.getAllDates();
            if (Log.LOG)
                Log.d(LOG_TAG, "Number of dates = " + dates.length);
            selected = mMementos.getCurrentIndex();
            mementoList = mMementos.toArray(new Memento[0]);
        }

        if (Log.LOG)
            Log.d(LOG_TAG, "Selected index = " + selected);

        // Reset for future selections
        mSelectedYear = -1;
        mSelectedMonth = -1;

        builder.setSingleChoiceItems(dates, selected, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                dialog.dismiss();

                // Display this Memento
                Memento m = mementoList[item];
                mCurrentMemento = m;
                final SimpleDateTime dateSelected = m.getDateTime();
                mDateDisplayed = dateSelected;
                setChosenDate(mDateDisplayed);
                if (Log.LOG)
                    Log.d(LOG_TAG, "User selected Memento with date " + dateSelected.dateFormatted());
                showToast("Time traveling to " + mDateDisplayed.dateFormatted());
                refreshDisplayedDate();

                // Load memento into the browser                 
                String redirectUrl = m.getUrl();
                surfToUrl(redirectUrl);

                setEnableForNextPrevButtons();
                mNowButton.setEnabled(true);

                // Potentially lengthly operation

                new Thread() {
                    public void run() {
                        int index = mMementos.getIndex(dateSelected);
                        if (index == -1) {
                            // This should never happen
                            if (Log.LOG)
                                Log.e(LOG_TAG, "!! Couldn't find " + dateSelected + " in the memento list!");
                        } else
                            mMementos.setCurrentIndex(index);
                    }
                }.start();
            }

        });

        dialog = builder.create();

        // Cause the dialog to be freed whenever it is dismissed.
        // This is necessary because the items are dynamic.  I couldn't find
        // a better way to solve this problem.
        dialog.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface arg0) {
                removeDialog(DIALOG_MEMENTO_DATES);
            }
        });

        break;
    }

    return dialog;
}

From source file:statistic.ca.gui.JCAStatisticPanel.java

private void showDiagramm(String diagrammName) {
    if (diagrammName.equals("Grundinformationen")) {
        String[] columnNames = { "Bezeichnung", "Wert" };
        EvacuationCellularAutomaton tmpCA;
        int nrOfInd = 0;
        double evacSec = 0.0;
        double evacCAStep = 0;
        double notEvac = 0;
        double evac = 0;
        double notEvacNoExit = 0;
        double notEvacNoTime = 0;
        int bestEvacIndex = 0;
        int aveEvacIndex = 0;
        int worseEvacIndex = 0;
        TreeMap<Double, Integer> findMedian = new TreeMap<>();
        for (int i = 0; i < selectedBatchResultEntry.getCa().length; i++) {
            tmpCA = selectedBatchResultEntry.getCa()[i];
            nrOfInd += tmpCA.getInitialIndividualCount();
            evacSec += tmpCA.getSecondsPerStep() * tmpCA.getTimeStep();
            evacCAStep += tmpCA.getTimeStep();
            evac += tmpCA.getInitialIndividualCount() - tmpCA.deadIndividualsCount();
            notEvac += tmpCA.deadIndividualsCount();
            notEvacNoExit += tmpCA.getDeadIndividualCount(DeathCause.ExitUnreachable);// getNrOfExitUnreachableDeadIndividuals();
            notEvacNoTime += tmpCA.getDeadIndividualCount(DeathCause.NotEnoughTime);// getNrOfNotEnoughTimeDeadIndividuals();
            findMedian.put(tmpCA.getTimeStep() * tmpCA.getSecondsPerStep(), i);
        }//from ww  w .  j a  va 2 s  . c om
        bestEvacIndex = findMedian.firstEntry().getValue();
        for (int j = 0; j < findMedian.size() / 2; j++)
            findMedian.remove(findMedian.firstKey());
        aveEvacIndex = findMedian.get(findMedian.firstKey());
        worseEvacIndex = findMedian.get(findMedian.lastKey());
        Object[][] data = { { "Informationen fr Modell", selectedBatchResultEntry.getName() },
                { "Evakuierungszeit in Sekunden", evacSec / selectedBatchResultEntry.getCa().length },
                { "Evakuierungszeit in ZA-Schritten", evacCAStep / selectedBatchResultEntry.getCa().length },
                { "Anzahl Individuen", (double) nrOfInd / selectedBatchResultEntry.getCa().length },
                { "evakuiert", evac / selectedBatchResultEntry.getCa().length },
                { "nicht evakuiert", notEvac / selectedBatchResultEntry.getCa().length },
                { "nicht evakuiert weil kein Ausgang erreichbar",
                        notEvacNoExit / selectedBatchResultEntry.getCa().length },
                { "nicht evakuiert weil die Zeit nicht gereicht hat",
                        notEvacNoTime / selectedBatchResultEntry.getCa().length },
                { "beste Evakuierungszeit (Durchlaufindex,Zeit)", ("(" + (bestEvacIndex + 1) + " - "
                        + (selectedBatchResultEntry.getCa()[bestEvacIndex].getTimeStep()
                                / selectedBatchResultEntry.getCa()[bestEvacIndex].getStepsPerSecond())
                        + ")") },
                { "durchschnit. Evakuierungszeit (Durchlaufindex,Zeit)", ("(" + (aveEvacIndex + 1) + " - "
                        + (selectedBatchResultEntry.getCa()[aveEvacIndex].getTimeStep()
                                / selectedBatchResultEntry.getCa()[bestEvacIndex].getStepsPerSecond())
                        + ")") },
                { "schlechteste Evakuierungszeit (Durchlaufindex,Zeit)",
                        ("(" + (worseEvacIndex + 1) + " - "
                                + (selectedBatchResultEntry.getCa()[worseEvacIndex].getTimeStep()
                                        / selectedBatchResultEntry.getCa()[bestEvacIndex].getStepsPerSecond())
                                + ")") } };
        basicInformationTable = new JTable(data, columnNames);
        basicInformationScrollPane = new JScrollPane(basicInformationTable);
        diagrams.addTable(diagrammName, basicInformationScrollPane, west);
    }

    if ((noIndividualsInAtLeastOneAssignmentIndex) && !(diagrammName.equals("Grundinformationen"))) {
        chartData = new ChartData("bar", "NO INDIVIDUALS in at least one of the choosed dataset(s)", "",
                new ArrayList<>(), new ArrayList<>());
        evakuierungsdauer = ChartFactory.createBarChart(
                "NO INDIVIDUALS in at least one of the choosed dataset(s)", "", chartData.getYAxisLabel(),
                chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true, false);
        diagrams.addChart("NO INDIVIDUALS in at least one of the choosed dataset(s)", evakuierungsdauer, west);
    } else {

        if (diagrammName.equals("Ausgangsverteilung")) {
            chartData = new ChartData("pie",
                    diagrammName + ":" + selectedBatchResultEntry.getName() + "-"
                            + assignmentGroups.get(assignmentIndexToShow.get(0)).toString(),
                    "Ausgnge", categoryDatasetValues, categoryDatasetAssignments);
            ausgangsverteilung = ChartFactory.createPieChart(
                    diagrammName + ":" + selectedBatchResultEntry.getName() + "-"
                            + assignmentGroups.get(assignmentIndexToShow.get(0)).toString(),
                    ChartData.getPieDataSet(), false, true, false);
            diagrams.addChart(diagrammName, ausgangsverteilung, west);
        }

        if (diagrammName.equals("Ankunftskurve")) {
            chartData = new ChartData("bar", diagrammName, "Zeit [s]", categoryDatasetValues,
                    categoryDatasetAssignments);
            ankunftskurve = ChartFactory.createXYLineChart(diagrammName, chartData.getYAxisLabel(),
                    "Individuen", (XYDataset) datasetCollection, PlotOrientation.VERTICAL, true, true, false);
            diagrams.addChart(diagrammName, ankunftskurve, west);
        }

        if (diagrammName.equals("Evakuierungsdauer")) {
            chartData = new ChartData("bar", diagrammName, "Zeit [s]", categoryDatasetValues,
                    categoryDatasetAssignments);
            evakuierungsdauer = ChartFactory.createBarChart(diagrammName, "Belegungen",
                    chartData.getYAxisLabel(), chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true,
                    false);
            diagrams.addChart(diagrammName, evakuierungsdauer, west);
        }

        if (diagrammName.equals("evakuierte Individuen in Prozent")) {
            chartData = new ChartData("pie",
                    diagrammName + ":" + selectedBatchResultEntry.getName() + "-"
                            + assignmentGroups.get(assignmentIndexToShow.get(0)).toString(),
                    "Individuen", categoryDatasetValues, categoryDatasetAssignments);
            evakuierteIndividueninProzent = ChartFactory.createPieChart(
                    diagrammName + ":" + selectedBatchResultEntry.getName() + "-"
                            + assignmentGroups.get(assignmentIndexToShow.get(0)).toString(),
                    ChartData.getPieDataSet(), false, true, false);
            diagrams.addChart(diagrammName, evakuierteIndividueninProzent, west);
        }

        if (diagrammName.equals("maximale Blockadezeit")) {
            chartData = new ChartData("bar", diagrammName, "Zeit [s]", categoryDatasetValues,
                    categoryDatasetAssignments);
            maxblockadezeit = ChartFactory.createBarChart(diagrammName, "Belegungen", chartData.getYAxisLabel(),
                    chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true, false);
            diagrams.addChart(diagrammName, maxblockadezeit, west);
        }

        if (diagrammName.equals("durchschnittliche Blockadezeit")) {
            chartData = new ChartData("bar", diagrammName, "Zeit [s]", categoryDatasetValues,
                    categoryDatasetAssignments);
            aveblockadezeit = ChartFactory.createBarChart(diagrammName, "Belegungen", chartData.getYAxisLabel(),
                    chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true, false);
            diagrams.addChart(diagrammName, aveblockadezeit, west);
        }

        if (diagrammName.equals("minimale Blockadezeit")) {
            chartData = new ChartData("bar", diagrammName, "Zeit [s]", categoryDatasetValues,
                    categoryDatasetAssignments);
            minblockadezeit = ChartFactory.createBarChart(diagrammName, "Belegungen", chartData.getYAxisLabel(),
                    chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true, false);
            diagrams.addChart(diagrammName, minblockadezeit, west);
        }

        if (diagrammName.equals("zurckgelegte Distanz")) {
            chartData = new ChartData("bar", diagrammName, "Meter [m]", categoryDatasetValues,
                    categoryDatasetAssignments);
            zurueckgelegteDistanz = ChartFactory.createBarChart(diagrammName, "Belegungen",
                    chartData.getYAxisLabel(), chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true,
                    false);
            diagrams.addChart(diagrammName, zurueckgelegteDistanz, west);
        }

        if (diagrammName.equals("minimale Distanz zum initialen Ausgang")) {
            chartData = new ChartData("bar", diagrammName, "Meter [m]", categoryDatasetValues,
                    categoryDatasetAssignments);
            minimaleDistanzzuminitialenAusgang = ChartFactory.createBarChart(diagrammName, "Belegungen",
                    chartData.getYAxisLabel(), chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true,
                    false);
            diagrams.addChart(diagrammName, minimaleDistanzzuminitialenAusgang, west);
        }

        if (diagrammName.equals("minimale Distanz zum nchsten Ausgang")) {
            chartData = new ChartData("bar", diagrammName, "Meter [m]", categoryDatasetValues,
                    categoryDatasetAssignments);
            minimaleDistanzzumnaechstenAusgang = ChartFactory.createBarChart(diagrammName, "Belegungen",
                    chartData.getYAxisLabel(), chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true,
                    false);
            diagrams.addChart(diagrammName, minimaleDistanzzumnaechstenAusgang, west);
        }

        if (diagrammName.equals("maximale Zeit bis Safe")) {
            chartData = new ChartData("bar", diagrammName, "Zeit [s]", categoryDatasetValues,
                    categoryDatasetAssignments);
            maxZeitBisSafe = ChartFactory.createBarChart(diagrammName, "Belegungen", chartData.getYAxisLabel(),
                    chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true, false);
            diagrams.addChart(diagrammName, maxZeitBisSafe, west);
        }

        if (diagrammName.equals("durchschnittliche Zeit bis Safe")) {
            chartData = new ChartData("bar", diagrammName, "Zeit [s]", categoryDatasetValues,
                    categoryDatasetAssignments);
            aveZeitBisSafe = ChartFactory.createBarChart(diagrammName, "Belegungen", chartData.getYAxisLabel(),
                    chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true, false);
            diagrams.addChart(diagrammName, aveZeitBisSafe, west);
        }

        if (diagrammName.equals("minimale Zeit bis Safe")) {
            chartData = new ChartData("bar", diagrammName, "Zeit [s]", categoryDatasetValues,
                    categoryDatasetAssignments);
            minZeitBisSafe = ChartFactory.createBarChart(diagrammName, "Belegungen", chartData.getYAxisLabel(),
                    chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true, false);
            diagrams.addChart(diagrammName, minZeitBisSafe, west);
        }

        if (diagrammName.equals("Distanz ber Zeit")) {
            chartData = new ChartData("bar", diagrammName, "Meter [m]", categoryDatasetValues,
                    categoryDatasetAssignments);
            distanzueberZeit = ChartFactory.createXYLineChart(diagrammName, "Zeit [s]",
                    chartData.getYAxisLabel(), (XYDataset) datasetCollection, PlotOrientation.VERTICAL, true,
                    true, false);
            diagrams.addChart(diagrammName, distanzueberZeit, west);
        }

        if (diagrammName.equals("maximale Geschwindigkeit ber Zeit")) {
            chartData = new ChartData("bar", diagrammName, "Zeit [s]", categoryDatasetValues,
                    categoryDatasetAssignments);
            maximaleGeschwindigkeitueberZeit = ChartFactory.createXYLineChart(diagrammName,
                    chartData.getYAxisLabel(), "Meter pro Sekunde [m/s]", (XYDataset) datasetCollection,
                    PlotOrientation.VERTICAL, true, true, false);
            diagrams.addChart(diagrammName, maximaleGeschwindigkeitueberZeit, west);
        }

        if (diagrammName.equals("durschnittliche Geschwindigkeit ber Zeit")) {
            chartData = new ChartData("bar", diagrammName, "Zeit [s]", categoryDatasetValues,
                    categoryDatasetAssignments);
            durschnittlicheGeschwindigkeitueberZeit = ChartFactory.createXYLineChart(diagrammName,
                    chartData.getYAxisLabel(), "Meter pro Sekunde [m/s]", (XYDataset) datasetCollection,
                    PlotOrientation.VERTICAL, true, true, false);
            diagrams.addChart(diagrammName, durschnittlicheGeschwindigkeitueberZeit, west);
        }

        if (diagrammName.equals("maximale Geschwindigkeit")) {
            chartData = new ChartData("bar", diagrammName, "Meter pro Sekunde [m/s]", categoryDatasetValues,
                    categoryDatasetAssignments);
            maximaleGeschwindigkeit = ChartFactory.createBarChart(diagrammName, "Belegungen",
                    chartData.getYAxisLabel(), chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true,
                    false);
            diagrams.addChart(diagrammName, maximaleGeschwindigkeit, west);
        }

        if (diagrammName.equals("durchschnittliche Geschwindigkeit")) {
            chartData = new ChartData("bar", diagrammName, "Meter pro Sekunde [m/s]", categoryDatasetValues,
                    categoryDatasetAssignments);
            durchschnittlicheGeschwindigkeit = ChartFactory.createBarChart(diagrammName, "Belegungen",
                    chartData.getYAxisLabel(), chartData.getCDataSet(), PlotOrientation.VERTICAL, false, true,
                    false);
            diagrams.addChart(diagrammName, durchschnittlicheGeschwindigkeit, west);
        }

        if (diagrammName.equals("Panik ber Zeit")) {
            chartData = new ChartData("bar", diagrammName, "Zeit [s]", categoryDatasetValues,
                    categoryDatasetAssignments);
            panik = ChartFactory.createXYLineChart(diagrammName, chartData.getYAxisLabel(), "Panik",
                    (XYDataset) datasetCollection, PlotOrientation.VERTICAL, true, true, false);
            diagrams.addChart(diagrammName, panik, west);
        }

        if (diagrammName.equals("Erschpfung ber Zeit")) {
            chartData = new ChartData("bar", diagrammName, "Zeit [s]", categoryDatasetValues,
                    categoryDatasetAssignments);
            erschoepfung = ChartFactory.createXYLineChart(diagrammName, chartData.getYAxisLabel(),
                    "Erschpfung", (XYDataset) datasetCollection, PlotOrientation.VERTICAL, true, true, false);
            diagrams.addChart(diagrammName, erschoepfung, west);
        }

    } //end else

    categoryDatasetValues = new ArrayList<>();
    categoryDatasetAssignments = new ArrayList<>();
    //dataset = new XYSeries("");
    datasetCollection = new XYSeriesCollection();
    diagrams.validate();
}

From source file:org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.JobControlCompiler.java

/**
 * Reads the global counters produced by a job on the group labeled with PIG_MAP_RANK_NAME.
 * Then, it is calculated the cumulative sum, which consists on the sum of previous cumulative
 * sum plus the previous global counter value.
 * @param job with the global counters collected.
 * @param operationID After being collected on global counters (POCounter),
 * these values are passed via configuration file to PORank, by using the unique
 * operation identifier//from   ww  w.  j a v  a 2  s . c o m
 */
private void saveCounters(Job job, String operationID, boolean isRowNumber) {
    Counters counters;
    Group groupCounters;

    int counterSize = -1;
    Long previousValue = 0L;
    Long previousSum = 0L;
    ArrayList<Pair<String, Long>> counterPairs;

    try {
        counters = HadoopShims.getCounters(job);

        String groupName = getGroupName(counters.getGroupNames());
        // In case that the counter group was not find, we need to find
        // out why. Only acceptable state is that the relation has been
        // empty.
        if (groupName == null) {
            Counter outputRecords = counters.getGroup(MRPigStatsUtil.TASK_COUNTER_GROUP)
                    .getCounterForName(MRPigStatsUtil.MAP_OUTPUT_RECORDS);

            if (outputRecords.getCounter() == 0) {
                globalCounters.put(operationID, new ArrayList<Pair<String, Long>>());
                return;
            } else {
                throw new RuntimeException("Did not found RANK counter group for operationId: " + operationID);
            }
        }
        groupCounters = counters.getGroup(groupName);

        TreeMap<Integer, Long> counterList = new TreeMap<Integer, Long>();

        Iterator<Counter> it = groupCounters.iterator();
        while (it.hasNext()) {
            try {
                Counter c = it.next();
                counterList.put(Integer.valueOf(c.getDisplayName()), c.getValue());
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        counterSize = counterList.size();
        counterPairs = new ArrayList<Pair<String, Long>>();

        // There could be empty tasks with no counters. That is not an issue
        // and we only need to calculate offsets for non-empty task ids
        // which will be accessed in PORank.
        for (Entry<Integer, Long> entry : counterList.entrySet()) {
            previousSum += previousValue;
            previousValue = entry.getValue();
            counterPairs.add(new Pair<String, Long>(JobControlCompiler.PIG_MAP_COUNTER + operationID
                    + JobControlCompiler.PIG_MAP_SEPARATOR + entry.getKey(), previousSum));
        }

        globalCounters.put(operationID, counterPairs);

    } catch (Exception e) {
        String msg = "Error to read counters into Rank operation counterSize " + counterSize;
        throw new RuntimeException(msg, e);
    }
}