List of usage examples for java.util LinkedHashMap size
int size();
From source file:org.apache.asterix.app.translator.QueryTranslator.java
private static ARecordType createEnforcedType(ARecordType initialType, List<Index> indexes) throws AlgebricksException { ARecordType enforcedType = initialType; for (Index index : indexes) { if (!index.isSecondaryIndex() || !index.isEnforcingKeyFileds()) { continue; }/*from ww w .j av a2 s. co m*/ if (index.hasMetaFields()) { throw new AlgebricksException("Indexing an open field is only supported on the record part"); } for (int i = 0; i < index.getKeyFieldNames().size(); i++) { Deque<Pair<ARecordType, String>> nestedTypeStack = new ArrayDeque<>(); List<String> splits = index.getKeyFieldNames().get(i); ARecordType nestedFieldType = enforcedType; boolean openRecords = false; String bridgeName = nestedFieldType.getTypeName(); int j; // Build the stack for the enforced type for (j = 1; j < splits.size(); j++) { nestedTypeStack.push(new Pair<ARecordType, String>(nestedFieldType, splits.get(j - 1))); bridgeName = nestedFieldType.getTypeName(); nestedFieldType = (ARecordType) enforcedType.getSubFieldType(splits.subList(0, j)); if (nestedFieldType == null) { openRecords = true; break; } } if (openRecords) { // create the smallest record enforcedType = new ARecordType(splits.get(splits.size() - 2), new String[] { splits.get(splits.size() - 1) }, new IAType[] { AUnionType.createUnknownableType(index.getKeyFieldTypes().get(i)) }, true); // create the open part of the nested field for (int k = splits.size() - 3; k > (j - 2); k--) { enforcedType = new ARecordType(splits.get(k), new String[] { splits.get(k + 1) }, new IAType[] { AUnionType.createUnknownableType(enforcedType) }, true); } // Bridge the gap Pair<ARecordType, String> gapPair = nestedTypeStack.pop(); ARecordType parent = gapPair.first; IAType[] parentFieldTypes = ArrayUtils.addAll(parent.getFieldTypes().clone(), new IAType[] { AUnionType.createUnknownableType(enforcedType) }); enforcedType = new ARecordType(bridgeName, ArrayUtils.addAll(parent.getFieldNames(), enforcedType.getTypeName()), parentFieldTypes, true); } else { //Schema is closed all the way to the field //enforced fields are either null or strongly typed LinkedHashMap<String, IAType> recordNameTypesMap = createRecordNameTypeMap(nestedFieldType); // if a an enforced field already exists and the type is correct IAType enforcedFieldType = recordNameTypesMap.get(splits.get(splits.size() - 1)); if (enforcedFieldType != null && enforcedFieldType.getTypeTag() == ATypeTag.UNION && ((AUnionType) enforcedFieldType).isUnknownableType()) { enforcedFieldType = ((AUnionType) enforcedFieldType).getActualType(); } if (enforcedFieldType != null && !ATypeHierarchy.canPromote(enforcedFieldType.getTypeTag(), index.getKeyFieldTypes().get(i).getTypeTag())) { throw new AlgebricksException("Cannot enforce field " + index.getKeyFieldNames().get(i) + " to have type " + index.getKeyFieldTypes().get(i)); } if (enforcedFieldType == null) { recordNameTypesMap.put(splits.get(splits.size() - 1), AUnionType.createUnknownableType(index.getKeyFieldTypes().get(i))); } enforcedType = new ARecordType(nestedFieldType.getTypeName(), recordNameTypesMap.keySet().toArray(new String[recordNameTypesMap.size()]), recordNameTypesMap.values().toArray(new IAType[recordNameTypesMap.size()]), nestedFieldType.isOpen()); } // Create the enforced type for the nested fields in the schema, from the ground up if (!nestedTypeStack.isEmpty()) { while (!nestedTypeStack.isEmpty()) { Pair<ARecordType, String> nestedTypePair = nestedTypeStack.pop(); ARecordType nestedRecType = nestedTypePair.first; IAType[] nestedRecTypeFieldTypes = nestedRecType.getFieldTypes().clone(); nestedRecTypeFieldTypes[nestedRecType.getFieldIndex(nestedTypePair.second)] = enforcedType; enforcedType = new ARecordType(nestedRecType.getTypeName() + "_enforced", nestedRecType.getFieldNames(), nestedRecTypeFieldTypes, nestedRecType.isOpen()); } } } } return enforcedType; }
From source file:com.gtwm.pb.model.manageData.DataManagement.java
public int globalEdit(HttpServletRequest request, TableInfo table, LinkedHashMap<BaseField, BaseValue> dataToSave, SessionDataInfo sessionData, List<FileItem> multipartItems) throws InputRecordException, ObjectNotFoundException, SQLException, CodingErrorException, CantDoThatException, DisallowedException, MissingParametersException { int affectedFieldCount = dataToSave.size(); for (BaseField affectedField : dataToSave.keySet()) { if (affectedField.getFieldName().equals(HiddenFields.LAST_MODIFIED.getFieldName())) { affectedFieldCount--;//from w ww .j a v a2s. c om } if (affectedField.getFieldName().equals(HiddenFields.MODIFIED_BY.getFieldName())) { affectedFieldCount--; } } if (affectedFieldCount > 1) { throw new CantDoThatException( "Global edits can only apply changes to one field at a time. Requested field changes were " + dataToSave); } Connection conn = null; Set<Integer> rowIds = new HashSet<Integer>(); BaseReportInfo sessionReport = sessionData.getReport(); BaseField primaryKey = table.getPrimaryKey(); try { conn = this.dataSource.getConnection(); conn.setAutoCommit(false); ReportDataInfo reportData = new ReportData(conn, sessionReport, false, false); // Generates a SELECT DISTINCT on the primary key including // filterValues & rowLimits in the WHERE clause Map<BaseField, Boolean> emptySorts = new HashMap<BaseField, Boolean>(); Map<BaseField, String> filterValues = sessionData.getReportFilterValues(); PreparedStatement statement = reportData.getReportSqlPreparedStatement(conn, filterValues, false, emptySorts, -1, primaryKey, QuickFilterType.AND, false); ResultSet results = statement.executeQuery(); while (results.next()) { Integer item = results.getInt(1); if (item != null) { rowIds.add(item); } } results.close(); statement.close(); } catch (SQLException sqlex) { // catch exception where field is not included // within report and simply return an empty tree logger.warn(sqlex.toString() + ". Probably occurred because field " + this + " isn't in report " + sessionReport + ", in which case it's nothing to worry about"); } finally { if (conn != null) { conn.close(); } } this.saveRecord(request, table, dataToSave, false, rowIds, sessionData, multipartItems); return rowIds.size(); }
From source file:com.dbmojo.QueryExecutor.java
/** * Execute a set of queries/updates encoded in JSON via <b>reqStr</b> in the * format <br><br><i>[{query:"select x from y",values:[]},{}...] * </i>.<br><br>The <b>update</b> flag determines whether or not to * treat each statement in the <b>reqStr</b> as an update or a query. *///w w w . ja v a 2s . c o m public String execute(String reqStr, boolean update) throws Exception { if (DebugLog.enabled) { DebugLog.add(this, "Begin execute"); } String message = ""; ArrayList<HashMap> resultsList = new ArrayList<HashMap>(); LinkedHashMap<String, PreparedStatement> bpstmts = null; Statement bstmt = null; try { this.open(update); if (update) { conn.setAutoCommit(false); } final JSONArray reqs = new JSONArray(reqStr); final boolean batchUpdates = reqs.length() > 1; //Connection MUST be ready to go if (this.conn == null) { throw new QueryExecutorException("Connection could not be checked out"); } final int rLen = reqs.length(); if (rLen <= 0) { throw new QueryExecutorException("No queries specified"); } for (int r = 0; r < rLen; r++) { String rMessage = ""; final JSONObject reqObj = reqs.getJSONObject(r); JSONArray tValues = reqObj.optJSONArray("values"); String[] values = new String[(tValues != null ? tValues.length() : 0)]; //Convert the JSONArray to a String[] for (int v = 0; v < values.length; v++) { values[v] = tValues.getString(v); } String query = reqObj.getString("query"); final boolean prepared = values != null; //Can't move forward without a query! if (query == null || query.equals("")) { throw new QueryExecutorException("Query is missing"); } //Here's where we need to do either an update or a query if (update) { if (batchUpdates) { // This is NOT a prepared statement and we need to create a // batch statement to add all non prepared statements to if (!prepared && bstmt == null) { bstmt = conn.createStatement(); // This IS a prepared statement and we need to create a // ordered map of prepared statements so we can execute // these statements together in order (sortof...) } else if (prepared && bpstmts == null) { bpstmts = new LinkedHashMap<String, PreparedStatement>(); } addBatchUpdate(this.conn, prepared, query, values, bstmt, bpstmts); } else { // Single update query / prepared statement to execute executeUpdate(this.conn, prepared, query, values); } } else { resultsList.add(executeQuery(this.conn, prepared, query, values)); } } //Execute Batch Updates if (update && batchUpdates) { //Execute any prepared statement batches that have been gathered. //If we have an SQL error and exception will be thrown if (bpstmts != null && bpstmts.size() > 0) { for (PreparedStatement p : bpstmts.values()) { if (DebugLog.enabled) { DebugLog.add(this, "Executing batch prepared statement"); } p.executeBatch(); } } //Execute all the standard SQL in a batch. //If we have a SQL error an Exception will be thrown if (bstmt != null) { if (DebugLog.enabled) { DebugLog.add(this, "Executing batch statement"); } bstmt.executeBatch(); } } if (update) { this.conn.commit(); } } catch (JSONException je) { //There was an error parsing the JSON final String err = je.toString(); if (DebugLog.enabled) { DebugLog.add(this, err); } resultsList.add(Util.getError(err)); } catch (Exception e) { //We couldn't connect to the DB... if (this.conn == null) { final String err = e.toString(); if (ErrorLog.enabled) { ErrorLog.add(this, err, false); } resultsList.add(Util.getError(err)); //There was an error executing the query/update } else if (update) { final String err = "Rolling Back Update(s): " + e; if (DebugLog.enabled) { DebugLog.add(this, err); } if (this.conn != null) { this.conn.rollback(); } resultsList.add(Util.getError(err)); } else { final String err = e.toString(); if (DebugLog.enabled) { DebugLog.add(this, err); } resultsList.add(Util.getError(err)); } } finally { //Cleanup batch statement (If applicable) if (bstmt != null) { try { if (DebugLog.enabled) { DebugLog.add(this, "Closing batch statement"); } bstmt.close(); } catch (Exception se) { String err = "Error closing batch statement - " + se.toString(); if (ErrorLog.enabled) { ErrorLog.add(this, err, false); } resultsList.add(Util.getError(err)); } } //Cleanup the batch prepared statement (If applicable) if (bpstmts != null) { for (PreparedStatement p : bpstmts.values()) { try { if (p != null) { p.close(); if (DebugLog.enabled) { DebugLog.add(this, "Closing batch prepared stmnt"); } } } catch (Exception pse) { String err = "Error closing batch prepared stmnt - " + pse.toString(); if (ErrorLog.enabled) { ErrorLog.add(this, err, false); } resultsList.add(Util.getError(err)); } } } if (DebugLog.enabled) { DebugLog.add(this, "Closing connection"); } //Cleanup DB connection (Always applicable) this.conn.close(); } if (DebugLog.enabled) { DebugLog.add(this, "End execute"); } //UPDATE => [{message:"",status:"success"}] if (update && resultsList.size() <= 0) { HashMap pObj = new HashMap(); pObj.put("message", ""); pObj.put("status", "success"); pObj.put("rows", new ArrayList()); pObj.put("types", new ArrayList()); pObj.put("cols", new ArrayList()); resultsList.add(pObj); } //Serialize resultsArray into JSON return serializeToJson(resultsList); }
From source file:me.piebridge.bible.Bible.java
public LinkedHashMap<String, String> getOsiss(String book, int limit) { LinkedHashMap<String, String> osiss = new LinkedHashMap<String, String>(); if (book != null) { // fix for zhcn book = book.replace("", ""); book = book.replace("", ""); book = book.replace("", "??"); book = book.replace(SearchManager.SUGGEST_URI_PATH_QUERY, "").replace(" ", "").toLowerCase(Locale.US); }/*from w w w.j a v a 2s .c o m*/ Log.d(TAG, "book: " + book); ArrayList<Entry<String, String>> maps = new ArrayList<Entry<String, String>>(); for (Entry<String, String> entry : searchshort.entrySet()) { maps.add(entry); } for (Entry<String, String> entry : searchfull.entrySet()) { maps.add(entry); } for (LinkedHashMap<String, String> map : getMaps(TYPE.HUMAN)) { for (Entry<String, String> entry : map.entrySet()) { maps.add(entry); } } for (LinkedHashMap<String, String> map : getMaps(TYPE.OSIS)) { for (Entry<String, String> entry : map.entrySet()) { maps.add(entry); } } if (book == null || "".equals(book)) { for (int i = 0; i < this.osiss.size() && i < limit; ++i) { osiss.put(humans.get(i), this.osiss.get(i)); } return osiss; } for (Entry<String, String> entry : maps) { if (checkStartSuggest(osiss, entry.getValue(), entry.getValue(), book, limit)) { return osiss; } } for (Entry<String, String> entry : maps) { if (checkContainSuggest(osiss, entry.getValue(), entry.getValue(), book, limit)) { return osiss; } } for (Entry<String, String> entry : maps) { if (checkStartSuggest(osiss, entry.getKey(), entry.getValue(), book, limit)) { return osiss; } } for (Entry<String, String> entry : maps) { if (checkContainSuggest(osiss, entry.getKey(), entry.getValue(), book, limit)) { return osiss; } } String osis = ""; String chapter = ""; if (osiss.size() == 0) { ArrayList<OsisItem> items = OsisItem.parseSearch(book, mContext); if (items.size() == 1) { OsisItem item = items.get(0); osis = item.book; chapter = item.chapter; } } else if (osiss.size() == 1) { for (Entry<String, String> entry : osiss.entrySet()) { osis = entry.getValue(); chapter = "0"; } } if ("".equals(osis)) { return osiss; } String bookname = get(TYPE.HUMAN, bible.getPosition(TYPE.OSIS, osis)); if (bookname == null) { bookname = osis; } int chapternum = 0; int maxchapter = 0; try { chapternum = Integer.parseInt(chapter); } catch (Exception e) { } try { maxchapter = Integer.parseInt(get(TYPE.CHAPTER, getPosition(TYPE.OSIS, osis))); } catch (Exception e) { return osiss; } if (bookname == null || "".equals(bookname)) { return osiss; } if (chapternum != 0) { osiss.put(bookname + " " + chapternum, osis + chapternum); } for (int i = 0 + chapternum * 10; i <= maxchapter && i < 10 * chapternum + 10; i++) { if (i != 0) { osiss.put(bookname + " " + i, osis + i); } } return osiss; }
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); }// w w w . j a va2s. 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:com.gtwm.pb.model.manageData.DataManagement.java
/** * Used by both the public saveRecord and globalEdit methods */// w w w .ja v a 2 s.co 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:com.alibaba.wasp.plan.parser.druid.DruidDDLParser.java
/** * Process Alter Table Statement and generate Execute Plan * /*from w w w .ja v a 2 s. c o m*/ */ private void getAlterTablePlan(ParseContext context, MySqlAlterTableStatement sqlAlterTableStatement, MetaEventOperation metaEventOperation) throws IOException { SQLExprTableSource tableSource = sqlAlterTableStatement.getTableSource(); String tableName = parseFromClause(tableSource); // check if table exists and get Table info FTable oldTable = metaEventOperation.checkAndGetTable(tableName, true); FTable newTable = FTable.clone(oldTable); List<SQLAlterTableItem> items = sqlAlterTableStatement.getItems(); for (SQLAlterTableItem item : items) { if (item instanceof WaspSqlAlterTableChangeColumn) { // Alter Table Change Column WaspSqlAlterTableChangeColumn changeColumn = (WaspSqlAlterTableChangeColumn) item; SQLName columnName = changeColumn.getColumnName(); LinkedHashMap<String, Field> ftableColumns = newTable.getColumns(); String oldColumnName = parseName(columnName); // Table have this column and this column is not primary key metaEventOperation.checkFieldExists(oldTable, oldColumnName); metaEventOperation.checkFieldNotInPrimaryKeys(oldTable, oldColumnName); // Check column not in a index metaEventOperation.checkColumnNotInIndex(oldTable, oldColumnName); // Which column(index) to change Field field = ftableColumns.get(oldColumnName); // Change this Field SQLColumnDefinition newColumnDefinition = changeColumn.getNewColumnDefinition(); // ColumnFamily specify do not supported. if (newColumnDefinition instanceof WaspSqlColumnDefinition) { WaspSqlColumnDefinition waspSqlColumnDefinition = (WaspSqlColumnDefinition) newColumnDefinition; if (waspSqlColumnDefinition.getColumnFamily() != null) { throw new UnsupportedException("Alter Table, columnFamily specify do not supported."); } } if (newColumnDefinition.getDataType() != null) { field.setType(parse(newColumnDefinition.getDataType())); } String newColumnName = parseName(newColumnDefinition.getName()); if (!oldColumnName.equals(newColumnName)) { // Change column name for (Field f : ftableColumns.values()) { if (f.getName().equalsIgnoreCase(newColumnName)) { throw new UnsupportedException( "Unsupported. Rename one column to a column that already column " + newColumnName); } } field.setName(newColumnName); } } else if (item instanceof MySqlAlterTableAddColumn) { // Alter Table Add Column MySqlAlterTableAddColumn addColumn = (MySqlAlterTableAddColumn) item; List<SQLColumnDefinition> columns = addColumn.getColumns(); boolean first = addColumn.isFirst(); SQLName afterColumn = addColumn.getAfterColumn(); LinkedHashMap<String, Field> ftableColumns = newTable.getColumns(); List<Field> addFields = convertColumnDefForAlterTable(columns); // check Duplicate column name metaEventOperation.areLegalTableColumns(ftableColumns.values(), addFields); // Do not support add ColumnFamily dynamic right now. metaEventOperation.checkColumnFamilyName(ftableColumns.values(), addFields); if (first) { this.addFieldByPosition(-1, addFields, ftableColumns, newTable); } else if (afterColumn != null) { int index = getIndex(parseName(afterColumn), ftableColumns); this.addFieldByPosition(index, addFields, ftableColumns, newTable); } else { int index = ftableColumns.size() - 1; this.addFieldByPosition(index, addFields, ftableColumns, newTable); } } else if (item instanceof SQLAlterTableDropColumnItem) { // Alter Table Drop Column SQLAlterTableDropColumnItem dropColumn = (SQLAlterTableDropColumnItem) item; SQLName columnName = dropColumn.getColumnName(); String cname = parseName(columnName); // This column is not primary key metaEventOperation.checkFieldNotInPrimaryKeys(oldTable, cname); // Check column not in a index, if you want to drop the column you // should drop the index first metaEventOperation.checkColumnNotInIndex(oldTable, cname); LinkedHashMap<String, Field> ftableColumns = newTable.getColumns(); Field field = ftableColumns.remove(cname); if (field == null) { throw new UnsupportedException("Unsupported Do not find this column " + SQLUtils.toSQLString(((SQLAlterTableDropColumnItem) item).getColumnName())); } newTable.setColumns(ftableColumns); } else { throw new UnsupportedException(SQLUtils.toSQLString(item) + " SQLAlterTableItem Unsupported"); } } AlterTablePlan alterTable = new AlterTablePlan(oldTable, newTable); context.setPlan(alterTable); LOG.debug("AlterTablePlan " + alterTable.toString()); }
From source file:lucee.runtime.config.ConfigWebFactory.java
/** * @param configServer/*from w w w . j a va 2s .co m*/ * @param config * @param doc * @throws IOException */ private static void loadCustomTagsMappings(ConfigServerImpl configServer, ConfigImpl config, Document doc, int mode) { boolean hasAccess = ConfigWebUtil.hasAccess(config, SecurityManager.TYPE_CUSTOM_TAG); boolean hasCS = configServer != null; Element customTag = getChildByName(doc.getDocumentElement(), "custom-tag"); Element[] ctMappings = getChildren(customTag, "mapping"); // String virtualx="/custom-tag/"; // do patch cache String strDoPathcache = customTag.getAttribute("use-cache-path"); if (hasAccess && !StringUtil.isEmpty(strDoPathcache, true)) { config.setUseCTPathCache(Caster.toBooleanValue(strDoPathcache.trim(), true)); } else if (hasCS) { config.setUseCTPathCache(configServer.useCTPathCache()); } // do custom tag local search if (mode == ConfigImpl.MODE_STRICT) { config.setDoLocalCustomTag(false); } else { String strDoCTLocalSearch = customTag.getAttribute("custom-tag-local-search"); if (hasAccess && !StringUtil.isEmpty(strDoCTLocalSearch)) { config.setDoLocalCustomTag(Caster.toBooleanValue(strDoCTLocalSearch.trim(), true)); } else if (hasCS) { config.setDoLocalCustomTag(configServer.doLocalCustomTag()); } } // do custom tag deep search if (mode == ConfigImpl.MODE_STRICT) { config.setDoCustomTagDeepSearch(false); } else { String strDoCTDeepSearch = customTag.getAttribute("custom-tag-deep-search"); if (hasAccess && !StringUtil.isEmpty(strDoCTDeepSearch)) { config.setDoCustomTagDeepSearch(Caster.toBooleanValue(strDoCTDeepSearch.trim(), false)); } else if (hasCS) { config.setDoCustomTagDeepSearch(configServer.doCustomTagDeepSearch()); } } // extensions if (mode == ConfigImpl.MODE_STRICT) { config.setCustomTagExtensions(new String[] { "cfc" }); } else { String strExtensions = customTag.getAttribute("extensions"); if (hasAccess && !StringUtil.isEmpty(strExtensions)) { try { String[] arr = ListUtil.toStringArray(ListUtil.listToArrayRemoveEmpty(strExtensions, ",")); config.setCustomTagExtensions(ListUtil.trimItems(arr)); } catch (PageException e) { } } else if (hasCS) { config.setCustomTagExtensions(configServer.getCustomTagExtensions()); } } // Web Mapping boolean hasSet = false; Mapping[] mappings = null; if (hasAccess && ctMappings.length > 0) { mappings = new Mapping[ctMappings.length]; for (int i = 0; i < ctMappings.length; i++) { Element ctMapping = ctMappings[i]; String physical = ctMapping.getAttribute("physical"); String archive = ctMapping.getAttribute("archive"); boolean readonly = toBoolean(ctMapping.getAttribute("readonly"), false); boolean hidden = toBoolean(ctMapping.getAttribute("hidden"), false); //boolean trusted = toBoolean(ctMapping.getAttribute("trusted"), false); short inspTemp = inspectTemplate(ctMapping); int clMaxEl = toInt(ctMapping.getAttribute("classloader-max-elements"), 100); String primary = ctMapping.getAttribute("primary"); boolean physicalFirst = archive == null || !primary.equalsIgnoreCase("archive"); hasSet = true; mappings[i] = new MappingImpl(config, ConfigWebAdmin.createVirtual(ctMapping), physical, archive, inspTemp, physicalFirst, hidden, readonly, true, false, true, null, clMaxEl); // print.out(mappings[i].isPhysicalFirst()); } config.setCustomTagMappings(mappings); } // Server Mapping if (hasCS) { Mapping[] originals = configServer.getCustomTagMappings(); Mapping[] clones = new Mapping[originals.length]; LinkedHashMap map = new LinkedHashMap(); Mapping m; for (int i = 0; i < clones.length; i++) { m = ((MappingImpl) originals[i]).cloneReadOnly(config); map.put(toKey(m), m); // clones[i]=((MappingImpl)m[i]).cloneReadOnly(config); } if (mappings != null) { for (int i = 0; i < mappings.length; i++) { m = mappings[i]; map.put(toKey(m), m); } } if (originals.length > 0) { clones = new Mapping[map.size()]; Iterator it = map.entrySet().iterator(); Map.Entry entry; int index = 0; while (it.hasNext()) { entry = (Entry) it.next(); clones[index++] = (Mapping) entry.getValue(); // print.out("c:"+clones[index-1]); } hasSet = true; // print.err("set:"+clones.length); config.setCustomTagMappings(clones); } } if (!hasSet) { // MappingImpl m=new // MappingImpl(config,"/default-customtags/","{lucee-web}/customtags/",null,false,true,false,false,true,false,true); // config.setCustomTagMappings(new // Mapping[]{m.cloneReadOnly(config)}); } }
From source file:lucee.runtime.config.ConfigWebFactory.java
/** * @param configServer// w w w. j av a2s . c o m * @param config * @param doc * @throws IOException */ private static void loadComponent(ConfigServer configServer, ConfigImpl config, Document doc, int mode) { Element component = getChildByName(doc.getDocumentElement(), "component"); boolean hasAccess = ConfigWebUtil.hasAccess(config, SecurityManager.TYPE_SETTING); boolean hasSet = false; boolean hasCS = configServer != null; // String virtual="/component/"; if (component != null && hasAccess) { // component-default-import String strCDI = component.getAttribute("component-default-import"); if (StringUtil.isEmpty(strCDI, true) && configServer != null) { strCDI = ((ConfigServerImpl) configServer).getComponentDefaultImport().toString(); } if (!StringUtil.isEmpty(strCDI, true)) config.setComponentDefaultImport(strCDI); // Base String strBase = component.getAttribute("base"); if (StringUtil.isEmpty(strBase, true) && configServer != null) { strBase = configServer.getBaseComponentTemplate(); } config.setBaseComponentTemplate(strBase); // deep search if (mode == ConfigImpl.MODE_STRICT) { config.setDoComponentDeepSearch(false); } else { String strDeepSearch = component.getAttribute("deep-search"); if (!StringUtil.isEmpty(strDeepSearch)) { config.setDoComponentDeepSearch(Caster.toBooleanValue(strDeepSearch.trim(), false)); } else if (hasCS) { config.setDoComponentDeepSearch(((ConfigServerImpl) configServer).doComponentDeepSearch()); } } // Dump-Template String strDumpRemplate = component.getAttribute("dump-template"); if ((strDumpRemplate == null || strDumpRemplate.trim().length() == 0) && configServer != null) { strDumpRemplate = configServer.getComponentDumpTemplate(); } config.setComponentDumpTemplate(strDumpRemplate); // data-member-default-access if (mode == ConfigImpl.MODE_STRICT) { config.setComponentDataMemberDefaultAccess(Component.ACCESS_PRIVATE); } else { String strDmda = component.getAttribute("data-member-default-access"); if (strDmda != null && strDmda.trim().length() > 0) { strDmda = strDmda.toLowerCase().trim(); if (strDmda.equals("remote")) config.setComponentDataMemberDefaultAccess(Component.ACCESS_REMOTE); else if (strDmda.equals("public")) config.setComponentDataMemberDefaultAccess(Component.ACCESS_PUBLIC); else if (strDmda.equals("package")) config.setComponentDataMemberDefaultAccess(Component.ACCESS_PACKAGE); else if (strDmda.equals("private")) config.setComponentDataMemberDefaultAccess(Component.ACCESS_PRIVATE); } else if (configServer != null) { config.setComponentDataMemberDefaultAccess(configServer.getComponentDataMemberDefaultAccess()); } } // trigger-properties if (mode == ConfigImpl.MODE_STRICT) { config.setTriggerComponentDataMember(true); } else { Boolean tp = Caster.toBoolean(component.getAttribute("trigger-data-member"), null); if (tp != null) config.setTriggerComponentDataMember(tp.booleanValue()); else if (configServer != null) { config.setTriggerComponentDataMember(configServer.getTriggerComponentDataMember()); } } // local search if (mode == ConfigImpl.MODE_STRICT) { config.setComponentLocalSearch(false); } else { Boolean ls = Caster.toBoolean(component.getAttribute("local-search"), null); if (ls != null) config.setComponentLocalSearch(ls.booleanValue()); else if (configServer != null) { config.setComponentLocalSearch(((ConfigServerImpl) configServer).getComponentLocalSearch()); } } // use cache path Boolean ucp = Caster.toBoolean(component.getAttribute("use-cache-path"), null); if (ucp != null) config.setUseComponentPathCache(ucp.booleanValue()); else if (configServer != null) { config.setUseComponentPathCache(((ConfigServerImpl) configServer).useComponentPathCache()); } // use component shadow if (mode == ConfigImpl.MODE_STRICT) { config.setUseComponentShadow(false); } else { Boolean ucs = Caster.toBoolean(component.getAttribute("use-shadow"), null); if (ucs != null) config.setUseComponentShadow(ucs.booleanValue()); else if (configServer != null) { config.setUseComponentShadow(configServer.useComponentShadow()); } } } else if (configServer != null) { config.setBaseComponentTemplate(configServer.getBaseComponentTemplate()); config.setComponentDumpTemplate(configServer.getComponentDumpTemplate()); if (mode == ConfigImpl.MODE_STRICT) { config.setComponentDataMemberDefaultAccess(Component.ACCESS_PRIVATE); config.setTriggerComponentDataMember(true); } else { config.setComponentDataMemberDefaultAccess(configServer.getComponentDataMemberDefaultAccess()); config.setTriggerComponentDataMember(configServer.getTriggerComponentDataMember()); } } if (mode == ConfigImpl.MODE_STRICT) { config.setDoComponentDeepSearch(false); config.setComponentDataMemberDefaultAccess(Component.ACCESS_PRIVATE); config.setTriggerComponentDataMember(true); config.setComponentLocalSearch(false); config.setUseComponentShadow(false); } // Web Mapping Element[] cMappings = getChildren(component, "mapping"); hasSet = false; Mapping[] mappings = null; if (hasAccess && cMappings.length > 0) { mappings = new Mapping[cMappings.length]; for (int i = 0; i < cMappings.length; i++) { Element cMapping = cMappings[i]; String physical = cMapping.getAttribute("physical"); String archive = cMapping.getAttribute("archive"); boolean readonly = toBoolean(cMapping.getAttribute("readonly"), false); boolean hidden = toBoolean(cMapping.getAttribute("hidden"), false); //boolean trusted = toBoolean(cMapping.getAttribute("trusted"), false); short inspTemp = inspectTemplate(cMapping); String virtual = ConfigWebAdmin.createVirtual(cMapping); int clMaxEl = toInt(cMapping.getAttribute("classloader-max-elements"), 100); String primary = cMapping.getAttribute("primary"); boolean physicalFirst = archive == null || !primary.equalsIgnoreCase("archive"); hasSet = true; mappings[i] = new MappingImpl(config, virtual, physical, archive, inspTemp, physicalFirst, hidden, readonly, true, false, true, null, clMaxEl); } config.setComponentMappings(mappings); } // Server Mapping if (hasCS) { Mapping[] originals = ((ConfigServerImpl) configServer).getComponentMappings(); Mapping[] clones = new Mapping[originals.length]; LinkedHashMap map = new LinkedHashMap(); Mapping m; for (int i = 0; i < clones.length; i++) { m = ((MappingImpl) originals[i]).cloneReadOnly(config); map.put(toKey(m), m); // clones[i]=((MappingImpl)m[i]).cloneReadOnly(config); } if (mappings != null) { for (int i = 0; i < mappings.length; i++) { m = mappings[i]; map.put(toKey(m), m); } } if (originals.length > 0) { clones = new Mapping[map.size()]; Iterator it = map.entrySet().iterator(); Map.Entry entry; int index = 0; while (it.hasNext()) { entry = (Entry) it.next(); clones[index++] = (Mapping) entry.getValue(); // print.out("c:"+clones[index-1]); } hasSet = true; // print.err("set:"+clones.length); config.setComponentMappings(clones); } } if (!hasSet) { MappingImpl m = new MappingImpl(config, "/default", "{lucee-web}/components/", null, ConfigImpl.INSPECT_UNDEFINED, true, false, false, true, false, true, null); config.setComponentMappings(new Mapping[] { m.cloneReadOnly(config) }); } }
From source file:lucee.runtime.config.XMLConfigWebFactory.java
/** * @param configServer//from w w w. ja va 2 s . c o m * @param config * @param doc * @throws IOException */ private static void loadCustomTagsMappings(ConfigServerImpl configServer, ConfigImpl config, Document doc, int mode) { boolean hasAccess = ConfigWebUtil.hasAccess(config, SecurityManager.TYPE_CUSTOM_TAG); boolean hasCS = configServer != null; Element customTag = getChildByName(doc.getDocumentElement(), "custom-tag"); Element[] ctMappings = getChildren(customTag, "mapping"); // String virtualx="/custom-tag/"; // do patch cache String strDoPathcache = customTag.getAttribute("use-cache-path"); if (hasAccess && !StringUtil.isEmpty(strDoPathcache, true)) { config.setUseCTPathCache(Caster.toBooleanValue(strDoPathcache.trim(), true)); } else if (hasCS) { config.setUseCTPathCache(configServer.useCTPathCache()); } // do custom tag local search if (mode == ConfigImpl.MODE_STRICT) { config.setDoLocalCustomTag(false); } else { String strDoCTLocalSearch = customTag.getAttribute("custom-tag-local-search"); if (hasAccess && !StringUtil.isEmpty(strDoCTLocalSearch)) { config.setDoLocalCustomTag(Caster.toBooleanValue(strDoCTLocalSearch.trim(), true)); } else if (hasCS) { config.setDoLocalCustomTag(configServer.doLocalCustomTag()); } } // do custom tag deep search if (mode == ConfigImpl.MODE_STRICT) { config.setDoCustomTagDeepSearch(false); } else { String strDoCTDeepSearch = customTag.getAttribute("custom-tag-deep-search"); if (hasAccess && !StringUtil.isEmpty(strDoCTDeepSearch)) { config.setDoCustomTagDeepSearch(Caster.toBooleanValue(strDoCTDeepSearch.trim(), false)); } else if (hasCS) { config.setDoCustomTagDeepSearch(configServer.doCustomTagDeepSearch()); } } // extensions if (mode == ConfigImpl.MODE_STRICT) { config.setCustomTagExtensions(Constants.getComponentExtensions()); } else { String strExtensions = customTag.getAttribute("extensions"); if (hasAccess && !StringUtil.isEmpty(strExtensions)) { try { String[] arr = ListUtil.toStringArray(ListUtil.listToArrayRemoveEmpty(strExtensions, ",")); config.setCustomTagExtensions(ListUtil.trimItems(arr)); } catch (PageException e) { } } else if (hasCS) { config.setCustomTagExtensions(configServer.getCustomTagExtensions()); } } // Web Mapping boolean hasSet = false; Mapping[] mappings = null; if (hasAccess && ctMappings.length > 0) { mappings = new Mapping[ctMappings.length]; for (int i = 0; i < ctMappings.length; i++) { Element ctMapping = ctMappings[i]; String physical = ctMapping.getAttribute("physical"); String archive = ctMapping.getAttribute("archive"); boolean readonly = toBoolean(ctMapping.getAttribute("readonly"), false); boolean hidden = toBoolean(ctMapping.getAttribute("hidden"), false); //boolean trusted = toBoolean(ctMapping.getAttribute("trusted"), false); short inspTemp = inspectTemplate(ctMapping); //int clMaxEl = toInt(ctMapping.getAttribute("classloader-max-elements"), 100); String primary = ctMapping.getAttribute("primary"); boolean physicalFirst = archive == null || !primary.equalsIgnoreCase("archive"); hasSet = true; mappings[i] = new MappingImpl(config, XMLConfigAdmin.createVirtual(ctMapping), physical, archive, inspTemp, physicalFirst, hidden, readonly, true, false, true, null, -1, -1); // print.out(mappings[i].isPhysicalFirst()); } config.setCustomTagMappings(mappings); } // Server Mapping if (hasCS) { Mapping[] originals = configServer.getCustomTagMappings(); Mapping[] clones = new Mapping[originals.length]; LinkedHashMap map = new LinkedHashMap(); Mapping m; for (int i = 0; i < clones.length; i++) { m = ((MappingImpl) originals[i]).cloneReadOnly(config); map.put(toKey(m), m); // clones[i]=((MappingImpl)m[i]).cloneReadOnly(config); } if (mappings != null) { for (int i = 0; i < mappings.length; i++) { m = mappings[i]; map.put(toKey(m), m); } } if (originals.length > 0) { clones = new Mapping[map.size()]; Iterator it = map.entrySet().iterator(); Map.Entry entry; int index = 0; while (it.hasNext()) { entry = (Entry) it.next(); clones[index++] = (Mapping) entry.getValue(); // print.out("c:"+clones[index-1]); } hasSet = true; // print.err("set:"+clones.length); config.setCustomTagMappings(clones); } } if (!hasSet) { // MappingImpl m=new // MappingImpl(config,"/default-customtags/","{lucee-web}/customtags/",null,false,true,false,false,true,false,true); // config.setCustomTagMappings(new // Mapping[]{m.cloneReadOnly(config)}); } }