2 * Copyright (C) 2010, 2011 Openismus GmbH
4 * This file is part of GWT-Glom.
6 * GWT-Glom is free software: you can redistribute it and/or modify it
7 * under the terms of the GNU Lesser General Public License as published by the
8 * Free Software Foundation, either version 3 of the License, or (at your
9 * option) any later version.
11 * GWT-Glom is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with GWT-Glom. If not, see <http://www.gnu.org/licenses/>.
20 package org.glom.web.server;
22 import java.beans.PropertyVetoException;
24 import java.io.FilenameFilter;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.sql.Connection;
29 import java.sql.ResultSet;
30 import java.sql.SQLException;
31 import java.sql.Statement;
33 import java.text.DateFormat;
34 import java.text.NumberFormat;
35 import java.util.ArrayList;
36 import java.util.Currency;
37 import java.util.Hashtable;
38 import java.util.Locale;
39 import java.util.Properties;
41 import org.glom.libglom.BakeryDocument.LoadFailureCodes;
42 import org.glom.libglom.Document;
43 import org.glom.libglom.Field;
44 import org.glom.libglom.FieldFormatting;
45 import org.glom.libglom.FieldVector;
46 import org.glom.libglom.Glom;
47 import org.glom.libglom.LayoutFieldVector;
48 import org.glom.libglom.LayoutGroupVector;
49 import org.glom.libglom.LayoutItem;
50 import org.glom.libglom.LayoutItemVector;
51 import org.glom.libglom.LayoutItem_Field;
52 import org.glom.libglom.NumericFormat;
53 import org.glom.libglom.SortClause;
54 import org.glom.libglom.SortFieldPair;
55 import org.glom.libglom.StringVector;
56 import org.glom.web.client.OnlineGlomService;
57 import org.glom.web.shared.ColumnInfo;
58 import org.glom.web.shared.GlomDocument;
59 import org.glom.web.shared.GlomField;
60 import org.glom.web.shared.LayoutListTable;
61 import org.glom.web.shared.layout.LayoutGroup;
62 import org.glom.web.shared.layout.LayoutItemField;
64 import com.allen_sauer.gwt.log.client.Log;
65 import com.google.gwt.user.server.rpc.RemoteServiceServlet;
66 import com.mchange.v2.c3p0.ComboPooledDataSource;
67 import com.mchange.v2.c3p0.DataSources;
69 @SuppressWarnings("serial")
70 public class OnlineGlomServiceImpl extends RemoteServiceServlet implements OnlineGlomService {
72 // class to hold configuration information for related to the glom document and db access
73 private class ConfiguredDocument {
74 private Document document;
75 private ComboPooledDataSource cpds;
76 private boolean authenticated = false;
79 public Document getDocument() { return document; }
80 public void setDocument(Document document) { this.document = document; }
81 public ComboPooledDataSource getCpds() { return cpds; }
82 public void setCpds(ComboPooledDataSource cpds) { this.cpds = cpds; }
83 public boolean isAuthenticated() { return authenticated; }
84 public void setAuthenticated(boolean authenticated) { this.authenticated = authenticated; }
88 // convenience class to for dealing with the Online Glom configuration file
89 private class OnlineGlomProperties extends Properties {
90 public String getKey(String value) {
91 for (String key : stringPropertyNames()) {
92 if (getProperty(key).trim().equals(value))
99 private final Hashtable<String, ConfiguredDocument> documents = new Hashtable<String, ConfiguredDocument>();
100 // TODO implement locale
101 private final Locale locale = Locale.ROOT;
104 * This is called when the servlet is started or restarted.
106 public OnlineGlomServiceImpl() throws Exception {
108 // Find the configuration file. See this thread for background info:
109 // http://stackoverflow.com/questions/2161054/where-to-place-properties-files-in-a-jsp-servlet-web-application
110 OnlineGlomProperties config = new OnlineGlomProperties();
111 InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("onlineglom.properties");
113 Log.fatal("onlineglom.properties not found.");
114 throw new IOException();
118 // check the configured glom file directory
119 String documentDirName = config.getProperty("glom.document.directory");
120 File documentDir = new File(documentDirName);
121 if (!documentDir.isDirectory()) {
122 Log.fatal(documentDirName + " is not a directory.");
123 throw new IOException();
125 if (!documentDir.canRead()) {
126 Log.fatal("Can't read the files in : " + documentDirName);
127 throw new IOException();
130 // get and check the glom files in the specified directory
131 File[] glomFiles = documentDir.listFiles(new FilenameFilter() {
133 public boolean accept(File dir, String name) {
134 return name.endsWith(".glom") ? true : false;
138 for (File glomFile : glomFiles) {
139 Document document = new Document();
140 document.set_file_uri("file://" + glomFile.getAbsolutePath());
142 boolean retval = document.load(error);
143 if (retval == false) {
145 if (LoadFailureCodes.LOAD_FAILURE_CODE_NOT_FOUND == LoadFailureCodes.swigToEnum(error)) {
146 message = "Could not find " + documentDir.getAbsolutePath();
148 message = "An unknown error occurred when trying to load " + documentDir.getAbsolutePath();
151 // continue with for loop because there may be other documents in the directory
155 // load the jdbc driver for the current glom document
156 ComboPooledDataSource cpds = new ComboPooledDataSource();
159 cpds.setDriverClass("org.postgresql.Driver");
160 } catch (PropertyVetoException e) {
161 Log.fatal("Error loading the PostgreSQL JDBC driver. Is the PostgreSQL JDBC jar available to the servlet?");
165 // setup the JDBC driver for the current glom document
166 cpds.setJdbcUrl("jdbc:postgresql://" + document.get_connection_server() + "/"
167 + document.get_connection_database());
169 // check if a username and password have been set and work for the current document
170 String documentTitle = document.get_database_title().trim();
171 ConfiguredDocument configuredDocument = new ConfiguredDocument();
172 String key = config.getKey(documentTitle);
174 String[] keyArray = key.split("\\.");
175 if (keyArray.length == 3 && "title".equals(keyArray[2])) {
176 // username/password could be set, let's check to see if it works
177 String usernameKey = key.replaceAll(keyArray[2], "username");
178 String passwordKey = key.replaceAll(keyArray[2], "password");
179 configuredDocument.setAuthenticated(checkAuthentication(documentTitle, cpds,
180 config.getProperty(usernameKey), config.getProperty(passwordKey)));
184 // check the if the global username and password have been set and work with this document
185 if (!configuredDocument.isAuthenticated()) {
186 configuredDocument.setAuthenticated(checkAuthentication(documentTitle, cpds,
187 config.getProperty("glom.document.username"), config.getProperty("glom.document.password")));
190 // add information to the hash table
191 configuredDocument.setDocument(document);
192 configuredDocument.setCpds(cpds);
193 documents.put(documentTitle, configuredDocument);
198 * Checks if the username and password works with the database configured with the specified ComboPooledDataSource.
200 * @return true if authentication works, false otherwise
202 private boolean checkAuthentication(String documentTitle, ComboPooledDataSource cpds, String username,
203 String password) throws SQLException {
204 cpds.setUser(username);
205 cpds.setPassword(password);
207 int acquireRetryAttempts = cpds.getAcquireRetryAttempts();
208 cpds.setAcquireRetryAttempts(1);
209 Connection conn = null;
211 // FIXME find a better way to check authentication
212 // it's possible that the connection could be failing for another reason
213 conn = cpds.getConnection();
215 } catch (SQLException e) {
216 Log.info("Username and password not correct for document: " + documentTitle);
220 cpds.setAcquireRetryAttempts(acquireRetryAttempts);
226 * This is called when the servlet is stopped or restarted.
228 * @see javax.servlet.GenericServlet#destroy()
231 public void destroy() {
232 Glom.libglom_deinit();
234 for (String documenTitle : documents.keySet()) {
235 ConfiguredDocument configuredDoc = documents.get(documenTitle);
237 DataSources.destroy(configuredDoc.getCpds());
238 } catch (SQLException e) {
239 Log.error("Error cleaning up the ComboPooledDataSource for " + documenTitle, e);
245 public GlomDocument getGlomDocument(String documentTitle) {
247 Document document = documents.get(documentTitle).getDocument();
248 GlomDocument glomDocument = new GlomDocument();
250 // get arrays of table names and titles, and find the default table index
251 StringVector tablesVec = document.get_table_names();
253 int numTables = safeLongToInt(tablesVec.size());
254 // we don't know how many tables will be hidden so we'll use half of the number of tables for the default size
256 ArrayList<String> tableNames = new ArrayList<String>(numTables / 2);
257 ArrayList<String> tableTitles = new ArrayList<String>(numTables / 2);
258 boolean foundDefaultTable = false;
259 int visibleIndex = 0;
260 for (int i = 0; i < numTables; i++) {
261 String tableName = tablesVec.get(i);
262 if (!document.get_table_is_hidden(tableName)) {
263 tableNames.add(tableName);
264 // JNI is "expensive", the comparison will only be called if we haven't already found the default table
265 if (!foundDefaultTable && tableName.equals(document.get_default_table())) {
266 glomDocument.setDefaultTableIndex(visibleIndex);
267 foundDefaultTable = true;
269 tableTitles.add(document.get_table_title(tableName));
274 // set everything we need
275 glomDocument.setTableNames(tableNames);
276 glomDocument.setTableTitles(tableTitles);
284 * @see org.glom.web.client.OnlineGlomService#getDefaultLayoutListTable(java.lang.String)
287 public LayoutListTable getDefaultLayoutListTable(String documentTitle) {
288 GlomDocument glomDocument = getGlomDocument(documentTitle);
289 String tableName = glomDocument.getTableNames().get(glomDocument.getDefaultTableIndex());
290 LayoutListTable layoutListTable = getLayoutListTable(documentTitle, tableName);
291 layoutListTable.setTableName(tableName);
292 return layoutListTable;
295 public LayoutListTable getLayoutListTable(String documentTitle, String table) {
296 ConfiguredDocument configuredDoc = documents.get(documentTitle);
297 Document document = configuredDoc.getDocument();
298 LayoutListTable tableInfo = new LayoutListTable();
300 // access the layout list
301 LayoutGroupVector layoutListVec = document.get_data_layout_groups("list", table);
302 ColumnInfo[] columns = null;
303 LayoutFieldVector layoutFields = new LayoutFieldVector();
304 int listViewLayoutGroupSize = safeLongToInt(layoutListVec.size());
305 if (listViewLayoutGroupSize > 0) {
306 // a layout list is defined, we can use it to for the LayoutListTable
307 if (listViewLayoutGroupSize > 1)
308 Log.warn(documentTitle + " - " + table + ": The size of the list view layout group for table " + table
309 + " is greater than 1. Attempting to use the first item for the layout list view.");
310 LayoutItemVector layoutItemsVec = layoutListVec.get(0).get_items();
312 // find the defined layout list fields
313 int numItems = safeLongToInt(layoutItemsVec.size());
314 columns = new ColumnInfo[numItems];
315 for (int i = 0; i < numItems; i++) {
316 // TODO add support for other LayoutItems (Text, Image, Button)
317 LayoutItem item = layoutItemsVec.get(i);
318 LayoutItem_Field layoutItemField = LayoutItem_Field.cast_dynamic(item);
319 if (layoutItemField != null) {
320 layoutFields.add(layoutItemField);
321 columns[i] = new ColumnInfo(
322 layoutItemField.get_title_or_name(),
323 getColumnInfoHorizontalAlignment(layoutItemField.get_formatting_used_horizontal_alignment()),
324 getColumnInfoGlomFieldType(layoutItemField.get_glom_type()));
328 // no layout list is defined, use the table fields as the layout list
329 FieldVector fieldsVec = document.get_table_fields(table);
331 // find the fields to display in the layout list
332 int numItems = safeLongToInt(fieldsVec.size());
333 columns = new ColumnInfo[numItems];
334 for (int i = 0; i < numItems; i++) {
335 Field field = fieldsVec.get(i);
336 LayoutItem_Field layoutItemField = new LayoutItem_Field();
337 layoutItemField.set_full_field_details(field);
338 layoutFields.add(layoutItemField);
339 columns[i] = new ColumnInfo(layoutItemField.get_title_or_name(),
340 getColumnInfoHorizontalAlignment(layoutItemField.get_formatting_used_horizontal_alignment()),
341 getColumnInfoGlomFieldType(layoutItemField.get_glom_type()));
345 tableInfo.setColumns(columns);
347 // Get the number of rows a query with the table name and layout fields would return. This is needed for the
349 if (!configuredDoc.isAuthenticated())
351 Connection conn = null;
355 // Setup and execute the count query. Special care needs to be take to ensure that the results will be based
356 // on a cursor so that large amounts of memory are not consumed when the query retrieve a large amount of
357 // data. Here's the relevant PostgreSQL documentation:
358 // http://jdbc.postgresql.org/documentation/83/query.html#query-with-cursor
359 ComboPooledDataSource cpds = configuredDoc.getCpds();
360 conn = cpds.getConnection();
361 conn.setAutoCommit(false);
362 st = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
363 String query = Glom.build_sql_select_count_simple(table, layoutFields);
364 // TODO Test execution time of this query with when the number of rows in the table is large (say >
365 // 1,000,000). Test memory usage at the same time (see the todo item in getTableData()).
366 rs = st.executeQuery(query);
368 // get the number of rows in the query
370 tableInfo.setNumRows(rs.getInt(1));
372 } catch (SQLException e) {
373 Log.error(documentTitle + " - " + table
374 + ": Error calculating number of rows in the query. Setting number of rows to 0.", e);
375 tableInfo.setNumRows(0);
377 // cleanup everything that has been used
385 } catch (Exception e) {
386 Log.error(documentTitle + " - " + table
387 + ": Error closing database resources. Subsequent database queries may not work.", e);
394 public ArrayList<GlomField[]> getTableData(String documentTitle, String tableName, int start, int length) {
395 return getTableData(documentTitle, tableName, start, length, false, 0, false);
398 public ArrayList<GlomField[]> getSortedTableData(String documentTitle, String tableName, int start, int length,
399 int sortColumnIndex, boolean isAscending) {
400 return getTableData(documentTitle, tableName, start, length, true, sortColumnIndex, isAscending);
403 private ArrayList<GlomField[]> getTableData(String documentTitle, String tableName, int start, int length,
404 boolean useSortClause, int sortColumnIndex, boolean isAscending) {
406 ConfiguredDocument configuredDoc = documents.get(documentTitle);
407 Document document = configuredDoc.getDocument();
409 // access the layout list using the defined layout list or the table fields if there's no layout list
410 LayoutGroupVector layoutListVec = document.get_data_layout_groups("list", tableName);
411 LayoutFieldVector layoutFields = new LayoutFieldVector();
412 SortClause sortClause = new SortClause();
413 int listViewLayoutGroupSize = safeLongToInt(layoutListVec.size());
414 if (layoutListVec.size() > 0) {
415 // a layout list is defined, we can use it to for the LayoutListTable
416 if (listViewLayoutGroupSize > 1)
417 Log.warn(documentTitle + ": The size of the list view layout group for table " + tableName
418 + " is greater than 1. Attempting to use the first item for the layout list view.");
419 LayoutItemVector layoutItemsVec = layoutListVec.get(0).get_items();
421 // find the defined layout list fields
422 int numItems = safeLongToInt(layoutItemsVec.size());
423 for (int i = 0; i < numItems; i++) {
424 // TODO add support for other LayoutItems (Text, Image, Button)
425 LayoutItem item = layoutItemsVec.get(i);
426 LayoutItem_Field layoutItemfield = LayoutItem_Field.cast_dynamic(item);
427 if (layoutItemfield != null) {
428 // use this field in the layout
429 layoutFields.add(layoutItemfield);
431 // create a sort clause if it's a primary key and we're not asked to sort a specific column
432 if (!useSortClause) {
433 Field details = layoutItemfield.get_full_field_details();
434 if (details != null && details.get_primary_key()) {
435 sortClause.addLast(new SortFieldPair(layoutItemfield, true)); // ascending
441 // no layout list is defined, use the table fields as the layout list
442 FieldVector fieldsVec = document.get_table_fields(tableName);
444 // find the fields to display in the layout list
445 int numItems = safeLongToInt(fieldsVec.size());
446 for (int i = 0; i < numItems; i++) {
447 Field field = fieldsVec.get(i);
448 LayoutItem_Field layoutItemField = new LayoutItem_Field();
449 layoutItemField.set_full_field_details(field);
450 layoutFields.add(layoutItemField);
452 // create a sort clause if it's a primary key and we're not asked to sort a specific column
453 if (!useSortClause) {
454 if (field.get_primary_key()) {
455 sortClause.addLast(new SortFieldPair(layoutItemField, true)); // ascending
461 // create a sort clause for the column we've been asked to sort
463 LayoutItem item = layoutFields.get(sortColumnIndex);
464 LayoutItem_Field field = LayoutItem_Field.cast_dynamic(item);
466 sortClause.addLast(new SortFieldPair(field, isAscending));
468 Log.error(documentTitle + " - " + tableName + ": Error getting LayoutItem_Field for column index "
469 + sortColumnIndex + ". Cannot create a sort clause for this column.");
474 ArrayList<GlomField[]> rowsList = new ArrayList<GlomField[]>();
475 if (!configuredDoc.isAuthenticated())
477 Connection conn = null;
481 // Setup and execute the query. Special care needs to be take to ensure that the results will be based on a
482 // cursor so that large amounts of memory are not consumed when the query retrieve a large amount of data.
483 // Here's the relevant PostgreSQL documentation:
484 // http://jdbc.postgresql.org/documentation/83/query.html#query-with-cursor
485 ComboPooledDataSource cpds = configuredDoc.getCpds();
486 conn = cpds.getConnection();
487 conn.setAutoCommit(false);
488 st = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
489 st.setFetchSize(length);
490 String query = Glom.build_sql_select_simple(tableName, layoutFields, sortClause) + " OFFSET " + start;
491 // TODO Test memory usage before and after we execute the query that would result in a large ResultSet.
492 // We need to ensure that the JDBC driver is in fact returning a cursor based result set that has a low
493 // memory footprint. Check the difference between this value before and after the query:
494 // Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()
495 // Test the execution time at the same time (see the todo item in getLayoutListTable()).
496 rs = st.executeQuery(query);
498 // get the data we've been asked for
500 while (rs.next() && rowCount <= length) {
501 int layoutFieldsSize = safeLongToInt(layoutFields.size());
502 GlomField[] rowArray = new GlomField[layoutFieldsSize];
503 for (int i = 0; i < layoutFieldsSize; i++) {
504 // make a new GlomField to set the text and colours
505 rowArray[i] = new GlomField();
507 // get foreground and background colours
508 LayoutItem_Field field = layoutFields.get(i);
509 FieldFormatting formatting = field.get_formatting_used();
510 String fgcolour = formatting.get_text_format_color_foreground();
511 if (!fgcolour.isEmpty())
512 rowArray[i].setFGColour(convertGdkColorToHtmlColour(fgcolour));
513 String bgcolour = formatting.get_text_format_color_background();
514 if (!bgcolour.isEmpty())
515 rowArray[i].setBGColour(convertGdkColorToHtmlColour(bgcolour));
517 // Convert the field value to a string based on the glom type. We're doing the formatting on the
518 // server side for now but it might be useful to move this to the client side.
519 switch (field.get_glom_type()) {
521 String text = rs.getString(i + 1);
522 rowArray[i].setText(text != null ? text : "");
525 rowArray[i].setBoolean(rs.getBoolean(i + 1));
528 // Take care of the numeric formatting before converting the number to a string.
529 NumericFormat numFormatGlom = formatting.getM_numeric_format();
530 // There's no isCurrency() method in the glom NumericFormat class so we're assuming that the
531 // number should be formatted as a currency if the currency code string is not empty.
532 String currencyCode = numFormatGlom.getM_currency_symbol();
533 NumberFormat numFormatJava = null;
534 boolean useGlomCurrencyCode = false;
535 if (currencyCode.length() == 3) {
536 // Try to format the currency using the Java Locales system.
538 Currency currency = Currency.getInstance(currencyCode);
539 Log.info(documentTitle
542 + ": A valid ISO 4217 currency code is being used. Overriding the numeric formatting with information from the locale.");
543 int digits = currency.getDefaultFractionDigits();
544 numFormatJava = NumberFormat.getCurrencyInstance(locale);
545 numFormatJava.setCurrency(currency);
546 numFormatJava.setMinimumFractionDigits(digits);
547 numFormatJava.setMaximumFractionDigits(digits);
548 } catch (IllegalArgumentException e) {
549 Log.warn(documentTitle
554 + " is not a valid ISO 4217 code. Manually setting currency code with this value.");
555 // The currency code is not this is not an ISO 4217 currency code.
556 // We're going to manually set the currency code and use the glom numeric formatting.
557 useGlomCurrencyCode = true;
558 numFormatJava = getJavaNumberFormat(numFormatGlom);
560 } else if (currencyCode.length() > 0) {
561 Log.warn(documentTitle + " - " + tableName + ": " + currencyCode
562 + " is not a valid ISO 4217 code. Manually setting currency code with this value.");
563 // The length of the currency code is > 0 and != 3; this is not an ISO 4217 currency code.
564 // We're going to manually set the currency code and use the glom numeric formatting.
565 useGlomCurrencyCode = true;
566 numFormatJava = getJavaNumberFormat(numFormatGlom);
568 // The length of the currency code is 0; the number is not a currency.
569 numFormatJava = getJavaNumberFormat(numFormatGlom);
572 // TODO: Do I need to do something with NumericFormat.get_default_precision() from libglom?
574 double number = rs.getDouble(i + 1);
576 if (formatting.getM_numeric_format().getM_alt_foreground_color_for_negatives())
577 // overrides the set foreground colour
578 rowArray[i].setFGColour(convertGdkColorToHtmlColour(NumericFormat
579 .get_alternative_color_for_negatives()));
582 // Finally convert the number to text using the glom currency string if required.
583 if (useGlomCurrencyCode) {
584 rowArray[i].setText(currencyCode + " " + numFormatJava.format(number));
586 rowArray[i].setText(numFormatJava.format(number));
590 Date date = rs.getDate(i + 1);
592 DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
593 rowArray[i].setText(dateFormat.format(date));
595 rowArray[i].setText("");
599 Time time = rs.getTime(i + 1);
601 DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM, locale);
602 rowArray[i].setText(timeFormat.format(time));
604 rowArray[i].setText("");
608 byte[] image = rs.getBytes(i + 1);
610 // TODO implement field TYPE_IMAGE
611 rowArray[i].setText("Image (FIXME)");
613 rowArray[i].setText("");
618 Log.warn(documentTitle + " - " + tableName
619 + ": Invalid LayoutItem Field type. Using empty string for value.");
620 rowArray[i].setText("");
625 // add the row of GlomFields to the ArrayList we're going to return and update the row count
626 rowsList.add(rowArray);
629 } catch (SQLException e) {
630 Log.error(documentTitle + " - " + tableName + ": Error executing database query.", e);
631 // TODO: somehow notify user of problem
633 // cleanup everything that has been used
641 } catch (Exception e) {
642 Log.error(documentTitle + " - " + tableName
643 + ": Error closing database resources. Subsequent database queries may not work.", e);
649 public ArrayList<String> getDocumentTitles() {
650 ArrayList<String> documentTitles = new ArrayList<String>();
651 for (String title : documents.keySet()) {
652 documentTitles.add(title);
654 return documentTitles;
658 * This method safely converts longs from libglom into ints. This method was taken from stackoverflow:
660 * http://stackoverflow.com/questions/1590831/safely-casting-long-to-int-in-java
662 private int safeLongToInt(long value) {
663 if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) {
664 throw new IllegalArgumentException(value + " cannot be cast to int without changing its value.");
669 private NumberFormat getJavaNumberFormat(NumericFormat numFormatGlom) {
670 NumberFormat numFormatJava = NumberFormat.getInstance(locale);
671 if (numFormatGlom.getM_decimal_places_restricted()) {
672 int digits = safeLongToInt(numFormatGlom.getM_decimal_places());
673 numFormatJava.setMinimumFractionDigits(digits);
674 numFormatJava.setMaximumFractionDigits(digits);
676 numFormatJava.setGroupingUsed(numFormatGlom.getM_use_thousands_separator());
677 return numFormatJava;
681 * Converts a Gdk::Color (16-bits per channel) to an HTML colour (8-bits per channel) by discarding the least
682 * significant 8-bits in each channel.
684 private String convertGdkColorToHtmlColour(String gdkColor) {
685 if (gdkColor.length() == 13)
686 return gdkColor.substring(0, 3) + gdkColor.substring(5, 7) + gdkColor.substring(9, 11);
687 else if (gdkColor.length() == 7) {
688 // This shouldn't happen but let's deal with it if it does.
689 Log.warn("convertGdkColorToHtmlColour(): Expected a 13 character string but received a 7 character string. Returning received string.");
692 Log.error("convertGdkColorToHtmlColour(): Did not receive a 13 or 7 character string. Returning black HTML colour code.");
698 * This method converts a FieldFormatting.HorizontalAlignment to the equivalent ColumnInfo.HorizontalAlignment. The
699 * need for this comes from the fact that the GWT HorizontalAlignment classes can't be used with RPC and there's no
700 * easy way to use the java-libglom FieldFormatting.HorizontalAlignment enum with RPC. An enum identical to
701 * FieldFormatting.HorizontalAlignment is included in the ColumnInfo class.
703 private ColumnInfo.HorizontalAlignment getColumnInfoHorizontalAlignment(
704 FieldFormatting.HorizontalAlignment alignment) {
706 case HORIZONTAL_ALIGNMENT_AUTO:
707 return ColumnInfo.HorizontalAlignment.HORIZONTAL_ALIGNMENT_AUTO;
708 case HORIZONTAL_ALIGNMENT_LEFT:
709 return ColumnInfo.HorizontalAlignment.HORIZONTAL_ALIGNMENT_LEFT;
710 case HORIZONTAL_ALIGNMENT_RIGHT:
711 return ColumnInfo.HorizontalAlignment.HORIZONTAL_ALIGNMENT_RIGHT;
713 Log.error("getColumnInfoGlomFieldType(): Recieved an alignment that I don't know about: "
714 + FieldFormatting.HorizontalAlignment.class.getName() + "." + alignment.toString() + ". Returning "
715 + ColumnInfo.HorizontalAlignment.HORIZONTAL_ALIGNMENT_RIGHT.toString() + ".");
716 return ColumnInfo.HorizontalAlignment.HORIZONTAL_ALIGNMENT_RIGHT;
721 * This method converts a Field.glom_field_type to the equivalent ColumnInfo.FieldType. The need for this comes from
722 * the fact that the GWT FieldType classes can't be used with RPC and there's no easy way to use the java-libglom
723 * Field.glom_field_type enum with RPC. An enum identical to FieldFormatting.glom_field_type is included in the
726 private ColumnInfo.GlomFieldType getColumnInfoGlomFieldType(Field.glom_field_type type) {
729 return ColumnInfo.GlomFieldType.TYPE_BOOLEAN;
731 return ColumnInfo.GlomFieldType.TYPE_DATE;
733 return ColumnInfo.GlomFieldType.TYPE_IMAGE;
735 return ColumnInfo.GlomFieldType.TYPE_NUMERIC;
737 return ColumnInfo.GlomFieldType.TYPE_TEXT;
739 return ColumnInfo.GlomFieldType.TYPE_TIME;
741 Log.info("getColumnInfoGlomFieldType(): Returning TYPE_INVALID.");
742 return ColumnInfo.GlomFieldType.TYPE_INVALID;
744 Log.error("getColumnInfoGlomFieldType(): Recieved a type that I don't know about: "
745 + Field.glom_field_type.class.getName() + "." + type.toString() + ". Returning "
746 + ColumnInfo.GlomFieldType.TYPE_INVALID.toString() + ".");
747 return ColumnInfo.GlomFieldType.TYPE_INVALID;
754 * @see org.glom.web.client.OnlineGlomService#isAuthenticated(java.lang.String)
756 public boolean isAuthenticated(String documentTitle) {
757 return documents.get(documentTitle).isAuthenticated();
763 * @see org.glom.web.client.OnlineGlomService#checkAuthentication(java.lang.String, java.lang.String,
766 public boolean checkAuthentication(String documentTitle, String username, String password) {
767 ConfiguredDocument configuredDoc = documents.get(documentTitle);
768 boolean authenticated;
770 authenticated = checkAuthentication(documentTitle, configuredDoc.getCpds(), username, password);
771 } catch (SQLException e) {
775 configuredDoc.setAuthenticated(authenticated);
776 return authenticated;
782 * @see org.glom.web.client.OnlineGlomService#getDetailsLayoutGroup(java.lang.String, java.lang.String)
784 public LayoutGroup getDetailsLayoutGroup(String documentTitle, String tableName) {
785 // FIXME not checking if authenticated
786 ConfiguredDocument configuredDoc = documents.get(documentTitle);
787 Document document = configuredDoc.getDocument();
788 LayoutGroupVector layoutGroupsVec = document.get_data_layout_groups("details", tableName);
789 org.glom.libglom.LayoutGroup libGlomLayoutGroup = layoutGroupsVec.get(0);
791 LayoutGroup layoutGroup = new LayoutGroup();
792 if (libGlomLayoutGroup == null)
795 layoutGroup.setTitle(libGlomLayoutGroup.get_title());
797 return getLayoutGroup(documentTitle, tableName, libGlomLayoutGroup);
801 * Gets a GWT-Glom LayoutGroup object for the specified libglom LayoutGroup object.
803 * @param libglomLayoutGroup
804 * <dt><b>Precondition:</b>
806 * libglomLayoutGroup must not be null
809 private LayoutGroup getLayoutGroup(String documentTitle, String tableName,
810 org.glom.libglom.LayoutGroup libglomLayoutGroup) {
811 LayoutGroup layoutGroup = new LayoutGroup();
812 layoutGroup.setColumnCount(safeLongToInt(libglomLayoutGroup.get_columns_count()));
814 // look at each child item
815 LayoutItemVector layoutItemsVec = libglomLayoutGroup.get_items();
816 for (int i = 0; i < layoutItemsVec.size(); i++) {
817 org.glom.libglom.LayoutItem libglomLayoutItem = layoutItemsVec.get(i);
819 // just a safety check
820 if (libglomLayoutItem == null)
823 org.glom.web.shared.layout.LayoutItem layoutItem = null;
824 org.glom.libglom.LayoutGroup group = org.glom.libglom.LayoutGroup.cast_dynamic(libglomLayoutItem);
826 // recurse into child groups
827 layoutItem = getLayoutGroup(documentTitle, tableName, group);
829 // create GWT-Glom LayoutItem types based on the the libglom type
830 String partTypeName = libglomLayoutItem.get_part_type_name();
831 if ("Field".equals(partTypeName)) {
832 layoutItem = new LayoutItemField();
834 Log.warn(documentTitle + " - " + tableName
835 + "- getLayoutGroup(): Ignoring unknown LayoutItem of type: " + partTypeName);
840 layoutItem.setTitle(libglomLayoutItem.get_title_original());
841 layoutGroup.addItem(layoutItem);
850 * @see org.glom.web.client.OnlineGlomService#getDefaultDetailsLayoutGroup(java.lang.String)
853 public LayoutGroup getDefaultDetailsLayoutGroup(String documentTitle) {
854 GlomDocument glomDocument = getGlomDocument(documentTitle);
855 String tableName = glomDocument.getTableNames().get(glomDocument.getDefaultTableIndex());
856 return getDetailsLayoutGroup(documentTitle, tableName);