Example usage for java.util SortedMap keySet

List of usage examples for java.util SortedMap keySet

Introduction

In this page you can find the example usage for java.util SortedMap keySet.

Prototype

Set<K> keySet();

Source Link

Document

Returns a Set view of the keys contained in this map.

Usage

From source file:org.wso2.carbon.appmgt.impl.token.JWTGenerator.java

/**
   * Method that generates the JWT.//w w w . ja v a 2  s.  co m
   *
   * @param keyValidationInfoDTO
   * @param apiContext
   * @param version
   * @param includeEndUserName
   * @return signed JWT token
   * @throws org.wso2.carbon.appmgt.api.AppManagementException
   */
public String generateToken(APIKeyValidationInfoDTO keyValidationInfoDTO, String apiContext, String version,
        boolean includeEndUserName) throws AppManagementException {

    //generating expiring timestamp
    long currentTime = Calendar.getInstance().getTimeInMillis();
    long expireIn = currentTime + 1000 * 60 * getTTL();

    String jwtBody;
    String dialect;
    if (claimsRetriever != null) {
        //jwtBody = JWT_INITIAL_BODY.replaceAll("\\[0\\]", claimsRetriever.getDialectURI(endUserName));
        dialect = claimsRetriever.getDialectURI(keyValidationInfoDTO.getEndUserName());
    } else {
        //jwtBody = JWT_INITIAL_BODY.replaceAll("\\[0\\]", dialectURI);
        dialect = dialectURI;
    }

    String subscriber = keyValidationInfoDTO.getSubscriber();
    String applicationName = keyValidationInfoDTO.getApplicationName();
    String applicationId = keyValidationInfoDTO.getApplicationId();
    String tier = keyValidationInfoDTO.getTier();
    String endUserName = includeEndUserName ? keyValidationInfoDTO.getEndUserName() : null;
    String keyType = keyValidationInfoDTO.getType();
    String userType = keyValidationInfoDTO.getUserType();
    String applicationTier = keyValidationInfoDTO.getApplicationTier();
    String enduserTenantId = includeEndUserName ? String.valueOf(getTenantId(endUserName)) : null;

    //Sample JWT body
    //{"iss":"wso2.org/products/am","exp":1349267862304,"http://wso2.org/claims/subscriber":"nirodhasub",
    // "http://wso2.org/claims/applicationname":"App1","http://wso2.org/claims/apicontext":"/echo",
    // "http://wso2.org/claims/version":"1.2.0","http://wso2.org/claims/tier":"Gold",
    // "http://wso2.org/claims/enduser":"null"}

    StringBuilder jwtBuilder = new StringBuilder();
    jwtBuilder.append("{");
    jwtBuilder.append("\"iss\":\"");
    jwtBuilder.append(API_GATEWAY_ID);
    jwtBuilder.append("\",");

    jwtBuilder.append("\"exp\":");
    jwtBuilder.append(String.valueOf(expireIn));
    jwtBuilder.append(",");

    jwtBuilder.append("\"");
    jwtBuilder.append(dialect);
    jwtBuilder.append("/subscriber\":\"");
    jwtBuilder.append(subscriber);
    jwtBuilder.append("\",");

    jwtBuilder.append("\"");
    jwtBuilder.append(dialect);
    jwtBuilder.append("/applicationid\":\"");
    jwtBuilder.append(applicationId);
    jwtBuilder.append("\",");

    jwtBuilder.append("\"");
    jwtBuilder.append(dialect);
    jwtBuilder.append("/applicationname\":\"");
    jwtBuilder.append(applicationName);
    jwtBuilder.append("\",");

    jwtBuilder.append("\"");
    jwtBuilder.append(dialect);
    jwtBuilder.append("/applicationtier\":\"");
    jwtBuilder.append(applicationTier);
    jwtBuilder.append("\",");

    jwtBuilder.append("\"");
    jwtBuilder.append(dialect);
    jwtBuilder.append("/apicontext\":\"");
    jwtBuilder.append(apiContext);
    jwtBuilder.append("\",");

    jwtBuilder.append("\"");
    jwtBuilder.append(dialect);
    jwtBuilder.append("/version\":\"");
    jwtBuilder.append(version);
    jwtBuilder.append("\",");

    jwtBuilder.append("\"");
    jwtBuilder.append(dialect);
    jwtBuilder.append("/tier\":\"");
    jwtBuilder.append(tier);
    jwtBuilder.append("\",");

    jwtBuilder.append("\"");
    jwtBuilder.append(dialect);
    jwtBuilder.append("/keytype\":\"");
    jwtBuilder.append(keyType);
    jwtBuilder.append("\",");

    jwtBuilder.append("\"");
    jwtBuilder.append(dialect);
    jwtBuilder.append("/usertype\":\"");
    jwtBuilder.append(userType);
    jwtBuilder.append("\",");

    jwtBuilder.append("\"");
    jwtBuilder.append(dialect);
    jwtBuilder.append("/enduser\":\"");
    jwtBuilder.append(endUserName);
    jwtBuilder.append("\",");

    jwtBuilder.append("\"");
    jwtBuilder.append(dialect);
    jwtBuilder.append("/enduserTenantId\":\"");
    jwtBuilder.append(enduserTenantId);
    jwtBuilder.append("\"");

    if (claimsRetriever != null) {
        SortedMap<String, String> claimValues = claimsRetriever.getClaims(endUserName);
        Iterator<String> it = new TreeSet(claimValues.keySet()).iterator();
        while (it.hasNext()) {
            String claimURI = it.next();
            jwtBuilder.append(", \"");
            jwtBuilder.append(claimURI);
            jwtBuilder.append("\":\"");
            jwtBuilder.append(claimValues.get(claimURI));
            jwtBuilder.append("\"");
        }
    }

    jwtBuilder.append("}");
    jwtBody = jwtBuilder.toString();

    String jwtHeader = null;

    //if signature algo==NONE, header without cert
    if (signatureAlgorithm.equals(NONE)) {
        jwtHeader = "{\"typ\":\"JWT\"}";
    } else if (signatureAlgorithm.equals(SHA256_WITH_RSA)) {
        jwtHeader = addCertToHeader(endUserName);
    }

    /*//add cert thumbprint to header
    String headerWithCertThumb = addCertToHeader(endUserName);*/

    String base64EncodedHeader = Base64Utils.encode(jwtHeader.getBytes());
    String base64EncodedBody = Base64Utils.encode(jwtBody.getBytes());
    if (signatureAlgorithm.equals(SHA256_WITH_RSA)) {
        String assertion = base64EncodedHeader + "." + base64EncodedBody;

        //get the assertion signed
        byte[] signedAssertion = signJWT(assertion, endUserName);

        if (log.isDebugEnabled()) {
            log.debug("signed assertion value : " + new String(signedAssertion));
        }
        String base64EncodedAssertion = Base64Utils.encode(signedAssertion);

        return base64EncodedHeader + "." + base64EncodedBody + "." + base64EncodedAssertion;
    } else {
        return base64EncodedHeader + "." + base64EncodedBody + ".";
    }
}

From source file:org.wso2.carbon.ml.dataset.internal.DatabaseHandler.java

/**
 * Create the JSON string with summary statistics for a column.
 *
 * @param type              Data-type of the column
 * @param graphFrequencies  Bin frequencies of the column
 * @param missing           Number of missing values in the column
 * @param unique            Number of unique values in the column
 * @param descriptiveStats  DescriptiveStats object of the column
 * @return                  JSON representation of the summary statistics of the column
 *//*from w  w  w .  ja va 2 s .c  om*/
private JSONArray createJson(String type, SortedMap<?, Integer> graphFrequencies, int missing, int unique,
        DescriptiveStatistics descriptiveStats) {
    JSONObject json = new JSONObject();
    JSONArray freqs = new JSONArray();
    Object[] categoryNames = graphFrequencies.keySet().toArray();
    // Create an array with intervals/categories and their frequencies.
    for (int i = 0; i < graphFrequencies.size(); i++) {
        JSONArray temp = new JSONArray();
        temp.put(categoryNames[i].toString());
        temp.put(graphFrequencies.get(categoryNames[i]));
        freqs.put(temp);
    }
    // Put the statistics to a json object
    json.put("unique", unique);
    json.put("missing", missing);

    DecimalFormat decimalFormat = new DecimalFormat("#.###");
    if (descriptiveStats.getN() != 0) {
        json.put("mean", decimalFormat.format(descriptiveStats.getMean()));
        json.put("median", decimalFormat.format(descriptiveStats.getPercentile(50)));
        json.put("std", decimalFormat.format(descriptiveStats.getStandardDeviation()));
        if (type.equalsIgnoreCase(FeatureType.NUMERICAL)) {
            json.put("skewness", decimalFormat.format(descriptiveStats.getSkewness()));
        }
    }
    json.put("values", freqs);
    json.put("bar", true);
    json.put("key", "Frequency");
    JSONArray summaryStatArray = new JSONArray();
    summaryStatArray.put(json);
    return summaryStatArray;
}

From source file:vmware.au.se.sqlfireweb.controller.QueryController.java

@RequestMapping(value = "/query", method = RequestMethod.POST)
public String worksheetAction(@ModelAttribute("queryAttribute") QueryWindow queryAttribute, Model model,
        HttpServletResponse response, HttpServletRequest request, HttpSession session) throws Exception {
    if (session.getAttribute("user_key") == null) {
        logger.debug("user_key is null new Login required");
        response.sendRedirect(request.getContextPath() + "/sqlfireweb/login");
        return null;
    }//from www.ja  v  a  2  s .c  om

    logger.debug("Received request to action SQL from query worksheet");
    logger.info(queryAttribute);

    UserPref userPrefs = (UserPref) session.getAttribute("prefs");

    ConnectionManager cm = ConnectionManager.getInstance();

    if (queryAttribute.getQuery() != null) {
        // retrieve connection
        Connection conn = cm.getConnection(session.getId());
        String query = queryAttribute.getQuery().trim();
        logger.debug("Query = " + query);

        String[] splitQueryStr = spiltQuery(query);

        CommandResult result = new CommandResult();

        if (query.length() > 0) {
            if (splitQueryStr.length == 1) {
                String s = checkForComments(query);
                s = s.trim();

                if (determineQueryType(s).equals("SELECT")) {
                    try {
                        if (queryAttribute.getExplainPlan().equals("Y")) {
                            logger.debug("Need to run explain plan");
                            model.addAttribute("explainresult", QueryUtil.runExplainPlan(conn, query));
                        } else {

                            if (queryAttribute.getShowMember().equals("Y")) {
                                String replace = "select dsid() as \"Member\",";

                                s = query.toLowerCase().replaceFirst("select", replace);
                            }

                            long start = System.currentTimeMillis();
                            Result res = QueryUtil.runQuery(conn, s, userPrefs.getMaxRecordsinSQLQueryWindow());
                            long end = System.currentTimeMillis();

                            double timeTaken = new Double(end - start).doubleValue();
                            DecimalFormat df = new DecimalFormat("#.##");

                            model.addAttribute("queryResults", res);
                            model.addAttribute("query", s);
                            model.addAttribute("querysql", s);
                            if (queryAttribute.getQueryCount().equals("Y")) {
                                model.addAttribute("queryResultCount", res.getRowCount());
                            }

                            if (queryAttribute.getElapsedTime().equals("Y")) {
                                model.addAttribute("elapsedTime", df.format(timeTaken / 1000));
                            }

                            addCommandToHistory(session, userPrefs, s);

                        }
                    } catch (Exception ex) {
                        result.setCommand(s);
                        result.setMessage(ex.getMessage() == null ? "Unable to run query" : ex.getMessage());
                        result.setRows(-1);
                        model.addAttribute("result", result);
                        model.addAttribute("query", s);
                    }
                } else {
                    if (s.length() > 0) {
                        if (determineQueryType(s).equals("COMMIT")) {
                            result = QueryUtil.runCommitOrRollback(conn, true, queryAttribute.getElapsedTime());
                            model.addAttribute("result", result);
                            if (result.getMessage().startsWith("SUCCESS")) {
                                addCommandToHistory(session, userPrefs, s);
                            }
                        } else if (determineQueryType(s).equals("ROLLBACK")) {
                            result = QueryUtil.runCommitOrRollback(conn, false,
                                    queryAttribute.getElapsedTime());
                            model.addAttribute("result", result);
                            if (result.getMessage().startsWith("SUCCESS")) {
                                addCommandToHistory(session, userPrefs, s);
                            }
                        } else if (determineQueryType(s).equals("CALL")) {

                            String procName = getProcName(s);

                            if (procName != null) {
                                String schema = null;

                                int x = procName.indexOf(".");
                                if (x != -1) {
                                    String newProcName = procName.substring((procName.indexOf(".") + 1));
                                    schema = procName.substring(0, (procName.indexOf(".")));
                                    procName = newProcName;
                                } else {
                                    schema = (String) session.getAttribute("schema");
                                }

                                logger.debug("schema for stored procedure = " + schema);
                                logger.debug("call statement called for proc with name " + procName);

                                // need to get schema name to check proc details
                                int numberOfDynamicResultSets = QueryUtil.checkForDynamicResultSetProc(conn,
                                        schema, procName);

                                if (numberOfDynamicResultSets > 0) {
                                    logger.debug("call statement with " + numberOfDynamicResultSets
                                            + " dynamic resultset(s)");
                                    try {
                                        List<Result> procResults = QueryUtil.runStoredprocWithResultSet(conn, s,
                                                userPrefs.getMaxRecordsinSQLQueryWindow(),
                                                numberOfDynamicResultSets);
                                        model.addAttribute("procresults", procResults);
                                        model.addAttribute("callstatement", procName);
                                        model.addAttribute("dynamicresults", numberOfDynamicResultSets);
                                        addCommandToHistory(session, userPrefs, s);
                                    } catch (Exception ex) {
                                        result.setCommand(s);
                                        result.setMessage(ex.getMessage() == null ? "Unable to run query"
                                                : ex.getMessage());
                                        result.setRows(-1);
                                        model.addAttribute("result", result);
                                        model.addAttribute("query", s);
                                    }
                                } else {
                                    result = QueryUtil.runCommand(conn, s, queryAttribute.getElapsedTime());
                                    model.addAttribute("result", result);
                                    if (result.getMessage().startsWith("SUCCESS")) {
                                        addCommandToHistory(session, userPrefs, s);
                                    }
                                }
                            } else {
                                result = QueryUtil.runCommand(conn, s, queryAttribute.getElapsedTime());
                                model.addAttribute("result", result);
                                if (result.getMessage().startsWith("SUCCESS")) {
                                    addCommandToHistory(session, userPrefs, s);
                                }
                            }
                        } else {
                            result = QueryUtil.runCommand(conn, s, queryAttribute.getElapsedTime());
                            model.addAttribute("result", result);
                            if (result.getMessage().startsWith("SUCCESS")) {
                                addCommandToHistory(session, userPrefs, s);
                            }
                        }

                    }
                }

            } else {
                logger.debug("multiple SQL statements need to be executed");
                SortedMap<String, Object> queryResults = handleMultipleStatements(splitQueryStr, conn,
                        userPrefs, queryAttribute, session);
                logger.debug("keys : " + queryResults.keySet());
                model.addAttribute("sqlResultMap", queryResults);
                model.addAttribute("statementsExecuted", queryResults.size());

            }
        }
    } else {
        if (ServletFileUpload.isMultipartContent(request)) {
            logger.debug("is multipartcontent request");
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<?> fileItemsList = upload.parseRequest(request);

            logger.debug("fileItemList size = " + fileItemsList.size());
            Iterator<?> it = fileItemsList.iterator();
            while (it.hasNext()) {
                FileItem fileItemTemp = (FileItem) it.next();
                if (fileItemTemp.getFieldName().equals("sqlfilename")) {
                    QueryWindow qw = new QueryWindow();
                    qw.setQuery(fileItemTemp.getString());
                    model.addAttribute("queryAttribute", qw);
                    model.addAttribute("sqlfile", fileItemTemp.getName());
                }
            }
        }
    }

    return "query";
}

From source file:org.jasig.schedassist.web.VisibleScheduleTag.java

@Override
public int doStartTagInternal() {
    final ServletContext servletContext = pageContext.getServletContext();

    final Date scheduleStart = visibleSchedule.getScheduleStart();
    if (null == scheduleStart) {
        // the visibleSchedule is empty, short circuit
        try {/*from  w ww. j av a 2s . c  om*/
            StringBuilder noappointments = new StringBuilder();
            noappointments.append("<span class=\"none-available\">");
            noappointments.append(getMessageSource().getMessage("no.available.appointments", null, null));
            noappointments.append("</span>");
            pageContext.getOut().write(noappointments.toString());
        } catch (IOException e) {
            LOG.error("IOException occurred in doStartTag", e);
        }
        // SKIP_BODY means don't print any content from body of tag
        return SKIP_BODY;
    }

    LOG.debug("scheduleStart: " + scheduleStart);
    SortedMap<Date, List<AvailableBlock>> dailySchedules = new TreeMap<Date, List<AvailableBlock>>();
    Date index = DateUtils.truncate(scheduleStart, java.util.Calendar.DATE);
    Date scheduleEnd = visibleSchedule.getScheduleEnd();
    while (index.before(scheduleEnd)) {
        dailySchedules.put(index, new ArrayList<AvailableBlock>());
        index = DateUtils.addDays(index, 1);
    }
    final Date lastMapKey = dailySchedules.lastKey();
    LOG.debug("visibleSchedule spans " + dailySchedules.keySet().size() + " days");

    try {
        SortedMap<AvailableBlock, AvailableStatus> scheduleBlockMap = visibleSchedule.getBlockMap();
        int numberOfEventsToDisplay = 0;
        for (AvailableBlock block : scheduleBlockMap.keySet()) {
            Date eventStartDate = block.getStartTime();
            LOG.debug("event start date: " + eventStartDate);
            Date mapKey = DateUtils.truncate(eventStartDate, java.util.Calendar.DATE);
            if (CommonDateOperations.equalsOrAfter(eventStartDate, scheduleStart)
                    && dailySchedules.containsKey(mapKey)) {
                dailySchedules.get(mapKey).add(block);
                numberOfEventsToDisplay++;
            }
        }
        LOG.debug("number of events to display: " + numberOfEventsToDisplay);
        if (numberOfEventsToDisplay == 0) {
            // no available times in this range!
            StringBuilder noappointments = new StringBuilder();
            noappointments.append("<span class=\"none-available\">");
            noappointments.append(getMessageSource().getMessage("no.available.appointments", null, null));
            noappointments.append("</span>");
            pageContext.getOut().write(noappointments.toString());
        } else {
            int weekNumber = 1;
            Date currentWeekStart = DateUtils.truncate(scheduleStart, java.util.Calendar.DATE);
            Date currentWeekFinish = DateUtils.addDays(currentWeekStart,
                    CommonDateOperations.numberOfDaysUntilSunday(currentWeekStart));
            currentWeekFinish = DateUtils.addMinutes(currentWeekFinish, -1);

            boolean renderAnotherWeek = true;

            while (renderAnotherWeek) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("will render another week using currentWeekStart " + currentWeekStart
                            + " and currentWeekFinish " + currentWeekFinish);
                }
                SortedMap<Date, List<AvailableBlock>> subMap = dailySchedules.subMap(currentWeekStart,
                        currentWeekFinish);
                renderWeek(servletContext, pageContext.getOut(), weekNumber++, subMap, scheduleBlockMap);

                currentWeekStart = DateUtils.addMinutes(currentWeekFinish, 1);
                currentWeekFinish = DateUtils.addDays(currentWeekStart, 7);
                currentWeekFinish = DateUtils.addMinutes(currentWeekFinish, -1);

                if (LOG.isDebugEnabled()) {
                    LOG.debug("recalculated currentWeekStart " + currentWeekStart + ", currentWeekFinish "
                            + currentWeekFinish);
                }

                if (currentWeekStart.after(lastMapKey)) {
                    renderAnotherWeek = false;
                    LOG.debug("will not render another week");
                }
            }
        }

    } catch (IOException e) {
        LOG.error("IOException occurred in doStartTag", e);
    }
    // SKIP_BODY means don't print any content from body of tag
    return SKIP_BODY;
}

From source file:com.activecq.tools.errorpagehandler.impl.ErrorPageHandlerImpl.java

/**
 * Merge two Maps together. In the event of any key collisions the Master map wins
 *
 * Any blank value keys are dropped from the final Map
 *
 * Map is sorted by value (String) length
 *
 * @param master//from ww w .  j  ava2s . c  om
 * @param slave
 * @return
 */
private SortedMap<String, String> mergeMaps(SortedMap<String, String> master, SortedMap<String, String> slave) {
    SortedMap<String, String> map = new TreeMap<String, String>(new StringLengthComparator());

    for (final String key : master.keySet()) {
        if (StringUtils.isNotBlank(master.get(key))) {
            map.put(key, master.get(key));
        }
    }

    for (final String key : slave.keySet()) {
        if (master.containsKey(key)) {
            continue;
        }
        if (StringUtils.isNotBlank(slave.get(key))) {
            map.put(key, slave.get(key));
        }
    }

    return map;
}

From source file:net.sourceforge.subsonic.controller.WapController.java

public ModelAndView wap(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Map<String, Object> map = new HashMap<String, Object>();

    String username = securityService.getCurrentUsername(request);
    List<MusicFolder> folders = settingsService.getMusicFoldersForUser(username);

    if (folders.isEmpty()) {
        map.put("noMusic", true);
    } else {//from   w  ww. jav  a  2 s  .c o  m

        SortedMap<MusicIndex, List<MusicIndex.SortableArtistWithMediaFiles>> allArtists = musicIndexService
                .getIndexedArtists(folders, false);

        // If an index is given as parameter, only show music files for this index.
        String index = request.getParameter("index");
        if (index != null) {
            List<MusicIndex.SortableArtistWithMediaFiles> artists = allArtists.get(new MusicIndex(index));
            if (artists == null) {
                map.put("noMusic", true);
            } else {
                map.put("artists", artists);
            }
        }

        // Otherwise, list all indexes.
        else {
            map.put("indexes", allArtists.keySet());
        }
    }

    return new ModelAndView("wap/index", "model", map);
}

From source file:org.jasig.schedassist.portlet.VisibleScheduleTag.java

@Override
public int doStartTagInternal() {
    RenderRequest renderRequest = (RenderRequest) pageContext.getRequest().getAttribute(PORTLET_REQUEST);
    RenderResponse renderResponse = (RenderResponse) pageContext.getRequest().getAttribute(PORTLET_RESPONSE);

    final Date scheduleStart = visibleSchedule.getScheduleStart();
    if (null == scheduleStart) {
        // the visibleSchedule is empty, short circuit
        try {/*w w  w  . ja  va 2s  .  co m*/
            StringBuilder noappointments = new StringBuilder();
            noappointments.append("<span class=\"none-available\">");
            noappointments.append(getMessageSource().getMessage("no.available.appointments", null, null));
            noappointments.append("</span>");
            pageContext.getOut().write(noappointments.toString());
        } catch (IOException e) {
            LOG.error("IOException occurred in doStartTag", e);
        }
        // SKIP_BODY means don't print any content from body of tag
        return SKIP_BODY;
    }

    LOG.debug("scheduleStart: " + scheduleStart);
    SortedMap<Date, List<AvailableBlock>> dailySchedules = new TreeMap<Date, List<AvailableBlock>>();
    Date index = DateUtils.truncate(scheduleStart, java.util.Calendar.DATE);
    Date scheduleEnd = visibleSchedule.getScheduleEnd();
    while (index.before(scheduleEnd)) {
        dailySchedules.put(index, new ArrayList<AvailableBlock>());
        index = DateUtils.addDays(index, 1);
    }
    final Date lastMapKey = dailySchedules.lastKey();
    LOG.debug("visibleSchedule spans " + dailySchedules.keySet().size() + " days");

    try {
        SortedMap<AvailableBlock, AvailableStatus> scheduleBlockMap = visibleSchedule.getBlockMap();
        int numberOfEventsToDisplay = 0;
        for (AvailableBlock block : scheduleBlockMap.keySet()) {
            Date eventStartDate = block.getStartTime();
            LOG.debug("event start date: " + eventStartDate);
            Date mapKey = DateUtils.truncate(eventStartDate, java.util.Calendar.DATE);
            if (CommonDateOperations.equalsOrAfter(eventStartDate, scheduleStart)
                    && dailySchedules.containsKey(mapKey)) {
                dailySchedules.get(mapKey).add(block);
                numberOfEventsToDisplay++;
            }
        }
        LOG.debug("number of events to display: " + numberOfEventsToDisplay);
        if (numberOfEventsToDisplay == 0) {
            // no available times in this range!
            StringBuilder noappointments = new StringBuilder();
            noappointments.append("<span class=\"none-available\">");
            noappointments.append(getMessageSource().getMessage("no.available.appointments", null, null));
            noappointments.append("</span>");
            pageContext.getOut().write(noappointments.toString());
        } else {
            int weekNumber = 1;
            Date currentWeekStart = DateUtils.truncate(scheduleStart, java.util.Calendar.DATE);
            Date currentWeekFinish = DateUtils.addDays(currentWeekStart,
                    CommonDateOperations.numberOfDaysUntilSunday(currentWeekStart));
            currentWeekFinish = DateUtils.addMinutes(currentWeekFinish, -1);

            boolean renderAnotherWeek = true;

            while (renderAnotherWeek) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("will render another week using currentWeekStart " + currentWeekStart
                            + " and currentWeekFinish " + currentWeekFinish);
                }
                SortedMap<Date, List<AvailableBlock>> subMap = dailySchedules.subMap(currentWeekStart,
                        currentWeekFinish);
                renderWeek(pageContext.getOut(), weekNumber++, subMap, scheduleBlockMap, renderRequest,
                        renderResponse);

                currentWeekStart = DateUtils.addMinutes(currentWeekFinish, 1);
                currentWeekFinish = DateUtils.addDays(currentWeekStart, 7);
                currentWeekFinish = DateUtils.addMinutes(currentWeekFinish, -1);

                if (LOG.isDebugEnabled()) {
                    LOG.debug("recalculated currentWeekStart " + currentWeekStart + ", currentWeekFinish "
                            + currentWeekFinish);
                }

                if (currentWeekStart.after(lastMapKey)) {
                    renderAnotherWeek = false;
                    LOG.debug("will not render another week");
                }
            }
        }

    } catch (IOException e) {
        LOG.error("IOException occurred in doStartTag", e);
    }
    // SKIP_BODY means don't print any content from body of tag
    return SKIP_BODY;
}

From source file:org.apache.felix.webconsole.internal.compendium.ConfigManager.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // let's check for a json request
    final String currInfo = request.getPathInfo();
    if (currInfo.endsWith(".json")) {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        // after last slash and without extension
        String tempPid = currInfo.substring(currInfo.lastIndexOf('/') + 1, currInfo.length() - TAIL_LENGTH);
        // check whether the pid is actually a filter for the selection
        // of configurations to display
        String pidFilter = request.getParameter(PID_FILTER);
        if (pidFilter == null) {
            pidFilter = tempPid;//w w w  .ja v a2  s  . co m
        }
        try {
            getBundleContext().createFilter(pidFilter);

            // if the pidFilter was set from the pid, clear the pid
            if (tempPid == pidFilter) {
                tempPid = null;
            }
        } catch (InvalidSyntaxException ex) {
            pidFilter = null;
        }

        final ConfigurationAdmin currConfigAdmin = this.getConfigurationAdmin();

        final Locale currLocale = getLocale(request);
        final String localeInfo = (currLocale != null) ? currLocale.toString() : null;

        final PrintWriter printWriter = response.getWriter();

        try {
            printWriter.write("[");
            final SortedMap tempServices = this.getServices(tempPid, pidFilter, localeInfo, false);
            final Iterator tempIter = tempServices.keySet().iterator();
            boolean moreConfig = false;
            while (tempIter.hasNext()) {
                final String servicePid = tempIter.next().toString();

                final Configuration config = this.getConfigurationWithPid(currConfigAdmin, servicePid);
                if (config != null) {
                    if (moreConfig) {
                        printWriter.print(',');
                    }
                    this.printJsonConfig(printWriter, servicePid, config, pidFilter, localeInfo);
                    moreConfig = true;
                }
            }
            printWriter.write("]");
        } catch (InvalidSyntaxException ex) {
            // this should not happend as we checked the filter before
        }
        // nothing more to do
        return;
    }

    super.doGet(request, response);
}

From source file:com.aurel.track.item.history.HistoryLoaderBL.java

/**
 * Get the list of HistoryValues from the map of Map<Integer, Map<Integer, HistoryValues>>
 * @param allHistoryMap//from   w w  w.  j  a va2s . c  o m
 * @param workItemBeansMap
 * @param workItemID
 * @param locale
 * @param longEntriesSeparate
 * @return
 */
public static List<FlatHistoryBean> getFlatHistoryValuesList(
        SortedMap<Integer, Map<Integer, HistoryValues>> allHistoryMap,
        Map<Integer, TWorkItemBean> workItemBeansMap, Integer workItemID, Locale locale,
        boolean longEntriesSeparate, boolean withChildren) {
    List<FlatHistoryBean> historyList = new ArrayList<FlatHistoryBean>();
    if (allHistoryMap != null) {
        Iterator<Integer> itrHistoryMap = allHistoryMap.keySet().iterator();
        while (itrHistoryMap.hasNext()) {
            Integer transactionID = itrHistoryMap.next();
            Map<Integer, HistoryValues> changesMap = allHistoryMap.get(transactionID);
            Set<Integer> changedFieldIDs = changesMap.keySet();
            int type = getType(changedFieldIDs);
            HistoryValues histValues = null;
            List<HistoryEntry> historyEntries = new ArrayList<HistoryEntry>();
            List<HistoryEntry> historyLongEntries = new ArrayList<HistoryEntry>();
            Iterator<Integer> itrChanges = changedFieldIDs.iterator();
            while (itrChanges.hasNext()) {
                Integer fieldID = itrChanges.next();
                histValues = changesMap.get(fieldID);
                HistoryEntry historyEntry = new HistoryEntry();
                historyEntry.setFieldLabel(histValues.getFieldName());
                String newValue = histValues.getNewShowValue();
                String oldValue = histValues.getOldShowValue();
                //for flat history with children only the new values are shown but for date change
                //the old value will also be included in a parenthesis
                if (withChildren && (SystemFields.INTEGER_STARTDATE.equals(fieldID)
                        || SystemFields.INTEGER_ENDDATE.equals(fieldID))) {
                    if (oldValue != null && !"".equals(oldValue.trim())) {
                        newValue = newValue + " (" + oldValue + ")";
                    }
                }
                boolean isLongField = isLong(fieldID);
                if (isLongField) {
                    //if(!SystemFields.INTEGER_COMMENT.equals(fieldID)){
                    String diff = null;
                    try {
                        String newValueFormatted = ItemDetailBL.formatDescription(newValue, locale);
                        String oldValueFormatted = ItemDetailBL.formatDescription(oldValue, locale);
                        diff = HTMLDiff.makeDiff(newValueFormatted, oldValueFormatted, locale);
                        diff = ItemDetailBL.formatDescription(diff, locale);
                    } catch (Exception ex) {
                        LOGGER.error(" can't create diff: " + ex.getMessage());
                        if (LOGGER.isDebugEnabled()) {
                            LOGGER.error(ExceptionUtils.getStackTrace(ex));
                        }
                    }
                    historyEntry.setDiff(diff);
                    //}
                }
                String changedText = null;
                if (type == HistoryBean.HISTORY_TYPE.ATTACHMENT) {
                    changedText = "<strong>" + histValues.getFieldName() + "</strong> ";
                    if (newValue != null && newValue.length() > 0) {
                        changedText += "<span class=\"histNewValue\">" + histValues.getNewShowValue()
                                + "</span>";
                    } else {
                        changedText += "<span class=\"histOldValue\">" + histValues.getOldShowValue()
                                + "</span>";
                    }
                } else {
                    String tkey = "item.history.changeTextSimpleField";
                    if (isLongField) {
                        tkey = "item.history.changeTextLongField";
                    }
                    if (newValue != null && newValue.length() > 0 && oldValue != null
                            && oldValue.length() > 0) {
                        changedText = LocalizeUtil
                                .getParametrizedString(
                                        tkey, new Object[] { histValues.getFieldName(),
                                                histValues.getOldShowValue(), histValues.getNewShowValue() },
                                        locale);
                    } else if (newValue != null && newValue.length() > 0) {
                        tkey = tkey + ".oldValueNull";
                        changedText = LocalizeUtil.getParametrizedString(tkey,
                                new Object[] { histValues.getFieldName(), histValues.getNewShowValue() },
                                locale);
                    } else {
                        tkey = tkey + ".newValueNull";
                        changedText = LocalizeUtil.getParametrizedString(tkey,
                                new Object[] { histValues.getFieldName(), histValues.getOldShowValue() },
                                locale);
                    }
                }
                historyEntry.setNewValue(newValue);
                historyEntry.setChangedText(changedText);
                historyEntry.setOldValue(oldValue);
                if (longEntriesSeparate && fieldID.intValue() == TFieldChangeBean.COMPOUND_HISTORY_FIELD) {
                    historyEntry.setFieldLabel(null);
                }
                boolean fieldIsLong = isLong(fieldID);
                if (fieldIsLong) {
                    historyEntry
                            .setNewValue(ItemDetailBL.formatDescription(historyEntry.getNewValue(), locale));
                }
                if (longEntriesSeparate && fieldIsLong) {
                    //TODO whether the not pseudo field is of type long 
                    historyLongEntries.add(historyEntry);
                } else {
                    //long fields and short fields are treated same: format the long field content already here (not in the jsp) 
                    historyEntries.add(historyEntry);
                }
            }
            if (histValues != null) {
                FlatHistoryBean flatHistoryBean = new FlatHistoryBean();
                flatHistoryBean.setChangedByName(histValues.getChangedByName());
                flatHistoryBean.setPersonID(histValues.getChangedByID());
                flatHistoryBean.setLastEdit(histValues.getLastEdit());
                flatHistoryBean.setHistoryEntries(historyEntries);
                flatHistoryBean.setHistoryLongEntries(historyLongEntries);
                flatHistoryBean.setType(type);
                flatHistoryBean.setIconName(getIconByType(type));
                addWorkItemToFlatHistoryBean(flatHistoryBean, workItemBeansMap, workItemID,
                        FlatHistoryBean.RENDER_TYPE.HISTORY_VALUES);
                historyList.add(flatHistoryBean);
            }
        }
    }
    if (historyList.size() > 0) {
        // sort all history beans chronologically
        Collections.sort(historyList, new HistoryComparator());
    }
    return historyList;
}

From source file:org.solmix.datax.mybatis.MybatisDataService.java

protected DSResponse executeInConcurrency(SortedMap<String, DataSource> dsMap, DSRequest req,
        final OperationType type) {
    DSResponse res = new DSResponseImpl(req, Status.STATUS_SUCCESS);
    List<RoutingRequest> requests = new ArrayList<RoutingRequest>();
    boolean usedTransaction = false;
    if (req.getDSCall() != null && this.canJoinTransaction(req)) {
        usedTransaction = true;/*from   w  w w . j a  va  2s .  c om*/
    }
    for (String key : dsMap.keySet()) {
        DataSourceInfo dsi = dataSourceService.getDataSourceInfo(key);
        ExecutorService es = dsi.getExecutorService();
        synchronized (es) {
            if (es == null) {
                es = createExecutorServiceIfNS(dsi);
            }
        }
        RoutingRequest rrequest = new RoutingRequest();
        rrequest.setExecutor(es);
        rrequest.setRequest(req);
        rrequest.setDataSource(dsMap.get(key));
        requests.add(rrequest);
    }

    if (CollectionUtils.isEmpty(requests)) {
        return res;
    }
    List<SqlSessionDepository> des = makeupSessionInConcurrency(requests, usedTransaction);
    // concurrent
    final CountDownLatch latch = new CountDownLatch(des.size());
    List<Future<Object>> futures = new ArrayList<Future<Object>>();
    try {
        for (SqlSessionDepository routing : des) {
            RoutingRequest request = routing.getRequest();
            final DSRequest actualReq = request.getRequest();
            final SqlSession session = routing.getSqlSession();
            futures.add(request.getExecutor().submit(new Callable<Object>() {

                @Override
                public Object call() throws Exception {
                    try {
                        return executeWithSqlSession(session, actualReq, type);
                    } finally {
                        latch.countDown();
                    }
                }
            }));
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            throw new ConcurrencyRequestException(
                    "interrupted when processing data access request in concurrency", e);
        }
    } finally {
        if (!usedTransaction) {
            for (SqlSessionDepository routing : des) {
                SqlSession session = routing.getSqlSession();
                session.close();
            }
        }
    }
    prepareResult(futures, type, req, res);

    return res;
}