Example usage for java.util LinkedHashMap keySet

List of usage examples for java.util LinkedHashMap keySet

Introduction

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

Prototype

public Set<K> keySet() 

Source Link

Document

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

Usage

From source file:au.org.ala.delta.intkey.Intkey.java

/**
 * Update the view of available characters
 *//*  www  .java2  s.  com*/
private void updateAvailableCharacters() {

    IntkeyCharacterOrder charOrder = _context.getCharacterOrder();

    Item taxonToSeparate = null;
    String formattedTaxonToSeparateName = null;

    switch (charOrder) {
    case SEPARATE:
        taxonToSeparate = _context.getDataset().getItem(_context.getTaxonToSeparate());
        formattedTaxonToSeparateName = _taxonformatter.formatItemDescription(taxonToSeparate);
        if (!_context.getAvailableTaxa().contains(taxonToSeparate)) {
            _listAvailableCharacters.setModel(new DefaultListModel());
            _lblNumAvailableCharacters
                    .setText(MessageFormat.format(separateCharactersCaption, formattedTaxonToSeparateName, 0));
            break;
        }

        // If taxon to separate has not been eliminated, drop through and
        // display the best characters for taxon separation
    case BEST:
        LinkedHashMap<Character, Double> bestCharactersMap = _context.getBestOrSeparateCharacters();
        if (bestCharactersMap != null) {
            if (charOrder == IntkeyCharacterOrder.BEST) {
                _lblNumAvailableCharacters.setText(
                        MessageFormat.format(bestCharactersCaption, bestCharactersMap.keySet().size()));
            } else {
                _lblNumAvailableCharacters.setText(MessageFormat.format(separateCharactersCaption,
                        formattedTaxonToSeparateName, bestCharactersMap.keySet().size()));
            }
            if (bestCharactersMap.isEmpty()) {
                handleNoAvailableCharacters();
                return;
            } else {
                _availableCharacterListModel = new DefaultListModel();
                for (Character ch : bestCharactersMap.keySet()) {
                    _availableCharacterListModel.addElement(ch);
                }
                _availableCharacterListModel.copyInto(bestCharactersMap.keySet().toArray());

                // Only display character separating powers if in advanced
                // mode.
                if (_advancedMode) {
                    _availableCharactersListCellRenderer = new BestCharacterCellRenderer(bestCharactersMap,
                            _context.displayNumbering());
                } else {
                    _availableCharactersListCellRenderer = new CharacterCellRenderer(
                            _context.displayNumbering());
                }
                _listAvailableCharacters.setCellRenderer(_availableCharactersListCellRenderer);
                _listAvailableCharacters.setModel(_availableCharacterListModel);
            }
        } else {
            _availableCharacterListModel = null;

            // The best characters list is not cached and needs to be
            // calculated. This is a
            // long-running operation so use a
            // SwingWorker to do it on a different thread, and update
            // the
            // available characters list when
            // it is complete.
            GetBestCharactersWorker worker = new GetBestCharactersWorker(_context);
            worker.execute();

            // Show the busy glass pane with a message if worker has not
            // completed within
            // 250 milliseconds. This avoids "flickering" of the
            // glasspane
            // when it takes a
            // very short time to calculate the best characters.
            try {
                Thread.sleep(250);
                if (!worker.isDone()) {
                    displayBusyMessage(calculatingBestCaption);
                }
            } catch (InterruptedException ex) {
                // do nothing
            }

            return;
        }

        break;
    case NATURAL:
        int lastSelectedIndex = _listAvailableCharacters.getSelectedIndex();

        List<Character> availableCharacters = new ArrayList<Character>(_context.getAvailableCharacters());
        _lblNumAvailableCharacters
                .setText(MessageFormat.format(availableCharactersCaption, availableCharacters.size()));
        if (availableCharacters.size() == 0) {
            handleNoAvailableCharacters();
            return;
        } else {
            _availableCharacterListModel = new DefaultListModel();
            for (Character ch : availableCharacters) {
                _availableCharacterListModel.addElement(ch);
            }
            _availableCharactersListCellRenderer = new CharacterCellRenderer(_context.displayNumbering());
            _listAvailableCharacters.setCellRenderer(_availableCharactersListCellRenderer);
            _listAvailableCharacters.setModel(_availableCharacterListModel);

            // Select the same index that was previously selected. This will
            // have the effect of selecting the character after the
            // previously used character.
            _listAvailableCharacters.setSelectedIndex(lastSelectedIndex);
        }
        break;
    default:
        throw new RuntimeException("Unrecognized character order");
    }

    // The viewport of the available characters scroll pane may be
    // displaying a
    // message due to an investigation finishing, or no characters being
    // available
    // previously. Ensure that the available characters list is now
    // displayed again.
    if (!_sclPaneAvailableCharacters.getViewport().getView().equals(_listAvailableCharacters)) {
        _sclPaneAvailableCharacters.setViewportView(_listAvailableCharacters);
        _sclPaneAvailableCharacters.revalidate();
    }
}

From source file:edu.jhuapl.openessence.controller.ReportController.java

private GraphObject createGraph(OeDataSource dataSource, final String userPrincipalName,
        final Collection<Record> records, final Dimension dimension, final Dimension filter,
        final Dimension accumulation, DefaultGraphData data, ChartModel chart, List<Filter> filters) {

    String filterId = (filter == null) ? dimension.getId() : filter.getId();
    Map<String, String> possibleKeyValueMap = null;
    if (dimension.getPossibleValuesConfiguration() != null
            && dimension.getPossibleValuesConfiguration().getData() != null) {
        List<List<Object>> dataMap = dimension.getPossibleValuesConfiguration().getData();
        possibleKeyValueMap = new HashMap<String, String>();
        for (int i = 0; i < dataMap.size(); i++) {
            String dispVal = dataMap.get(i).size() == 2 ? dataMap.get(i).get(1).toString()
                    : dataMap.get(i).get(0).toString();
            possibleKeyValueMap.put(dataMap.get(i).get(0).toString(), dispVal);
        }//from www  . j ava  2 s  .c  om
    }

    GraphDataSerializeToDiskHandler hndl = new GraphDataSerializeToDiskHandler(graphDir);
    GraphObject graph = null;

    Color[] colorsFromHex = null;
    //only set an array if they provided one
    if (!ArrayUtils.isEmpty(chart.getGraphBaseColors())) {
        colorsFromHex = ControllerUtils.getColorsFromHex(Color.BLUE, chart.getGraphBaseColors());
        //TODO when we limit the series these colors need augmented.  Create a map of id = graphbasecolor[index] first, then use that map to create a
        //new graph base color array that combines the parameter list with the default list...
        data.setGraphBaseColors(colorsFromHex);
    }

    GraphController gc = getGraphController(null, hndl, userPrincipalName);

    List<Record> recs = new ArrayList<Record>(records);

    String otherLabel = messageSource.getDataSourceMessage("graph.category.other", dataSource);

    LinkedHashMap<String, ChartData> recordMap = getRecordMap(recs, accumulation.getId(), dimension.getId(),
            filterId);
    //perform series limit
    recordMap = ControllerUtils.getSortedAndLimitedChartDataMap(recordMap, chart.getCategoryLimit(),
            otherLabel);

    //if there is no data (all zeros for a pie chart) the chart will not display anything
    if (!ControllerUtils.isCollectionValued(getCountsForChart(recordMap)) && !chart.isShowNoDataGraph()) {
        //this will hide the title and message if there is no data
        data.setGraphTitle("");
        data.setNoDataMessage("");
    }

    // Create urls for each slice/bar
    DataSeriesSource dss = null;
    StringBuilder jsCall = new StringBuilder();
    jsCall.append("javascript:OE.report.datasource.showDetails({");

    if (dataSource instanceof DataSeriesSource) {
        dss = (DataSeriesSource) dataSource;

        Collection<Dimension> dims = new ArrayList<Dimension>(dss.getResultDimensions());
        Collection<String> dimIds = ControllerUtils.getDimensionIdsFromCollection(dims);

        Collection<Dimension> accums = new ArrayList<Dimension>(dss.getAccumulations());

        for (Dimension d : accums) {
            if (dimIds.contains(d.getId()) && d.getId().equals(accumulation.getId())) {

            } else {
                dimIds.remove(d.getId());
            }
        }

        jsCall.append("dsId:'").append(dss.getClass().getName()).append("'");
        //specify results
        jsCall.append(",results:[").append(StringUtils.collectionToDelimitedString(dimIds, ",", "'", "'"))
                .append(']');
        //specify accumId
        jsCall.append(",accumId:'").append(accumulation.getId()).append("'");

        addJavaScriptFilters(jsCall, filters, dimension.getId());
    }

    int rSize = recordMap.size();
    int aSize = 1;
    String[] lbl = new String[rSize];
    String[][] txtb = new String[1][rSize];
    double[][] bardat = new double[aSize][rSize];
    String[][] txtp = new String[rSize][1];
    double[][] piedat = new double[rSize][aSize];
    String[][] urlsP = new String[rSize][1];
    String[][] urlsB = new String[1][rSize];
    int i = 0;
    double totalCount = 0;
    DecimalFormat df = new DecimalFormat("#.##");

    for (String key : recordMap.keySet()) {
        if (recordMap.get(key) != null && recordMap.get(key).getCount() != null
                && !recordMap.get(key).getCount().isNaN()) {
            totalCount += recordMap.get(key).getCount();
        }
    }

    for (String key : recordMap.keySet()) {
        Double dubVal = recordMap.get(key).getCount();
        String strPercentVal = df.format(100 * dubVal / totalCount);
        lbl[i] = recordMap.get(key).getName();
        //create bar data set
        bardat[0][i] = dubVal;
        txtb[0][i] = lbl[i] + " - " + Double.toString(dubVal) + " (" + strPercentVal + "%)";
        if (lbl[i].length() > DEFAULT_LABEL_LENGTH) {
            lbl[i] = lbl[i].substring(0, DEFAULT_LABEL_LENGTH - 3) + "...";
        }
        //create pie data set
        piedat[i][0] = dubVal;
        txtp[i][0] = lbl[i] + " - " + Double.toString(dubVal) + " (" + strPercentVal + "%)";
        if (lbl[i].length() > DEFAULT_LABEL_LENGTH) {
            lbl[i] = lbl[i].substring(0, DEFAULT_LABEL_LENGTH - 3) + "...";
        }
        //TODO all "Others" to return details of all results except for those in recordMap.keyset
        //We need a "Not" filter
        if (!otherLabel.equals(key)) {
            if (dataSource instanceof DataSeriesSource) {
                if (dimension.getId().equals(filterId) && possibleKeyValueMap != null) {
                    if (possibleKeyValueMap.containsKey(key)) {
                        urlsP[i][0] = jsCall.toString() + "," + filterId + ":'" + key + "'" + "});";
                        urlsB[0][i] = jsCall.toString() + "," + filterId + ":'" + key + "'" + "});";
                    } else {
                        urlsP[i][0] = jsCall.toString() + "});";
                        urlsB[0][i] = jsCall.toString() + "});";
                    }
                } else {
                    if (key == null || key.equals("")
                            || key.equals(messageSource.getMessage("graph.dimension.null", "Empty Value"))) {
                        // TODO: This is when we have an ID field also marked as isResult:true and the value is null
                        // We can not provide url param filterId:null as field can be numeric and we get a java.lang.NumberFormatException...
                        urlsP[i][0] = jsCall.toString() + "});";
                        urlsB[0][i] = jsCall.toString() + "});";
                    } else {
                        urlsP[i][0] = jsCall.toString() + "," + filterId + ":'" + key + "'" + "});";
                        urlsB[0][i] = jsCall.toString() + "," + filterId + ":'" + key + "'" + "});";
                    }
                }
            }
        }

        i++;
    }

    if (BAR.equalsIgnoreCase(chart.getType())) {
        data.setCounts(bardat);
        data.setXLabels(lbl);
        data.setMaxLabeledCategoryTicks(rSize);
        data.setAltTexts(txtb);
        if (jsCall.length() > 0) {
            data.setLineSetURLs(urlsB);
        }
        //TODO add encoding?
        graph = gc.createBarGraph(data, false, true);
    } else if (PIE.equalsIgnoreCase(chart.getType())) {
        data.setCounts(piedat);
        data.setLineSetLabels(lbl);
        data.setAltTexts(txtp);
        if (jsCall.length() > 0) {
            data.setLineSetURLs(urlsP);
        }
        graph = gc.createPieGraph(data, Encoding.PNG_WITH_TRANSPARENCY);
    }
    return graph;
}

From source file:de.ingrid.importer.udk.strategy.v1.IDCStrategy1_0_4.java

protected void updateSysGui() throws Exception {
    if (log.isInfoEnabled()) {
        log.info("Updating sys_gui...");
    }/*from   w  w w.java2  s .c o m*/

    if (log.isInfoEnabled()) {
        log.info("Updating sys_gui entries (including Clean Up !)...");
    }

    // clean up, to guarantee no old values !
    sqlStr = "DELETE FROM sys_gui";
    jdbc.executeUpdate(sqlStr);

    LinkedHashMap<String, Integer> initialSysGuis = new LinkedHashMap<String, Integer>();
    Integer initialBehaviour = -1;
    Integer mandatory = 1;

    initialSysGuis.put("1130", initialBehaviour);
    initialSysGuis.put("1140", initialBehaviour);
    initialSysGuis.put("1220", initialBehaviour);
    initialSysGuis.put("1230", initialBehaviour);
    initialSysGuis.put("1240", initialBehaviour);
    initialSysGuis.put("1250", initialBehaviour);
    initialSysGuis.put("1310", initialBehaviour);
    initialSysGuis.put("1320", initialBehaviour);
    initialSysGuis.put("1350", initialBehaviour);
    initialSysGuis.put("1409", mandatory);
    initialSysGuis.put("1410", mandatory);
    initialSysGuis.put("3100", initialBehaviour);
    initialSysGuis.put("3110", initialBehaviour);
    initialSysGuis.put("3120", initialBehaviour);
    initialSysGuis.put("3200", initialBehaviour);
    initialSysGuis.put("3210", initialBehaviour);
    initialSysGuis.put("3230", initialBehaviour);
    initialSysGuis.put("3240", initialBehaviour);
    initialSysGuis.put("3250", initialBehaviour);
    initialSysGuis.put("3300", initialBehaviour);
    initialSysGuis.put("3310", initialBehaviour);
    initialSysGuis.put("3320", initialBehaviour);
    initialSysGuis.put("3330", initialBehaviour);
    initialSysGuis.put("3340", initialBehaviour);
    initialSysGuis.put("3345", initialBehaviour);
    initialSysGuis.put("3350", initialBehaviour);
    initialSysGuis.put("3355", initialBehaviour);
    initialSysGuis.put("3360", initialBehaviour);
    initialSysGuis.put("3365", initialBehaviour);
    initialSysGuis.put("3370", initialBehaviour);
    initialSysGuis.put("3375", initialBehaviour);
    initialSysGuis.put("3380", initialBehaviour);
    initialSysGuis.put("3385", initialBehaviour);
    initialSysGuis.put("3400", initialBehaviour);
    initialSysGuis.put("3410", initialBehaviour);
    initialSysGuis.put("3420", initialBehaviour);
    initialSysGuis.put("3500", initialBehaviour);
    initialSysGuis.put("3515", initialBehaviour);
    initialSysGuis.put("3520", initialBehaviour);
    initialSysGuis.put("3530", initialBehaviour);
    initialSysGuis.put("3535", initialBehaviour);
    initialSysGuis.put("3555", initialBehaviour);
    initialSysGuis.put("3565", initialBehaviour);
    initialSysGuis.put("3570", initialBehaviour);
    initialSysGuis.put("4400", initialBehaviour);
    initialSysGuis.put("4405", initialBehaviour);
    initialSysGuis.put("4410", initialBehaviour);
    initialSysGuis.put("4415", initialBehaviour);
    initialSysGuis.put("4420", initialBehaviour);
    initialSysGuis.put("4425", initialBehaviour);
    initialSysGuis.put("4435", initialBehaviour);
    initialSysGuis.put("4440", initialBehaviour);
    initialSysGuis.put("4510", mandatory);
    initialSysGuis.put("5000", initialBehaviour);
    initialSysGuis.put("5020", initialBehaviour);
    initialSysGuis.put("5021", initialBehaviour);
    initialSysGuis.put("5022", initialBehaviour);
    initialSysGuis.put("5040", initialBehaviour);
    initialSysGuis.put("5052", initialBehaviour);
    initialSysGuis.put("5062", initialBehaviour);
    initialSysGuis.put("5063", initialBehaviour);
    initialSysGuis.put("5069", initialBehaviour);
    initialSysGuis.put("5070", initialBehaviour);
    initialSysGuis.put("N001", initialBehaviour);
    initialSysGuis.put("N002", initialBehaviour);
    initialSysGuis.put("N003", initialBehaviour);
    initialSysGuis.put("N004", initialBehaviour);
    initialSysGuis.put("N005", initialBehaviour);
    initialSysGuis.put("N007", initialBehaviour);
    initialSysGuis.put("N009", initialBehaviour);
    initialSysGuis.put("N010", initialBehaviour);
    initialSysGuis.put("N011", initialBehaviour);
    initialSysGuis.put("N012", initialBehaviour);
    initialSysGuis.put("N013", initialBehaviour);
    initialSysGuis.put("N014", initialBehaviour);
    initialSysGuis.put("N015", initialBehaviour);
    initialSysGuis.put("N016", initialBehaviour);
    initialSysGuis.put("N017", initialBehaviour);
    initialSysGuis.put("N018", initialBehaviour);
    initialSysGuis.put("N019", mandatory);
    initialSysGuis.put("N020", initialBehaviour);
    initialSysGuis.put("N023", initialBehaviour);

    Iterator<String> itr = initialSysGuis.keySet().iterator();
    while (itr.hasNext()) {
        String key = itr.next();
        jdbc.executeUpdate("INSERT INTO sys_gui (id, gui_id, behaviour) VALUES (" + getNextId() + ", '" + key
                + "', " + initialSysGuis.get(key) + ")");
    }

    if (log.isInfoEnabled()) {
        log.info("Updating sys_gui... done");
    }
}

From source file:org.apache.axis2.context.MessageContext.java

/**
 * Flatten the phase list into a list of just unique handler instances
 *
 * @param list the list of handlers/*from w  w w  .jav a  2 s .  c o m*/
 * @param map  users should pass null as this is just a holder for the recursion
 * @return a list of unigue object instances
 */
private ArrayList<Handler> flattenPhaseListToHandlers(ArrayList<Handler> list,
        LinkedHashMap<String, Handler> map) {

    if (map == null) {
        map = new LinkedHashMap<String, Handler>();
    }

    Iterator<Handler> it = list.iterator();
    while (it.hasNext()) {
        Handler handler = (Handler) it.next();

        String key = null;
        if (handler != null) {
            key = handler.getClass().getName() + "@" + handler.hashCode();
        }

        if (handler instanceof Phase) {
            // add its handlers to the list
            flattenHandlerList(((Phase) handler).getHandlers(), map);
        } else {
            // if the same object is already in the list,
            // then it won't be in the list multiple times
            map.put(key, handler);
        }
    }

    if (DEBUG_ENABLED && log.isTraceEnabled()) {
        Iterator<String> it2 = map.keySet().iterator();
        while (it2.hasNext()) {
            Object key = it2.next();
            Handler value = (Handler) map.get(key);
            String name = value.getName();
            log.trace(getLogIDString() + ":flattenPhaseListToHandlers():  key [" + key + "]    handler name ["
                    + name + "]");
        }
    }

    return new ArrayList<Handler>(map.values());
}

From source file:org.exoplatform.calendar.service.impl.JCRDataStorage.java

/**
 * {@inheritDoc}/* ww  w . j  a  va 2  s . c  o m*/
 */
@Deprecated
public int generateRss(String username, LinkedHashMap<String, Calendar> calendars, RssData rssData,
        CalendarImportExport importExport) throws Exception {
    Node rssHomeNode = getRssHome(username);
    try {
        SyndFeed feed = new SyndFeedImpl();
        feed.setFeedType(rssData.getVersion());
        feed.setTitle(rssData.getTitle());
        feed.setLink(rssData.getLink());
        feed.setDescription(rssData.getDescription());
        List<SyndEntry> entries = new ArrayList<SyndEntry>();
        SyndEntry entry;
        SyndContent description;

        // String portalName = PortalContainer.getCurrentPortalContainerName();
        for (String calendarMap : calendars.keySet()) {
            String calendarId = calendarMap.split(Utils.COLON)[1];
            String type = calendarMap.split(Utils.COLON)[0];
            OutputStream out = importExport.exportCalendar(username, Arrays.asList(new String[] { calendarId }),
                    type, -1);
            if (out != null) {
                Calendar exoCal = calendars.get(calendarMap);
                entry = new SyndEntryImpl();
                entry.setTitle(exoCal.getName());

                entry.setLink(rssHomeNode.getPath() + Utils.SLASH + calendarId);
                entry.setAuthor(username);
                description = new SyndContentImpl();
                description.setType(Utils.MIMETYPE_TEXTPLAIN);
                description.setValue(exoCal.getDescription());
                entry.setDescription(description);
                entries.add(entry);
                entry.getEnclosures();
            }
        }
        if (!entries.isEmpty()) {
            feed.setEntries(entries);
            feed.setEncoding("UTF-8");
            SyndFeedOutput output = new SyndFeedOutput();
            String feedXML = output.outputString(feed);
            feedXML = StringUtils.replace(feedXML, "&amp;", "&");
            storeXML(feedXML, rssHomeNode, rssData);
            rssHomeNode.getSession().save();
        } else {
            log.info("No data to make rss!");
            return -1;
        }
    } catch (Exception e) {
        if (log.isDebugEnabled())
            log.debug(e);
        return -1;
    }
    return 1;
}

From source file:org.apache.hadoop.hive.ql.exec.DDLTask.java

/**
 * Rename a partition in a table/*  w w w . j a  va2 s. c  o  m*/
 *
 * @param db
 *          Database to rename the partition.
 * @param renamePartitionDesc
 *          rename old Partition to new one.
 * @return Returns 0 when execution succeeds and above 0 if it fails.
 * @throws HiveException
 */
private int renamePartition(Hive db, RenamePartitionDesc renamePartitionDesc) throws HiveException {
    String tableName = renamePartitionDesc.getTableName();
    LinkedHashMap<String, String> oldPartSpec = renamePartitionDesc.getOldPartSpec();

    if (!allowOperationInReplicationScope(db, tableName, oldPartSpec,
            renamePartitionDesc.getReplicationSpec())) {
        // no rename, the table is missing either due to drop/rename which follows the current rename.
        // or the existing table is newer than our update.
        LOG.debug("DDLTask: Rename Partition is skipped as table {} / partition {} is newer than update",
                tableName, FileUtils.makePartName(new ArrayList(oldPartSpec.keySet()),
                        new ArrayList(oldPartSpec.values())));
        return 0;
    }

    Table tbl = db.getTable(tableName);
    Partition oldPart = db.getPartition(tbl, oldPartSpec, false);
    if (oldPart == null) {
        String partName = FileUtils.makePartName(new ArrayList<String>(oldPartSpec.keySet()),
                new ArrayList<String>(oldPartSpec.values()));
        throw new HiveException("Rename partition: source partition [" + partName + "] does not exist.");
    }
    Partition part = db.getPartition(tbl, oldPartSpec, false);
    part.setValues(renamePartitionDesc.getNewPartSpec());
    db.renamePartition(tbl, oldPartSpec, part);
    Partition newPart = db.getPartition(tbl, renamePartitionDesc.getNewPartSpec(), false);
    work.getInputs().add(new ReadEntity(oldPart));
    // We've already obtained a lock on the table, don't lock the partition too
    addIfAbsentByName(new WriteEntity(newPart, WriteEntity.WriteType.DDL_NO_LOCK));
    return 0;
}

From source file:com.gtwm.pb.model.manageData.DataManagement.java

/**
 * Used by both the public saveRecord and globalEdit methods
 *///from   w  ww.j  a va  2 s  . c  o  m
private void saveRecord(HttpServletRequest request, TableInfo table,
        LinkedHashMap<BaseField, BaseValue> dataToSave, boolean newRecord, Set<Integer> rowIds,
        SessionDataInfo sessionData, List<FileItem> multipartItems)
        throws InputRecordException, ObjectNotFoundException, SQLException, CantDoThatException,
        CodingErrorException, DisallowedException, MissingParametersException {
    if ((dataToSave.size() == 0) && (!newRecord)) {
        // Note: this does actually happen quite a lot, from two particular
        // users, therefore I've commented out the log warning.
        // Haven't tracked down the cause but it doesn't seem to be creating
        // a problem.
        // logger.warn("Call to saveRecord with no data to save. User = "
        // + request.getRemoteUser() + ", table = " + table + ", rowIds = "
        // + rowIds);
        return;
    }
    this.setHiddenFieldValues(request, table, dataToSave, newRecord);
    boolean globalEdit = false;
    int rowId = -1;
    if (rowIds.size() > 1) {
        globalEdit = true;
    } else if (rowIds.size() == 1) {
        rowId = (new LinkedList<Integer>(rowIds)).getFirst();
    } else {
        throw new ObjectNotFoundException("Row ID list " + rowIds + " is invalid");
    }
    StringBuilder SQLCodeBuilder = new StringBuilder();
    // Generate CSV of fields and placeholders to use in update/insert SQL
    // string
    StringBuilder fieldsCsvBuilder = new StringBuilder();
    StringBuilder fieldsAndPlaceholdersCsvBuilder = new StringBuilder();
    StringBuilder valuePlaceholdersCsvBuilder = new StringBuilder();
    for (BaseField field : dataToSave.keySet()) {
        fieldsCsvBuilder.append(field.getInternalFieldName());
        fieldsCsvBuilder.append(", ");
        valuePlaceholdersCsvBuilder.append("?, ");
        fieldsAndPlaceholdersCsvBuilder.append(field.getInternalFieldName());
        fieldsAndPlaceholdersCsvBuilder.append("=?, ");
    }
    // Used if doing an INSERT
    String fieldsCsv = fieldsCsvBuilder.toString();
    String valuePlaceholdersCsv = valuePlaceholdersCsvBuilder.toString();
    // Used if doing an UPDATE
    String fieldsAndPlaceholdersCsv = fieldsAndPlaceholdersCsvBuilder.toString();
    if (!fieldsCsv.equals("")) {
        fieldsCsv = fieldsCsv.substring(0, fieldsCsv.length() - 2);
        valuePlaceholdersCsv = valuePlaceholdersCsv.substring(0, valuePlaceholdersCsv.length() - 2);
        fieldsAndPlaceholdersCsv = fieldsAndPlaceholdersCsv.substring(0, fieldsAndPlaceholdersCsv.length() - 2);
    }
    if (newRecord) {
        SQLCodeBuilder.append("INSERT INTO " + table.getInternalTableName());
        if (fieldsCsv.equals("")) {
            SQLCodeBuilder.append(" VALUES(default)");
        } else {
            SQLCodeBuilder.append("(" + fieldsCsv + ") VALUES (" + valuePlaceholdersCsv + ")");
        }
    } else {
        SQLCodeBuilder.append("UPDATE " + table.getInternalTableName() + " SET " + fieldsAndPlaceholdersCsv);
        if (globalEdit) {
            // add filter for various row ids
            SQLCodeBuilder.append(" WHERE " + table.getPrimaryKey().getInternalFieldName() + " in (?");
            for (int i = 1; i < rowIds.size(); i++) {
                SQLCodeBuilder.append(",?");
            }
            SQLCodeBuilder.append(")");
        } else {
            // add filter for single row id
            SQLCodeBuilder.append(" WHERE " + table.getPrimaryKey().getInternalFieldName() + "=?");
        }
    }
    Connection conn = null;
    int fieldNumber = 0;
    // Will be set if we're inserting a record
    int newRowId = -1;
    TableDataInfo tableData = new TableData(table);
    try {
        conn = this.dataSource.getConnection();
        conn.setAutoCommit(false);
        PreparedStatement statement = conn.prepareStatement(SQLCodeBuilder.toString());
        for (BaseField field : dataToSave.keySet()) {
            // If an exception is raised, currentField will be the field
            // which caused it
            // currentField = field;
            fieldNumber++;
            BaseValue fieldValue = dataToSave.get(field);
            if (field instanceof FileField) {
                if (fieldValue.isNull() || fieldValue.toString().equals("")) {
                    throw new InputRecordException("No file specified for the upload", field);
                }
            }
            if (fieldValue.isNull()) {
                statement.setNull(fieldNumber, Types.NULL);
            } else {
                if (fieldValue instanceof TextValue) {
                    String textValue = ((TextValue) fieldValue).toXmlString();
                    statement.setString(fieldNumber, textValue);
                } else if (fieldValue instanceof IntegerValue) {
                    // if no related value, set relation field to null
                    if (field instanceof RelationField && (((IntegerValue) fieldValue).getValueInteger() == -1)
                            || (fieldValue.isNull())) {
                        statement.setNull(fieldNumber, Types.NULL);
                    } else {
                        statement.setInt(fieldNumber, ((IntegerValue) fieldValue).getValueInteger());
                    }
                } else if (fieldValue instanceof DurationValue) {
                    statement.setString(fieldNumber, ((DurationValue) fieldValue).getSqlFormatInterval());
                } else if (fieldValue instanceof DecimalValue) {
                    statement.setDouble(fieldNumber, ((DecimalValue) fieldValue).getValueFloat());
                } else if (fieldValue instanceof DateValue) {
                    if (((DateValue) fieldValue).getValueDate() != null) {
                        java.util.Date javaDateValue = ((DateValue) fieldValue).getValueDate().getTime();
                        java.sql.Timestamp sqlTimestampValue = new java.sql.Timestamp(javaDateValue.getTime());
                        statement.setTimestamp(fieldNumber, sqlTimestampValue);
                    } else {
                        statement.setTimestamp(fieldNumber, null);
                    }
                } else if (fieldValue instanceof CheckboxValue) {
                    statement.setBoolean(fieldNumber, ((CheckboxValue) fieldValue).getValueBoolean());
                } else if (fieldValue instanceof FileValue) {
                    statement.setString(fieldNumber, ((FileValue) fieldValue).toString());
                } else {
                    throw new CodingErrorException("Field value " + fieldValue + " is of unknown type "
                            + fieldValue.getClass().getSimpleName());
                }
            }
        }
        // We've finished setting individual fields, if an SQL error occurs
        // after here we won't know which
        // field caused it without looking for it by other means
        // currentField = null;
        if (!newRecord) {
            if (globalEdit) {
                // Fill in the 'WHERE [row id field] in (?,..,?)' for use in
                // the UPDATE statement
                for (Integer aRowId : rowIds) {
                    if (tableData.isRecordLocked(conn, sessionData, aRowId)) {
                        throw new CantDoThatException(
                                "Record " + aRowId + " from table " + table + " is locked to prevent editing");
                    }
                    statement.setInt(++fieldNumber, aRowId);
                }
            } else {
                // Fill in the 'WHERE [row id field]=?' for use in the
                // UPDATE statement
                if (tableData.isRecordLocked(conn, sessionData, rowId)) {
                    throw new CantDoThatException(
                            "Record " + rowId + " from table " + table + " is locked to prevent editing");
                }
                statement.setInt(fieldNumber + 1, rowId);
            }
        }
        int numRowsAffected = statement.executeUpdate();
        statement.close();
        if ((numRowsAffected != 1) && (!globalEdit)) {
            conn.rollback();
            if (numRowsAffected > 0) {
                throw new ObjectNotFoundException(String.valueOf(numRowsAffected)
                        + " records would be altered during a single record save");
            } else {
                throw new ObjectNotFoundException(
                        "The current record can't be found to edit - perhaps someone else has deleted it");
            }
        }
        if (newRecord) {
            // Find the newly inserted Row ID
            // postgres-specific code, not database independent
            String SQLCode = "SELECT currval('" + table.getInternalTableName() + "_"
                    + table.getPrimaryKey().getInternalFieldName() + "_seq')";
            statement = conn.prepareStatement(SQLCode);
            ResultSet results = statement.executeQuery();
            if (results.next()) {
                newRowId = results.getInt(1);
            } else {
                results.close();
                statement.close();
                throw new SQLException(
                        "Row ID not found for the newly inserted record. '" + SQLCodeBuilder + "' didn't work");
            }
            results.close();
            statement.close();
        }
        conn.commit();
    } catch (SQLException sqlex) {
        // Find out which field caused the error by looking for internal
        // field names in the error message
        String errorMessage = sqlex.getMessage();
        for (BaseField possibleCauseField : dataToSave.keySet()) {
            if (errorMessage.contains(possibleCauseField.getInternalFieldName())) {
                if (errorMessage.contains("check constraint")) {
                    errorMessage = "The value " + dataToSave.get(possibleCauseField)
                            + " falls outside the allowed range";
                } else if (errorMessage.contains("not-null constraint")) {
                    errorMessage = "No value entered";
                } else if (errorMessage.contains("unique constraint")) {
                    errorMessage = "Value " + dataToSave.get(possibleCauseField)
                            + " is already in the database and cannot be entered again";
                } else if (errorMessage.contains("foreign key constraint")
                        && possibleCauseField instanceof RelationField) {
                    errorMessage = "Please select a valid "
                            + ((RelationField) possibleCauseField).getRelatedTable() + " record first";
                } else {
                    errorMessage = "Value " + dataToSave.get(possibleCauseField) + " not allowed ("
                            + Helpers.replaceInternalNames(errorMessage, table.getDefaultReport()) + ")";
                }
                throw new InputRecordException(errorMessage, possibleCauseField, sqlex);
            }
        }
        // Not able to find field
        errorMessage = Helpers.replaceInternalNames(errorMessage, table.getDefaultReport());
        throw new InputRecordException(errorMessage, null, sqlex);
    } finally {
        if (conn != null) {
            conn.close();
        }
    }
    // If any fields were files to upload, do the actual uploads.
    // Do this after the commit in case the uploads take a long time and
    // time out the SQL connection.
    for (BaseField field : dataToSave.keySet()) {
        if (field instanceof FileField) {
            try {
                if (newRecord) {
                    this.uploadFile(request, (FileField) field, (FileValue) dataToSave.get(field), newRowId,
                            multipartItems);
                } else {
                    this.uploadFile(request, (FileField) field, (FileValue) dataToSave.get(field), rowId,
                            multipartItems);
                }
            } catch (CantDoThatException cdtex) {
                throw new InputRecordException("Error uploading file: " + cdtex.getMessage(), field, cdtex);
            } catch (FileUploadException fuex) {
                throw new InputRecordException("Error uploading file: " + fuex.getMessage(), field, fuex);
            }
        }
    }
    if (newRecord) {
        sessionData.setRowId(table, newRowId);
    }
    this.logLastDataChangeTime(request);
    logLastTableDataChangeTime(table);
    UsageLogger usageLogger = new UsageLogger(this.dataSource);
    AppUserInfo user = null;
    if (request.getRemoteUser() == null) {
        user = ServletUtilMethods.getPublicUserForRequest(request, this.authManager.getAuthenticator());
    } else {
        user = this.authManager.getUserByUserName(request, request.getRemoteUser());
    }
    // Send websocket notification
    // UsageLogger.sendNotification(user, table, sessionData.getReport(),
    // rowId, "edit", "Record saved: " + dataToSave);
    // Log everything apart from hidden (auto set) fields
    Map<BaseField, BaseValue> dataToLog = new LinkedHashMap<BaseField, BaseValue>();
    for (Map.Entry<BaseField, BaseValue> entrySet : dataToSave.entrySet()) {
        BaseField field = entrySet.getKey();
        if (!field.getHidden()) {
            BaseValue value = entrySet.getValue();
            dataToLog.put(field, value);
        }
    }
    if (newRecord) {
        usageLogger.logDataChange(user, table, null, AppAction.SAVE_NEW_RECORD, newRowId, dataToLog.toString());
    } else if (globalEdit) {
        // TODO: need better logging of global edits
        usageLogger.logDataChange(user, table, null, AppAction.GLOBAL_EDIT, rowId, dataToLog.toString());
    } else {
        BaseField fieldUpdated = null;
        Set<BaseField> fieldSet = new TreeSet<BaseField>();
        for (BaseField field : dataToSave.keySet()) {
            if (!field.getHidden()) {
                fieldSet.add(field);
            }
        }
        if (fieldSet.size() == 1) {
            fieldUpdated = new LinkedList<BaseField>(fieldSet).getFirst();
        }
        usageLogger.logDataChange(user, table, fieldUpdated, AppAction.UPDATE_RECORD, rowId,
                dataToLog.toString());
    }
    UsageLogger.startLoggingThread(usageLogger);
}

From source file:org.exoplatform.calendar.service.impl.JCRDataStorage.java

/**
 * {@inheritDoc}/* ww  w .  ja va  2 s.com*/
 */
@Deprecated
public int generateCalDav(String username, LinkedHashMap<String, Calendar> calendars, RssData rssData,
        CalendarImportExport importExport) throws Exception {
    Node rssHomeNode = getRssHome(username);
    Node iCalHome = null;
    try {
        iCalHome = rssHomeNode.getNode(Utils.CALDAV_NODE);
    } catch (Exception e) {
        iCalHome = rssHomeNode.addNode(Utils.CALDAV_NODE, Utils.NT_UNSTRUCTURED);
    }
    try {
        SyndFeed feed = new SyndFeedImpl();
        feed.setFeedType(rssData.getVersion());
        feed.setTitle(rssData.getTitle());
        feed.setLink(rssData.getLink());
        feed.setDescription(rssData.getDescription());
        List<SyndEntry> entries = new ArrayList<SyndEntry>();
        SyndEntry entry;
        SyndContent description;
        for (String calendarMap : calendars.keySet()) {
            String calendarId = calendarMap.split(Utils.SPLITTER)[0];
            String type = calendarMap.split(Utils.SPLITTER)[1];
            OutputStream out = importExport.exportCalendar(username, Arrays.asList(new String[] { calendarId }),
                    type, -1);
            if (out != null) {
                ByteArrayInputStream is = new ByteArrayInputStream(out.toString().getBytes());
                Node ical = null;
                Node nodeContent = null;
                try {
                    ical = iCalHome.getNode(calendarMap + Utils.ICS_EXT);
                    nodeContent = ical.getNode(Utils.JCR_CONTENT);
                } catch (Exception e) {
                    ical = iCalHome.addNode(calendarMap + Utils.ICS_EXT, Utils.NT_FILE);
                    nodeContent = ical.addNode(Utils.JCR_CONTENT, Utils.NT_RESOURCE);
                }
                nodeContent.setProperty(Utils.JCR_LASTMODIFIED,
                        java.util.Calendar.getInstance().getTimeInMillis());
                nodeContent.setProperty(Utils.JCR_MIMETYPE, Utils.MIMETYPE_ICALENDAR);
                nodeContent.setProperty(Utils.JCR_DATA, is);
                if (!iCalHome.isNew())
                    iCalHome.save();
                else
                    iCalHome.getSession().save();
                String link = rssData.getLink() + ical.getPath();
                Calendar exoCal = calendars.get(calendarMap);
                entry = new SyndEntryImpl();
                entry.setTitle(exoCal.getName());
                entry.setLink(link);
                description = new SyndContentImpl();
                description.setType(Utils.MIMETYPE_TEXTPLAIN);
                description.setValue(exoCal.getDescription());
                entry.setDescription(description);
                entry.setAuthor(username);
                entries.add(entry);
                entry.getEnclosures();
            }
        }
        if (!entries.isEmpty()) {
            feed.setEntries(entries);
            feed.setEncoding("UTF-8");
            SyndFeedOutput output = new SyndFeedOutput();
            String feedXML = output.outputString(feed);
            feedXML = StringUtils.replace(feedXML, "&amp;", "&");
            storeXML(feedXML, rssHomeNode, rssData);
            rssHomeNode.getSession().save();
        } else {
            log.info("No data to make caldav!");
            return -1;
        }
    } catch (Exception e) {
        if (log.isDebugEnabled())
            log.debug(e);
        return -1;
    }
    return 1;
}

From source file:jp.primecloud.auto.api.ApiFilter.java

/**
 * PCC-API ?/* ww w.ja  v a  2s. c o  m*/
 *
 * ??????
 * notUseFarmApies?API??????
 * ????????????????
 * (????????API???)
 * {@inheritDoc}
 */
public ContainerRequest filter(ContainerRequest request) {

    try {
        // URI()
        URI uri = request.getRequestUri();

        // BASE64???URI(LinkedHashMap)??
        LinkedHashMap<String, String> decodeParamMap = getDecodedParamMap(uri);

        String apiName = uri.getPath().substring(request.getBaseUri().getPath().length());
        if (StringUtils.isEmpty(apiName)) {
            //API??????
            throw new AutoApplicationException("EAPI-000008", "URL", uri.toString());
        }

        //String userName = decodeParamMap.get(PARAM_NAME_KEY);
        String accessId = decodeParamMap.get(PARAM_NAME_ACCESS_ID);
        String signature = decodeParamMap.get(PARAM_NAME_SIGNATURE);
        String timestamp = decodeParamMap.get(PARAM_NAME_TIMESTAMP);
        String farmNo = decodeParamMap.get(PARAM_NAME_FARM_NO);
        String userName = null;
        Long userNo = null;
        Farm farm = null;
        User accessUser = null;
        User autoScaleUser = null;
        User masterUser = null;

        // ?
        // Key(??)
        ApiValidate.validateAccessId(accessId);
        // Signature
        ApiValidate.validateSignature(signature);
        // Timestamp(yyyy/MM/dd HH:mm:ss)
        ApiValidate.validateTimestamp(timestamp);

        // PCC-API??
        ApiCertificate apiCertificate = apiCertificateDao.readByApiAccessId(accessId);
        if (apiCertificate == null) {
            // PCC-API?????
            Thread.sleep(SECURE_WAIT_TIME.intValue() * 1000);
            throw new AutoApplicationException("EAPI-000008", PARAM_NAME_ACCESS_ID, accessId);
        }

        //(API)?
        accessUser = userDao.read(apiCertificate.getUserNo());
        if (accessUser == null) {
            // ????
            throw new AutoApplicationException("EAPI-100000", "User", "UserNo", apiCertificate.getUserNo());
        }

        //TODO ????
        //????/??
        //??????????????
        //if (?) {
        //    ?
        //}

        // Signature??
        String uriText = createUriQueryParams(decodeParamMap, uri);
        String encodeUriText = encodeSHA256(uriText, apiCertificate.getApiSecretKey());
        if (BooleanUtils.isFalse(encodeUriText.equals(signature))) {
            //Signature??????
            Thread.sleep(SECURE_WAIT_TIME.intValue() * 1000);
            throw new AutoApplicationException("EAPI-000008", "URL", uri.toString());
        }

        if (Arrays.asList(notUseFarmApies).contains(apiName) == false) {
            //FarmNo
            ApiValidate.validateFarmNo(farmNo);
            farm = farmDao.read(Long.parseLong(farmNo));
            if (farm == null) {
                // ????
                throw new AutoApplicationException("EAPI-100000", "Farm", PARAM_NAME_FARM_NO, farmNo);
            }
        }

        //?????
        if (farm != null && (StringUtils.isNotEmpty(AUTO_SCALING_USER)
                && AUTO_SCALING_USER.equals(accessUser.getUsername()) || accessUser.getPowerUser())) {
            //????POWER USER????
            //????????????
            //TODO ?????PCC-API?????
            autoScaleUser = userDao.read(farm.getUserNo());
            userNo = autoScaleUser.getUserNo();
            userName = autoScaleUser.getUsername();
        } else if (!accessUser.getPowerUser()
                && accessUser.getUserNo().equals(accessUser.getMasterUser()) == false) {
            //?PCC  ?????
            if (accessUser.getMasterUser() != null) {
                userNo = accessUser.getMasterUser();
                masterUser = userDao.read(accessUser.getMasterUser());
                userName = masterUser.getUsername();
            }
        } else {
            //  ?????
            userNo = accessUser.getUserNo();
            userName = accessUser.getUsername();
        }

        if (farm != null && farm.getUserNo().equals(userNo) == false) {
            // ?????????
            throw new AutoApplicationException("EAPI-100026", farmNo, accessUser.getUsername());
        }

        //User(??)URL?
        if (!apiName.equals("Login")) {
            decodeParamMap.put(PARAM_NAME_USER, userName);
        }

        //LoggingUtils?
        LoggingUtils.setUserNo(userNo);
        LoggingUtils.setLoginUserNo(accessUser.getUserNo());
        LoggingUtils.setUserName(accessUser.getUsername());
        if (farm != null) {
            LoggingUtils.setFarmNo(farm.getFarmNo());
            LoggingUtils.setFarmName(farm.getFarmName());
        }

        // ??URL?
        for (String key : decodeParamMap.keySet()) {
            request.getQueryParameters().putSingle(key, decodeParamMap.get(key));
        }

        // 
        log.info(MessageUtils.getMessage("IAPI-000001", accessUser.getUsername(), apiName));
    } catch (Throwable e) {
        String message = "";
        if (e instanceof AutoException || e instanceof AutoApplicationException) {
            message = e.getMessage();
        } else {
            message = MessageUtils.getMessage("EAPI-000000");
        }
        // 
        log.error(message, e);

        // ErrorApi?
        URI errorUri = URI.create(request.getBaseUri() + "Error");
        request.setUris(request.getBaseUri(), errorUri);
        request.getQueryParameters().putSingle("Message", message);
    }

    return request;
}