diff --git a/src/adql/db/DBChecker.java b/src/adql/db/DBChecker.java index aec19a4ad6f5963b2727e0df72154b3ec5a37e5a..90841974a4f220bb4070c6ce71cbdce06d1e77ac 100644 --- a/src/adql/db/DBChecker.java +++ b/src/adql/db/DBChecker.java @@ -23,7 +23,6 @@ import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; - import adql.db.exception.UnresolvedColumnException; import adql.db.exception.UnresolvedIdentifiersException; import adql.db.exception.UnresolvedTableException; @@ -71,7 +70,6 @@ public class DBChecker implements QueryChecker { /** List of all available tables ({@link DBTable}). */ protected SearchTableList lstTables; - /* ************ */ /* CONSTRUCTORS */ /* ************ */ @@ -91,7 +89,6 @@ public class DBChecker implements QueryChecker { setTables(tables); } - /* ****** */ /* SETTER */ /* ****** */ @@ -114,7 +111,6 @@ public class DBChecker implements QueryChecker { lstTables = new SearchTableList(tables); } - /* ************* */ /* CHECK METHODS */ /* ************* */ @@ -166,9 +162,9 @@ public class DBChecker implements QueryChecker { * @see #resolveColumn(ADQLColumn, SearchColumnList) * @see #checkColumnReference(ColumnReference, ClauseSelect, SearchColumnList) */ - public void check(final ADQLQuery query) throws ParseException { + public void check(final ADQLQuery query) throws ParseException{ UnresolvedIdentifiersException errors = new UnresolvedIdentifiersException(); - HashMap<DBTable, ADQLTable> mapTables = new HashMap<DBTable, ADQLTable>(); + HashMap<DBTable,ADQLTable> mapTables = new HashMap<DBTable,ADQLTable>(); ISearchHandler sHandler; // Check the existence of all tables: @@ -276,7 +272,7 @@ public class DBChecker implements QueryChecker { * * @throws ParseException An {@link UnresolvedTableException} if the given table can't be resolved. */ - protected DBTable resolveTable(final ADQLTable table) throws ParseException { + protected DBTable resolveTable(final ADQLTable table) throws ParseException{ ArrayList<DBTable> tables = lstTables.search(table); // good if only one table has been found: @@ -284,7 +280,7 @@ public class DBChecker implements QueryChecker { return tables.get(0); // but if more than one: ambiguous table name ! else if (tables.size() > 1) - throw new UnresolvedTableException(table, tables.get(0).getADQLSchemaName()+"."+tables.get(0).getADQLName(), tables.get(1).getADQLSchemaName()+"."+tables.get(1).getADQLName()); + throw new UnresolvedTableException(table, tables.get(0).getADQLSchemaName() + "." + tables.get(0).getADQLName(), tables.get(1).getADQLSchemaName() + "." + tables.get(1).getADQLName()); // otherwise (no match): unknown table ! else throw new UnresolvedTableException(table); @@ -301,7 +297,7 @@ public class DBChecker implements QueryChecker { * @throws ParseException An {@link UnresolvedColumnException} if the given column can't be resolved * or an {@link UnresolvedTableException} if its table reference can't be resolved. */ - protected DBColumn resolveColumn(final ADQLColumn column, final SearchColumnList dbColumns) throws ParseException { + protected DBColumn resolveColumn(final ADQLColumn column, final SearchColumnList dbColumns) throws ParseException{ ArrayList<DBColumn> foundColumns = dbColumns.search(column); // good if only one column has been found: @@ -310,9 +306,9 @@ public class DBChecker implements QueryChecker { // but if more than one: ambiguous table reference ! else if (foundColumns.size() > 1){ if (column.getTableName() == null) - throw new UnresolvedColumnException(column, (foundColumns.get(0).getTable()==null)?"<NULL>":(foundColumns.get(0).getTable().getADQLName()+"."+foundColumns.get(0).getADQLName()), (foundColumns.get(1).getTable()==null)?"<NULL>":(foundColumns.get(1).getTable().getADQLName()+"."+foundColumns.get(1).getADQLName())); + throw new UnresolvedColumnException(column, (foundColumns.get(0).getTable() == null) ? "<NULL>" : (foundColumns.get(0).getTable().getADQLName() + "." + foundColumns.get(0).getADQLName()), (foundColumns.get(1).getTable() == null) ? "<NULL>" : (foundColumns.get(1).getTable().getADQLName() + "." + foundColumns.get(1).getADQLName())); else - throw new UnresolvedTableException(column, (foundColumns.get(0).getTable()==null)?"<NULL>":foundColumns.get(0).getTable().getADQLName(), (foundColumns.get(1).getTable()==null)?"<NULL>":foundColumns.get(1).getTable().getADQLName()); + throw new UnresolvedTableException(column, (foundColumns.get(0).getTable() == null) ? "<NULL>" : foundColumns.get(0).getTable().getADQLName(), (foundColumns.get(1).getTable() == null) ? "<NULL>" : foundColumns.get(1).getTable().getADQLName()); }// otherwise (no match): unknown column ! else throw new UnresolvedColumnException(column); @@ -334,17 +330,17 @@ public class DBChecker implements QueryChecker { * @see ClauseSelect#searchByAlias(String) * @see #resolveColumn(ADQLColumn, SearchColumnList) */ - protected DBColumn checkColumnReference(final ColumnReference colRef, final ClauseSelect select, final SearchColumnList dbColumns) throws ParseException { + protected DBColumn checkColumnReference(final ColumnReference colRef, final ClauseSelect select, final SearchColumnList dbColumns) throws ParseException{ if (colRef.isIndex()){ int index = colRef.getColumnIndex(); if (index > 0 && index <= select.size()){ - SelectItem item = select.get(index-1); + SelectItem item = select.get(index - 1); if (item.getOperand() instanceof ADQLColumn) return ((ADQLColumn)item.getOperand()).getDBLink(); else return null; }else - throw new ParseException("Column index out of bounds: "+index+" (must be between 1 and "+select.size()+") !"); + throw new ParseException("Column index out of bounds: " + index + " (must be between 1 and " + select.size() + ") !"); }else{ ADQLColumn col = new ADQLColumn(colRef.getColumnName()); col.setCaseSensitive(colRef.isCaseSensitive()); @@ -363,7 +359,6 @@ public class DBChecker implements QueryChecker { } } - /* ************************************* */ /* DBTABLE & DBCOLUMN GENERATION METHODS */ /* ************************************* */ @@ -378,7 +373,7 @@ public class DBChecker implements QueryChecker { * * @throws ParseException Can be used to explain why the table has not been found. */ - public static DBTable generateDBTable(final ADQLQuery subQuery, final String tableName) throws ParseException { + public static DBTable generateDBTable(final ADQLQuery subQuery, final String tableName) throws ParseException{ DefaultDBTable dbTable = new DefaultDBTable(tableName); DBColumn[] columns = subQuery.getResultingColumns(); @@ -388,7 +383,6 @@ public class DBChecker implements QueryChecker { return dbTable; } - /* *************** */ /* SEARCH HANDLERS */ /* *************** */ @@ -400,7 +394,7 @@ public class DBChecker implements QueryChecker { */ private static class SearchTableHandler extends SimpleSearchHandler { @Override - public boolean match(final ADQLObject obj) { + public boolean match(final ADQLObject obj){ return obj instanceof ADQLTable; } } @@ -426,7 +420,7 @@ public class DBChecker implements QueryChecker { */ private static class SearchColReferenceHandler extends SimpleSearchHandler { @Override - public boolean match(final ADQLObject obj) { + public boolean match(final ADQLObject obj){ return (obj instanceof ColumnReference); } } diff --git a/src/adql/db/DefaultDBColumn.java b/src/adql/db/DefaultDBColumn.java index 1f323dd27bf6c576f88f6f54658be0f1a39646de..8496501aa3ee7ecc3fb15619c8bddecafb98e3ef 100644 --- a/src/adql/db/DefaultDBColumn.java +++ b/src/adql/db/DefaultDBColumn.java @@ -63,7 +63,7 @@ public class DefaultDBColumn implements DBColumn { this.table = table; } - public final String getADQLName() { + public final String getADQLName(){ return adqlName; } @@ -72,11 +72,11 @@ public class DefaultDBColumn implements DBColumn { this.adqlName = adqlName; } - public final String getDBName() { + public final String getDBName(){ return dbName; } - public final DBTable getTable() { + public final DBTable getTable(){ return table; } diff --git a/src/adql/db/DefaultDBTable.java b/src/adql/db/DefaultDBTable.java index b4d321f8a9dd4d75582a58b4a753dfe6614e1a47..b26c668ddb5d2d16d493ce5cc737abf032ae206d 100644 --- a/src/adql/db/DefaultDBTable.java +++ b/src/adql/db/DefaultDBTable.java @@ -39,8 +39,7 @@ public class DefaultDBTable implements DBTable { protected String adqlSchemaName = null; protected String adqlName = null; - protected HashMap<String, DBColumn> columns = new HashMap<String, DBColumn>(); - + protected HashMap<String,DBColumn> columns = new HashMap<String,DBColumn>(); /** * <p>Builds a default {@link DBTable} with the given DB name.</p> @@ -111,9 +110,7 @@ public class DefaultDBTable implements DBTable { * @param dbName Database table name. * @param adqlName Table name used in ADQL queries. */ - public DefaultDBTable(final String dbCatName, final String adqlCatName - , final String dbSchemName, final String adqlSchemName - , final String dbName, final String adqlName){ + public DefaultDBTable(final String dbCatName, final String adqlCatName, final String dbSchemName, final String adqlSchemName, final String dbName, final String adqlName){ if (dbName == null || dbName.length() == 0) throw new NullPointerException("Missing DB name !"); @@ -128,40 +125,40 @@ public class DefaultDBTable implements DBTable { adqlCatalogName = adqlCatName; } - public final String getDBName() { + public final String getDBName(){ return dbName; } - public final String getDBSchemaName() { + public final String getDBSchemaName(){ return dbSchemaName; } - public final String getDBCatalogName() { + public final String getDBCatalogName(){ return dbCatalogName; } - public final String getADQLName() { + public final String getADQLName(){ return adqlName; } public void setADQLName(final String name){ - adqlName = (name != null)?name:dbName; + adqlName = (name != null) ? name : dbName; } - public final String getADQLSchemaName() { + public final String getADQLSchemaName(){ return adqlSchemaName; } public void setADQLSchemaName(final String name){ - adqlSchemaName = (name != null)?name:dbSchemaName; + adqlSchemaName = (name != null) ? name : dbSchemaName; } - public final String getADQLCatalogName() { + public final String getADQLCatalogName(){ return adqlCatalogName; } public void setADQLCatalogName(final String name){ - adqlName = (name != null)?null:dbName; + adqlName = (name != null) ? null : dbName; } /** @@ -170,7 +167,7 @@ public class DefaultDBTable implements DBTable { * * @see adql.db.DBTable#getColumn(java.lang.String, boolean) */ - public DBColumn getColumn(String colName, boolean byAdqlName) { + public DBColumn getColumn(String colName, boolean byAdqlName){ if (byAdqlName) return columns.get(colName); else{ @@ -182,11 +179,11 @@ public class DefaultDBTable implements DBTable { } } - public boolean hasColumn(String colName, boolean byAdqlName) { + public boolean hasColumn(String colName, boolean byAdqlName){ return (getColumn(colName, byAdqlName) != null); } - public Iterator<DBColumn> iterator() { + public Iterator<DBColumn> iterator(){ return columns.values().iterator(); } @@ -209,39 +206,39 @@ public class DefaultDBTable implements DBTable { * * @return A String array of 3 items: [0]=catalog, [1]=schema, [0]=table. */ - public static final String[] splitTableName(final String table) { - String[] splitRes = new String[]{null, null, null}; + public static final String[] splitTableName(final String table){ + String[] splitRes = new String[]{null,null,null}; if (table == null || table.trim().length() == 0) return splitRes; String[] names = table.trim().split("\\."); switch(names.length){ - case 1: - splitRes[2] = table.trim(); - break; - case 2: - splitRes[2] = names[1].trim(); - splitRes[1] = names[0].trim(); - break; - case 3: - splitRes[2] = names[2].trim(); - splitRes[1] = names[1].trim(); - splitRes[0] = names[0].trim(); - break; - default: - splitRes[2] = names[names.length-1].trim(); - splitRes[1] = names[names.length-2].trim(); - StringBuffer buff = new StringBuffer(names[0].trim()); - for(int i=1; i<names.length-2; i++) - buff.append('.').append(names[i].trim()); - splitRes[0] = buff.toString(); + case 1: + splitRes[2] = table.trim(); + break; + case 2: + splitRes[2] = names[1].trim(); + splitRes[1] = names[0].trim(); + break; + case 3: + splitRes[2] = names[2].trim(); + splitRes[1] = names[1].trim(); + splitRes[0] = names[0].trim(); + break; + default: + splitRes[2] = names[names.length - 1].trim(); + splitRes[1] = names[names.length - 2].trim(); + StringBuffer buff = new StringBuffer(names[0].trim()); + for(int i = 1; i < names.length - 2; i++) + buff.append('.').append(names[i].trim()); + splitRes[0] = buff.toString(); } return splitRes; } - public DBTable copy(final String dbName, final String adqlName) { + public DBTable copy(final String dbName, final String adqlName){ DefaultDBTable copy = new DefaultDBTable(dbName, adqlName); for(DBColumn col : this) copy.addColumn(col.copy(col.getDBName(), col.getADQLName(), copy)); diff --git a/src/adql/db/SearchColumnList.java b/src/adql/db/SearchColumnList.java index 03708df010e9192f63221b4cfb9a8cca3b311135..1149f379ad637815a8e48f5293c3380c5a6d02c9 100644 --- a/src/adql/db/SearchColumnList.java +++ b/src/adql/db/SearchColumnList.java @@ -53,11 +53,10 @@ public class SearchColumnList extends TextualSearchList<DBColumn> { private boolean distinct = false; /** Case-sensitive dictionary of table aliases. (tableAlias <-> TableName) */ - private final HashMap<String, String> tableAliases = new HashMap<String, String>(); + private final HashMap<String,String> tableAliases = new HashMap<String,String>(); /** Case-insensitive dictionary of table aliases. (tablealias <-> List<TableName>) */ - private final HashMap<String, ArrayList<String>> mapAliases = new HashMap<String, ArrayList<String>>(); - + private final HashMap<String,ArrayList<String>> mapAliases = new HashMap<String,ArrayList<String>>(); /* ************ */ /* CONSTRUCTORS */ @@ -65,7 +64,7 @@ public class SearchColumnList extends TextualSearchList<DBColumn> { /** * Void constructor. */ - public SearchColumnList() { + public SearchColumnList(){ super(new DBColumnKeyExtractor()); } @@ -74,7 +73,7 @@ public class SearchColumnList extends TextualSearchList<DBColumn> { * * @param collection Collection of {@link DBColumn} to copy. */ - public SearchColumnList(final Collection<DBColumn> collection) { + public SearchColumnList(final Collection<DBColumn> collection){ super(collection, new DBColumnKeyExtractor()); } @@ -83,11 +82,10 @@ public class SearchColumnList extends TextualSearchList<DBColumn> { * * @param initialCapacity Initial capacity of this list. */ - public SearchColumnList(final int initialCapacity) { + public SearchColumnList(final int initialCapacity){ super(initialCapacity, new DBColumnKeyExtractor()); } - /* ******* */ /* GETTERS */ /* ******* */ @@ -96,7 +94,7 @@ public class SearchColumnList extends TextualSearchList<DBColumn> { * * @return <i>true</i> means that multiple occurrences are allowed, <i>false</i> otherwise. */ - public final boolean isDistinct() { + public final boolean isDistinct(){ return distinct; } @@ -105,11 +103,10 @@ public class SearchColumnList extends TextualSearchList<DBColumn> { * * @param distinct <i>true</i> means that multiple occurrences are allowed, <i>false</i> otherwise. */ - public final void setDistinct(final boolean distinct) { + public final void setDistinct(final boolean distinct){ this.distinct = distinct; } - /* ********************** */ /* TABLE ALIAS MANAGEMENT */ /* ********************** */ @@ -228,7 +225,8 @@ public class SearchColumnList extends TextualSearchList<DBColumn> { DBTable dbTable = match.getTable(); if (IdentifierField.TABLE.isCaseSensitive(caseSensitivity)){ String tableName = tableAliases.get(table); - if (tableName == null) tableName = table; + if (tableName == null) + tableName = table; if (!dbTable.getADQLName().equals(tableName)) continue; }else{ @@ -239,7 +237,7 @@ public class SearchColumnList extends TextualSearchList<DBColumn> { }else{ boolean foundAlias = false; String temp; - for(int a=0; !foundAlias && a<aliases.size(); a++){ + for(int a = 0; !foundAlias && a < aliases.size(); a++){ temp = tableAliases.get(aliases.get(a)); if (temp != null) foundAlias = dbTable.getADQLName().equalsIgnoreCase(temp); @@ -277,7 +275,7 @@ public class SearchColumnList extends TextualSearchList<DBColumn> { // Special case: the columns merged by a NATURAL JOIN or a USING may have no table reference: if (tmpResult.size() > 1){ ArrayList<DBColumn> result = new ArrayList<DBColumn>(tmpResult.size()); - for(int i=0; i<tmpResult.size(); i++){ + for(int i = 0; i < tmpResult.size(); i++){ if (tmpResult.get(i).getTable() == null) result.add(tmpResult.remove(i)); } @@ -289,12 +287,11 @@ public class SearchColumnList extends TextualSearchList<DBColumn> { } } - /* ***************** */ /* INHERITED METHODS */ /* ***************** */ @Override - public boolean add(final DBColumn item) { + public boolean add(final DBColumn item){ if (distinct && contains(item)) return false; else @@ -302,13 +299,13 @@ public class SearchColumnList extends TextualSearchList<DBColumn> { } @Override - public boolean addAll(final Collection<? extends DBColumn> c) { + public boolean addAll(final Collection<? extends DBColumn> c){ boolean changed = super.addAll(c); if (changed){ if (c instanceof SearchColumnList){ SearchColumnList list = (SearchColumnList)c; - for(Map.Entry<String, String> entry : list.tableAliases.entrySet()) + for(Map.Entry<String,String> entry : list.tableAliases.entrySet()) putTableAlias(entry.getKey(), entry.getValue()); } } @@ -317,7 +314,7 @@ public class SearchColumnList extends TextualSearchList<DBColumn> { } @Override - public boolean removeAll(final Collection<?> c) { + public boolean removeAll(final Collection<?> c){ boolean changed = super.removeAll(c); if (changed){ @@ -331,7 +328,6 @@ public class SearchColumnList extends TextualSearchList<DBColumn> { return changed; } - /** * Lets extracting the key to associate with a given {@link DBColumn} instance. * @@ -339,7 +335,7 @@ public class SearchColumnList extends TextualSearchList<DBColumn> { * @version 09/2011 */ private static class DBColumnKeyExtractor implements KeyExtractor<DBColumn> { - public String getKey(DBColumn obj) { + public String getKey(DBColumn obj){ return obj.getADQLName(); } } diff --git a/src/adql/db/SearchTableList.java b/src/adql/db/SearchTableList.java index ef6caca91d5e8f0681c9ec29efd5243fcdd8cacd..649b4fd60b6962c2d304353bada4506704506988 100644 --- a/src/adql/db/SearchTableList.java +++ b/src/adql/db/SearchTableList.java @@ -43,14 +43,13 @@ public class SearchTableList extends TextualSearchList<DBTable> { /** Indicates whether multiple occurrences are allowed. */ private boolean distinct = false; - /* ************ */ /* CONSTRUCTORS */ /* ************ */ /** * Void constructor. */ - public SearchTableList() { + public SearchTableList(){ super(new DBTableKeyExtractor()); } @@ -59,7 +58,7 @@ public class SearchTableList extends TextualSearchList<DBTable> { * * @param collection Collection of {@link DBTable} to copy. */ - public SearchTableList(final Collection<DBTable> collection) { + public SearchTableList(final Collection<DBTable> collection){ super(collection, new DBTableKeyExtractor()); } @@ -68,11 +67,10 @@ public class SearchTableList extends TextualSearchList<DBTable> { * * @param initialCapacity Initial capacity of this list. */ - public SearchTableList(final int initialCapacity) { + public SearchTableList(final int initialCapacity){ super(initialCapacity, new DBTableKeyExtractor()); } - /* ******* */ /* GETTERS */ /* ******* */ @@ -81,7 +79,7 @@ public class SearchTableList extends TextualSearchList<DBTable> { * * @return <i>true</i> means that multiple occurrences are allowed, <i>false</i> otherwise. */ - public final boolean isDistinct() { + public final boolean isDistinct(){ return distinct; } @@ -90,7 +88,7 @@ public class SearchTableList extends TextualSearchList<DBTable> { * * @param distinct <i>true</i> means that multiple occurrences are allowed, <i>false</i> otherwise. */ - public final void setDistinct(final boolean distinct) { + public final void setDistinct(final boolean distinct){ this.distinct = distinct; } @@ -183,19 +181,17 @@ public class SearchTableList extends TextualSearchList<DBTable> { return tmpResult; } - /* ***************** */ /* INHERITED METHODS */ /* ***************** */ @Override - public boolean add(final DBTable item) { + public boolean add(final DBTable item){ if (distinct && contains(item)) return false; else return super.add(item); } - /** * Lets extracting a key to associate with a given {@link DBTable} instance. * @@ -203,7 +199,7 @@ public class SearchTableList extends TextualSearchList<DBTable> { * @version 09/2011 */ private static class DBTableKeyExtractor implements KeyExtractor<DBTable> { - public String getKey(DBTable obj) { + public String getKey(DBTable obj){ return obj.getADQLName(); } } diff --git a/src/adql/db/exception/UnresolvedColumnException.java b/src/adql/db/exception/UnresolvedColumnException.java index ed196bd1ee7826c23a2c6c953277179f842744f9..dffd8f6c1c4bd267c3d42b09f954683ebd246ea9 100644 --- a/src/adql/db/exception/UnresolvedColumnException.java +++ b/src/adql/db/exception/UnresolvedColumnException.java @@ -50,7 +50,7 @@ public class UnresolvedColumnException extends ParseException { public UnresolvedColumnException(ADQLColumn c){ super(buildMessage("Unknown column", c)); initPosition(c); - columnName = (c!=null)?c.getColumnName():null; + columnName = (c != null) ? c.getColumnName() : null; } /** @@ -68,7 +68,7 @@ public class UnresolvedColumnException extends ParseException { public UnresolvedColumnException(ADQLColumn c, String col1, String col2){ super(buildMessage("Ambiguous column name", c, col1, col2)); initPosition(c); - columnName = (c!=null)?c.getColumnName():null; + columnName = (c != null) ? c.getColumnName() : null; } protected final void initPosition(final ADQLColumn c){ diff --git a/src/adql/db/exception/UnresolvedIdentifiersException.java b/src/adql/db/exception/UnresolvedIdentifiersException.java index 8c3fa7775d4b93d216e06f23895ea78032d7aef1..b141befb55700ffa2a51f0d39fcba06d58d61d0f 100644 --- a/src/adql/db/exception/UnresolvedIdentifiersException.java +++ b/src/adql/db/exception/UnresolvedIdentifiersException.java @@ -51,7 +51,7 @@ public class UnresolvedIdentifiersException extends ParseException implements It /** * Build an empty {@link UnresolvedIdentifiersException} (that's to say: there is no unresolved identifier). */ - public UnresolvedIdentifiersException() { + public UnresolvedIdentifiersException(){ exceptions = new ArrayList<ParseException>(); } @@ -66,11 +66,11 @@ public class UnresolvedIdentifiersException extends ParseException implements It if (pe instanceof UnresolvedColumnException){ String colName = ((UnresolvedColumnException)pe).getColumnName(); if (colName != null && !colName.trim().isEmpty()) - addIdentifierName(colName+" "+pe.getPosition()); + addIdentifierName(colName + " " + pe.getPosition()); }else if (pe instanceof UnresolvedTableException){ String tableName = ((UnresolvedTableException)pe).getTableName(); if (tableName != null && !tableName.trim().isEmpty()) - addIdentifierName(tableName+" "+pe.getPosition()); + addIdentifierName(tableName + " " + pe.getPosition()); }else if (pe instanceof UnresolvedIdentifiersException) addIdentifierName(((UnresolvedIdentifiersException)pe).unresolvedIdentifiers); } @@ -119,10 +119,8 @@ public class UnresolvedIdentifiersException extends ParseException implements It * @see java.lang.Throwable#getMessage() */ @Override - public String getMessage() { - return exceptions.size()+" unresolved identifiers"+((unresolvedIdentifiers!=null)?(": "+unresolvedIdentifiers):"")+" !"; + public String getMessage(){ + return exceptions.size() + " unresolved identifiers" + ((unresolvedIdentifiers != null) ? (": " + unresolvedIdentifiers) : "") + " !"; } - - } diff --git a/src/adql/db/exception/UnresolvedTableException.java b/src/adql/db/exception/UnresolvedTableException.java index 6a8a985fbf089c80fc63aa4d93a25371ce6b2808..f08e629a15275c7b348c9685dafe1e5886edca71 100644 --- a/src/adql/db/exception/UnresolvedTableException.java +++ b/src/adql/db/exception/UnresolvedTableException.java @@ -50,10 +50,10 @@ public class UnresolvedTableException extends ParseException { * * @param table The unresolved {@link ADQLTable}. */ - public UnresolvedTableException(ADQLTable table) { + public UnresolvedTableException(ADQLTable table){ super(buildMessage("Unknown table", table)); initPosition(table); - tableName = (table!=null)?table.getTableName():null; + tableName = (table != null) ? table.getTableName() : null; } /** @@ -71,7 +71,7 @@ public class UnresolvedTableException extends ParseException { public UnresolvedTableException(ADQLTable table, String t1, String t2){ super(buildMessage("Ambiguous table name", table, t1, t2)); initPosition(table); - tableName = (table!=null)?table.getTableName():null; + tableName = (table != null) ? table.getTableName() : null; } /** @@ -93,7 +93,7 @@ public class UnresolvedTableException extends ParseException { public UnresolvedTableException(ADQLColumn column){ super(buildMessage("Unknown table reference", column)); initPosition(column); - tableName = (column!=null)?column.getTableName():null; + tableName = (column != null) ? column.getTableName() : null; } /** @@ -111,7 +111,7 @@ public class UnresolvedTableException extends ParseException { public UnresolvedTableException(ADQLColumn column, String table1, String table2){ super(buildMessage("Ambiguous table reference", column, table1, table2)); initPosition(column); - tableName = (column!=null)?column.getTableName():null; + tableName = (column != null) ? column.getTableName() : null; } protected final void initPosition(ADQLColumn column){ @@ -125,7 +125,7 @@ public class UnresolvedTableException extends ParseException { if (t.isSubQuery()) msg.append(t.getAlias()).append("\" !"); else - msg.append(t.getFullTableName()).append("\"").append(t.hasAlias()?(" (alias "+t.getAlias()+")"):"").append(" !"); + msg.append(t.getFullTableName()).append("\"").append(t.hasAlias() ? (" (alias " + t.getAlias() + ")") : "").append(" !"); return msg.toString(); } @@ -157,7 +157,7 @@ public class UnresolvedTableException extends ParseException { return buildMessage(msgStart, c); } - public final String getTableName() { + public final String getTableName(){ return tableName; } diff --git a/src/adql/parser/ADQLParser.java b/src/adql/parser/ADQLParser.java index 47e2cd265a68b9daa3fe7c1fee52fdda3e78236a..cd0c151497b4e6f6d7397abe30c4142261f8bacf 100644 --- a/src/adql/parser/ADQLParser.java +++ b/src/adql/parser/ADQLParser.java @@ -81,7 +81,7 @@ public class ADQLParser implements ADQLParserConstants { * @param checker The object to use to check each ADQLQuery. * @param factory The object to use to build an object representation of the given ADQL query. */ - public ADQLParser(QueryChecker checker, ADQLQueryFactory factory) { + public ADQLParser(QueryChecker checker, ADQLQueryFactory factory){ this(); queryChecker = checker; @@ -95,7 +95,7 @@ public class ADQLParser implements ADQLParserConstants { * * @param checker The object to use to check each ADQLQuery. */ - public ADQLParser(QueryChecker checker) { + public ADQLParser(QueryChecker checker){ this(checker, null); } @@ -104,7 +104,7 @@ public class ADQLParser implements ADQLParserConstants { * * @param factory The object to use to build an object representation of the given ADQL query. */ - public ADQLParser(ADQLQueryFactory factory) { + public ADQLParser(ADQLQueryFactory factory){ this((QueryChecker)null, factory); } @@ -115,7 +115,7 @@ public class ADQLParser implements ADQLParserConstants { * @param checker The object to use to check each ADQLQuery. * @param factory The object to use to build an object representation of the given ADQL query. */ - public ADQLParser(java.io.InputStream stream, QueryChecker checker, ADQLQueryFactory factory) { + public ADQLParser(java.io.InputStream stream, QueryChecker checker, ADQLQueryFactory factory){ this(stream); queryChecker = checker; @@ -130,7 +130,7 @@ public class ADQLParser implements ADQLParserConstants { * @param stream The stream in which the ADQL query to parse is given. * @param checker The object to use to check each ADQLQuery. */ - public ADQLParser(java.io.InputStream stream, QueryChecker checker) { + public ADQLParser(java.io.InputStream stream, QueryChecker checker){ this(stream, checker, null); } @@ -140,7 +140,7 @@ public class ADQLParser implements ADQLParserConstants { * @param stream The stream in which the ADQL query to parse is given. * @param factory The object to use to build an object representation of the given ADQL query. */ - public ADQLParser(java.io.InputStream stream, ADQLQueryFactory factory) { + public ADQLParser(java.io.InputStream stream, ADQLQueryFactory factory){ this(stream, (QueryChecker)null, factory); } @@ -152,7 +152,7 @@ public class ADQLParser implements ADQLParserConstants { * @param checker The object to use to check each ADQLQuery. * @param factory The object to use to build an object representation of the given ADQL query. */ - public ADQLParser(java.io.InputStream stream, String encoding, QueryChecker checker, ADQLQueryFactory factory) { + public ADQLParser(java.io.InputStream stream, String encoding, QueryChecker checker, ADQLQueryFactory factory){ this(stream, encoding); queryChecker = checker; @@ -168,7 +168,7 @@ public class ADQLParser implements ADQLParserConstants { * @param encoding The supplied encoding. * @param checker The object to use to check each ADQLQuery. */ - public ADQLParser(java.io.InputStream stream, String encoding, QueryChecker checker) { + public ADQLParser(java.io.InputStream stream, String encoding, QueryChecker checker){ this(stream, encoding, checker, null); } @@ -179,7 +179,7 @@ public class ADQLParser implements ADQLParserConstants { * @param encoding The supplied encoding. * @param factory The object to use to build an object representation of the given ADQL query. */ - public ADQLParser(java.io.InputStream stream, String encoding, ADQLQueryFactory factory) { + public ADQLParser(java.io.InputStream stream, String encoding, ADQLQueryFactory factory){ this(stream, encoding, null, factory); } @@ -190,7 +190,7 @@ public class ADQLParser implements ADQLParserConstants { * @param checker The object to use to check each ADQLQuery. * @param factory The object to use to build an object representation of the given ADQL query. */ - public ADQLParser(java.io.Reader reader, QueryChecker checker, ADQLQueryFactory factory) { + public ADQLParser(java.io.Reader reader, QueryChecker checker, ADQLQueryFactory factory){ this(reader); queryChecker = checker; @@ -205,7 +205,7 @@ public class ADQLParser implements ADQLParserConstants { * @param reader The reader in which the ADQL query to parse is given. * @param checker The object to use to check each ADQLQuery. */ - public ADQLParser(java.io.Reader reader, QueryChecker checker) { + public ADQLParser(java.io.Reader reader, QueryChecker checker){ this(reader, checker, null); } @@ -215,7 +215,7 @@ public class ADQLParser implements ADQLParserConstants { * @param reader The reader in which the ADQL query to parse is given. * @param factory The object to use to build an object representation of the given ADQL query. */ - public ADQLParser(java.io.Reader reader, ADQLQueryFactory factory) { + public ADQLParser(java.io.Reader reader, ADQLQueryFactory factory){ this(reader, null, factory); } @@ -226,7 +226,7 @@ public class ADQLParser implements ADQLParserConstants { * @param checker The object to use to check each ADQLQuery. * @param factory The object to use to build an object representation of the given ADQL query. */ - public ADQLParser(ADQLParserTokenManager tm, QueryChecker checker, ADQLQueryFactory factory) { + public ADQLParser(ADQLParserTokenManager tm, QueryChecker checker, ADQLQueryFactory factory){ this(tm); queryChecker = checker; @@ -241,7 +241,7 @@ public class ADQLParser implements ADQLParserConstants { * @param tm The manager which associates a token to a numeric code. * @param checker The object to use to check each ADQLQuery. */ - public ADQLParser(ADQLParserTokenManager tm, QueryChecker checker) { + public ADQLParser(ADQLParserTokenManager tm, QueryChecker checker){ this(tm, checker, null); } @@ -251,7 +251,7 @@ public class ADQLParser implements ADQLParserConstants { * @param tm The manager which associates a token to a numeric code. * @param factory The object to use to build an object representation of the given ADQL query. */ - public ADQLParser(ADQLParserTokenManager tm, ADQLQueryFactory factory) { + public ADQLParser(ADQLParserTokenManager tm, ADQLQueryFactory factory){ this(tm, null, factory); } @@ -263,7 +263,7 @@ public class ADQLParser implements ADQLParserConstants { * * @see ADQLParser#Query() */ - public final ADQLQuery parseQuery() throws ParseException { + public final ADQLQuery parseQuery() throws ParseException{ stackQuery.clear(); query = null; return Query(); @@ -280,7 +280,7 @@ public class ADQLParser implements ADQLParserConstants { * @see ADQLParser#setDebug(boolean) * @see ADQLParser#Query() */ - public final ADQLQuery parseQuery(String q) throws ParseException { + public final ADQLQuery parseQuery(String q) throws ParseException{ stackQuery.clear(); query = null; ReInit(new java.io.ByteArrayInputStream(q.getBytes())); @@ -298,7 +298,7 @@ public class ADQLParser implements ADQLParserConstants { * @see ADQLParser#setDebug(boolean) * @see ADQLParser#Query() */ - public final ADQLQuery parseQuery(java.io.InputStream stream) throws ParseException { + public final ADQLQuery parseQuery(java.io.InputStream stream) throws ParseException{ stackQuery.clear(); query = null; ReInit(stream); @@ -315,7 +315,7 @@ public class ADQLParser implements ADQLParserConstants { allowedCoordSys.addAll(coordSys); } - public final boolean isAllowedCoordSys(final String coordSys) { + public final boolean isAllowedCoordSys(final String coordSys){ for(String cs : allowedCoordSys){ if (cs.equalsIgnoreCase(coordSys)) return true; @@ -324,8 +324,10 @@ public class ADQLParser implements ADQLParserConstants { } public final void setDebug(boolean debug){ - if (debug) enable_tracing(); - else disable_tracing(); + if (debug) + enable_tracing(); + else + disable_tracing(); } public final QueryChecker getQueryChecker(){ @@ -341,12 +343,12 @@ public class ADQLParser implements ADQLParserConstants { } public final void setQueryFactory(ADQLQueryFactory factory){ - queryFactory = (factory!=null)?factory:(new ADQLQueryFactory()); + queryFactory = (factory != null) ? factory : (new ADQLQueryFactory()); } private final ParseException generateParseException(Exception ex){ if (!(ex instanceof ParseException)){ - ParseException pex = new ParseException("["+ex.getClass().getName()+"] "+ex.getMessage()); + ParseException pex = new ParseException("[" + ex.getClass().getName() + "] " + ex.getMessage()); pex.setStackTrace(ex.getStackTrace()); return pex; }else @@ -361,7 +363,7 @@ public class ADQLParser implements ADQLParserConstants { * @param args * @throws Exception */ - public static final void main(String[] args) throws Exception { + public static final void main(String[] args) throws Exception{ final String USAGE = "Usage:\u005cn\u005ctadqlParser.jar [-d] [-v] [-e] [-a|-s] [<FILE>|<URL>]\u005cn\u005cnNOTE: If no file or URL is given, the ADQL query is expected in the standard input. This query must end with a ';' !\u005cn\u005cnParameters:\u005cn\u005ct-v or --verbose : Print the main steps of the parsing\u005cn\u005ct-d or --debug : Print stack traces when a grave error occurs\u005cn\u005ct-e or --explain : Explain the ADQL parsing (or Expand the parsing tree)\u005cn\u005ct-a or --adql : Display the understood ADQL query\u005cn\u005ct-s or --sql : Ask the SQL translation of the given ADQL query (SQL compatible with PostgreSQL)\u005cn\u005cnReturn:\u005cn\u005ctBy default: nothing if the query is correct. Otherwise a message explaining why the query is not correct is displayed.\u005cn\u005ctWith the -s option, the SQL translation of the given ADQL query will be returned.\u005cn\u005ctWith the -a option, the ADQL query is returned as it has been understood.\u005cn\u005cnExit status:\u005cn\u005ct0\u005ctOK !\u005cn\u005ct1\u005ctParameter error (missing or incorrect parameter)\u005cn\u005ct2\u005ctFile error (incorrect file/url, reading error, ...)\u005cn\u005ct3\u005ctParsing error (syntactic or semantic error)\u005cn\u005ct4\u005ctTranslation error (a problem has occurred during the translation of the given ADQL query in SQL)."; ADQLParser parser; @@ -370,86 +372,95 @@ public class ADQLParser implements ADQLParserConstants { String file = null, metaFile = null; short mode = -1; - boolean verbose=false, debug=false, explain=false; + boolean verbose = false, debug = false, explain = false; // Parameters reading: - for(int i=0; i<args.length; i++){ - if (args[i].equalsIgnoreCase("-d") || args[i].equalsIgnoreCase("--debug")) - debug = true; - else if (args[i].equalsIgnoreCase("-v") || args[i].equalsIgnoreCase("--verbose")) - verbose = true; - else if (args[i].equalsIgnoreCase("-e") || args[i].equalsIgnoreCase("--explain")) - explain = true; - else if (args[i].equalsIgnoreCase("-a") || args[i].equalsIgnoreCase("--adql")){ - if (mode != -1){ - System.err.println("((!)) Too much parameter: you must choose between -s, -c, -a or nothing ((!))\u005cn"+USAGE); - System.exit(1); - }else - mode = 1; - }else if (args[i].equalsIgnoreCase("-s") || args[i].equalsIgnoreCase("--sql")){ - if (mode != -1){ - System.err.println("((!)) Too much parameter: you must choose between -s, -c, -a or nothing ((!))\u005cn"+USAGE); - System.exit(1); - }else - mode = 2; - }else if (args[i].equalsIgnoreCase("-h") || args[i].equalsIgnoreCase("--help")){ - System.out.println(USAGE); - System.exit(0); - }else if (args[i].startsWith("-")){ - System.err.println("((!)) Unknown parameter: \u005c""+args[i]+"\u005c" ((!))\u005cn"+USAGE); + for(int i = 0; i < args.length; i++){ + if (args[i].equalsIgnoreCase("-d") || args[i].equalsIgnoreCase("--debug")) + debug = true; + else if (args[i].equalsIgnoreCase("-v") || args[i].equalsIgnoreCase("--verbose")) + verbose = true; + else if (args[i].equalsIgnoreCase("-e") || args[i].equalsIgnoreCase("--explain")) + explain = true; + else if (args[i].equalsIgnoreCase("-a") || args[i].equalsIgnoreCase("--adql")){ + if (mode != -1){ + System.err.println("((!)) Too much parameter: you must choose between -s, -c, -a or nothing ((!))\u005cn" + USAGE); System.exit(1); }else - file = args[i].trim(); - } - - try{ + mode = 1; + }else if (args[i].equalsIgnoreCase("-s") || args[i].equalsIgnoreCase("--sql")){ + if (mode != -1){ + System.err.println("((!)) Too much parameter: you must choose between -s, -c, -a or nothing ((!))\u005cn" + USAGE); + System.exit(1); + }else + mode = 2; + }else if (args[i].equalsIgnoreCase("-h") || args[i].equalsIgnoreCase("--help")){ + System.out.println(USAGE); + System.exit(0); + }else if (args[i].startsWith("-")){ + System.err.println("((!)) Unknown parameter: \u005c"" + args[i] + "\u005c" ((!))\u005cn" + USAGE); + System.exit(1); + }else + file = args[i].trim(); + } - if (file == null || file.isEmpty()) - parser = new ADQLParser(System.in); - else if (file.matches(urlRegex)) - parser = new ADQLParser((new java.net.URL(file)).openStream()); - else - parser = new ADQLParser(new FileReader(file)); + try{ - parser.setDebug(explain); + if (file == null || file.isEmpty()) + parser = new ADQLParser(System.in); + else if (file.matches(urlRegex)) + parser = new ADQLParser((new java.net.URL(file)).openStream()); + else + parser = new ADQLParser(new FileReader(file)); - // Query parsing: - try{ - if (verbose) System.out.print("((i)) Parsing ADQL query..."); - ADQLQuery q = parser.parseQuery(); - if (verbose) System.out.println("((i)) CORRECT ADQL QUERY ((i))"); - if (mode==2){ - PostgreSQLTranslator translator = new PostgreSQLTranslator(); - if (verbose) System.out.print("((i)) Translating in SQL..."); - String sql = translator.translate(q); - if (verbose) System.out.println("ok"); - System.out.println(sql); - }else if (mode==1){ - System.out.println(q.toADQL()); - } - }catch(UnresolvedIdentifiersException uie){ - System.err.println("((X)) "+uie.getNbErrors()+" unresolved identifiers:"); - for(ParseException pe : uie) - System.err.println("\u005ct - at "+pe.getPosition()+": "+uie.getMessage()); - if (debug) uie.printStackTrace(System.err); - System.exit(3); - }catch(ParseException pe){ - System.err.println("((X)) Syntax error: "+pe.getMessage()+" ((X))"); - if (debug) pe.printStackTrace(System.err); - System.exit(3); - }catch(TranslationException te){ - if (verbose) System.out.println("error"); - System.err.println("((X)) Translation error: "+te.getMessage()+" ((X))"); - if (debug) te.printStackTrace(System.err); - System.exit(4); - } + parser.setDebug(explain); - }catch(IOException ioe){ - System.err.println("\u005cn((X)) Error while reading the file \u005c""+file+"\u005c": "+ioe.getMessage()+" ((X))"); - if (debug) ioe.printStackTrace(System.err); - System.exit(2); + // Query parsing: + try{ + if (verbose) + System.out.print("((i)) Parsing ADQL query..."); + ADQLQuery q = parser.parseQuery(); + if (verbose) + System.out.println("((i)) CORRECT ADQL QUERY ((i))"); + if (mode == 2){ + PostgreSQLTranslator translator = new PostgreSQLTranslator(); + if (verbose) + System.out.print("((i)) Translating in SQL..."); + String sql = translator.translate(q); + if (verbose) + System.out.println("ok"); + System.out.println(sql); + }else if (mode == 1){ + System.out.println(q.toADQL()); + } + }catch(UnresolvedIdentifiersException uie){ + System.err.println("((X)) " + uie.getNbErrors() + " unresolved identifiers:"); + for(ParseException pe : uie) + System.err.println("\u005ct - at " + pe.getPosition() + ": " + uie.getMessage()); + if (debug) + uie.printStackTrace(System.err); + System.exit(3); + }catch(ParseException pe){ + System.err.println("((X)) Syntax error: " + pe.getMessage() + " ((X))"); + if (debug) + pe.printStackTrace(System.err); + System.exit(3); + }catch(TranslationException te){ + if (verbose) + System.out.println("error"); + System.err.println("((X)) Translation error: " + te.getMessage() + " ((X))"); + if (debug) + te.printStackTrace(System.err); + System.exit(4); } + }catch(IOException ioe){ + System.err.println("\u005cn((X)) Error while reading the file \u005c"" + file + "\u005c": " + ioe.getMessage() + " ((X))"); + if (debug) + ioe.printStackTrace(System.err); + System.exit(2); + } + } /* ########## */ @@ -466,382 +477,419 @@ public class ADQLParser implements ADQLParserConstants { * @return The object representation of the query. * @throws ParseException If the query syntax is incorrect. */ - final public ADQLQuery Query() throws ParseException { + final public ADQLQuery Query() throws ParseException{ trace_call("Query"); - try { + try{ ADQLQuery q = null; q = QueryExpression(); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case 0: - jj_consume_token(0); - break; - case EOQ: - jj_consume_token(EOQ); - break; - default: - jj_la1[0] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case 0: + jj_consume_token(0); + break; + case EOQ: + jj_consume_token(EOQ); + break; + default: + jj_la1[0] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + { + if (true) + return q; } - {if (true) return q;} throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("Query"); } } - final public ADQLQuery QueryExpression() throws ParseException { + final public ADQLQuery QueryExpression() throws ParseException{ trace_call("QueryExpression"); - try { + try{ try{ // create the query: query = queryFactory.createQuery(); stackQuery.push(query); }catch(Exception ex){ - {if (true) throw generateParseException(ex);} + { + if (true) + throw generateParseException(ex); + } } Select(); From(); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case WHERE: - Where(); - break; - default: - jj_la1[1] = jj_gen; - ; + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case WHERE: + Where(); + break; + default: + jj_la1[1] = jj_gen; + ; } - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case GROUP_BY: - GroupBy(); - break; - default: - jj_la1[2] = jj_gen; - ; + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case GROUP_BY: + GroupBy(); + break; + default: + jj_la1[2] = jj_gen; + ; } - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case HAVING: - Having(); - break; - default: - jj_la1[3] = jj_gen; - ; + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case HAVING: + Having(); + break; + default: + jj_la1[3] = jj_gen; + ; } - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case ORDER_BY: - OrderBy(); - break; - default: - jj_la1[4] = jj_gen; - ; + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case ORDER_BY: + OrderBy(); + break; + default: + jj_la1[4] = jj_gen; + ; } // check the query: - if (queryChecker != null) - queryChecker.check(query); + if (queryChecker != null) + queryChecker.check(query); // get the previous query (!= null if the current query is a sub-query): - ADQLQuery previousQuery = stackQuery.pop(); - if (stackQuery.isEmpty()) - query = null; - else - query = stackQuery.peek(); + ADQLQuery previousQuery = stackQuery.pop(); + if (stackQuery.isEmpty()) + query = null; + else + query = stackQuery.peek(); - {if (true) return previousQuery;} - throw new Error("Missing return statement in function"); - } finally { + { + if (true) + return previousQuery; + } + throw new Error("Missing return statement in function"); + }finally{ trace_return("QueryExpression"); } } - final public ADQLQuery SubQueryExpression() throws ParseException { + final public ADQLQuery SubQueryExpression() throws ParseException{ trace_call("SubQueryExpression"); - try { + try{ ADQLQuery q = null; jj_consume_token(LEFT_PAR); q = QueryExpression(); jj_consume_token(RIGHT_PAR); - {if (true) return q;} + { + if (true) + return q; + } throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("SubQueryExpression"); } } - final public void Select() throws ParseException { + final public void Select() throws ParseException{ trace_call("Select"); - try { - ClauseSelect select = query.getSelect(); SelectItem item=null; Token t = null; + try{ + ClauseSelect select = query.getSelect(); + SelectItem item = null; + Token t = null; jj_consume_token(SELECT); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case QUANTIFIER: - t = jj_consume_token(QUANTIFIER); - select.setDistinctColumns(t.image.equalsIgnoreCase("DISTINCT")); - break; - default: - jj_la1[5] = jj_gen; - ; - } - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case TOP: - jj_consume_token(TOP); - t = jj_consume_token(UNSIGNED_INTEGER); - try{ - select.setLimit(Integer.parseInt(t.image)); - }catch(NumberFormatException nfe){ - {if (true) throw new ParseException("[l."+t.beginLine+";c."+t.beginColumn+"] The TOP limit (\u005c""+t.image+"\u005c") isn't a regular unsigned integer !");} - } - break; - default: - jj_la1[6] = jj_gen; - ; + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case QUANTIFIER: + t = jj_consume_token(QUANTIFIER); + select.setDistinctColumns(t.image.equalsIgnoreCase("DISTINCT")); + break; + default: + jj_la1[5] = jj_gen; + ; + } + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case TOP: + jj_consume_token(TOP); + t = jj_consume_token(UNSIGNED_INTEGER); + try{ + select.setLimit(Integer.parseInt(t.image)); + }catch(NumberFormatException nfe){ + { + if (true) + throw new ParseException("[l." + t.beginLine + ";c." + t.beginColumn + "] The TOP limit (\u005c"" + t.image + "\u005c") isn't a regular unsigned integer !"); + } + } + break; + default: + jj_la1[6] = jj_gen; + ; } item = SelectItem(); select.add(item); - label_1: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + label_1: while(true){ + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ case COMMA: ; break; default: jj_la1[7] = jj_gen; break label_1; - } - jj_consume_token(COMMA); - item = SelectItem(); - select.add(item); } - } finally { + jj_consume_token(COMMA); + item = SelectItem(); + select.add(item); + } + }finally{ trace_return("Select"); } } - final public SelectItem SelectItem() throws ParseException { + final public SelectItem SelectItem() throws ParseException{ trace_call("SelectItem"); - try { - IdentifierItems identifiers = new IdentifierItems(true); IdentifierItem id = null, label = null; ADQLOperand op = null; - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case ASTERISK: - jj_consume_token(ASTERISK); - {if (true) return new SelectAllColumns(query);} - break; - default: - jj_la1[11] = jj_gen; - if (jj_2_1(7)) { - id = Identifier(); - jj_consume_token(DOT); - identifiers.append(id); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case DELIMITED_IDENTIFIER: - case REGULAR_IDENTIFIER: + try{ + IdentifierItems identifiers = new IdentifierItems(true); + IdentifierItem id = null, label = null; + ADQLOperand op = null; + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case ASTERISK: + jj_consume_token(ASTERISK); + { + if (true) + return new SelectAllColumns(query); + } + break; + default: + jj_la1[11] = jj_gen; + if (jj_2_1(7)){ id = Identifier(); jj_consume_token(DOT); identifiers.append(id); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case DELIMITED_IDENTIFIER: - case REGULAR_IDENTIFIER: - id = Identifier(); - jj_consume_token(DOT); - identifiers.append(id); - break; - default: - jj_la1[8] = jj_gen; - ; + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case DELIMITED_IDENTIFIER: + case REGULAR_IDENTIFIER: + id = Identifier(); + jj_consume_token(DOT); + identifiers.append(id); + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case DELIMITED_IDENTIFIER: + case REGULAR_IDENTIFIER: + id = Identifier(); + jj_consume_token(DOT); + identifiers.append(id); + break; + default: + jj_la1[8] = jj_gen; + ; + } + break; + default: + jj_la1[9] = jj_gen; + ; } - break; - default: - jj_la1[9] = jj_gen; - ; - } - jj_consume_token(ASTERISK); - try{; - {if (true) return new SelectAllColumns( queryFactory.createTable(identifiers, null) );} - }catch(Exception ex) { - {if (true) throw generateParseException(ex);} - } - } else { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case LEFT_PAR: - case PLUS: - case MINUS: - case AVG: - case MAX: - case MIN: - case SUM: - case COUNT: - case BOX: - case CENTROID: - case CIRCLE: - case POINT: - case POLYGON: - case REGION: - case CONTAINS: - case INTERSECTS: - case AREA: - case COORD1: - case COORD2: - case COORDSYS: - case DISTANCE: - case ABS: - case CEILING: - case DEGREES: - case EXP: - case FLOOR: - case LOG: - case LOG10: - case MOD: - case PI: - case POWER: - case RADIANS: - case RAND: - case ROUND: - case SQRT: - case TRUNCATE: - case ACOS: - case ASIN: - case ATAN: - case ATAN2: - case COS: - case COT: - case SIN: - case TAN: - case STRING_LITERAL: - case DELIMITED_IDENTIFIER: - case REGULAR_IDENTIFIER: - case SCIENTIFIC_NUMBER: - case UNSIGNED_FLOAT: - case UNSIGNED_INTEGER: - op = ValueExpression(); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case AS: - jj_consume_token(AS); - label = Identifier(); - break; - default: - jj_la1[10] = jj_gen; + jj_consume_token(ASTERISK); + try{ ; + { + if (true) + return new SelectAllColumns(queryFactory.createTable(identifiers, null)); + } + }catch(Exception ex){ + { + if (true) + throw generateParseException(ex); + } + } + }else{ + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case LEFT_PAR: + case PLUS: + case MINUS: + case AVG: + case MAX: + case MIN: + case SUM: + case COUNT: + case BOX: + case CENTROID: + case CIRCLE: + case POINT: + case POLYGON: + case REGION: + case CONTAINS: + case INTERSECTS: + case AREA: + case COORD1: + case COORD2: + case COORDSYS: + case DISTANCE: + case ABS: + case CEILING: + case DEGREES: + case EXP: + case FLOOR: + case LOG: + case LOG10: + case MOD: + case PI: + case POWER: + case RADIANS: + case RAND: + case ROUND: + case SQRT: + case TRUNCATE: + case ACOS: + case ASIN: + case ATAN: + case ATAN2: + case COS: + case COT: + case SIN: + case TAN: + case STRING_LITERAL: + case DELIMITED_IDENTIFIER: + case REGULAR_IDENTIFIER: + case SCIENTIFIC_NUMBER: + case UNSIGNED_FLOAT: + case UNSIGNED_INTEGER: + op = ValueExpression(); + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case AS: + jj_consume_token(AS); + label = Identifier(); + break; + default: + jj_la1[10] = jj_gen; + ; + } + break; + default: + jj_la1[12] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); } - break; - default: - jj_la1[12] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); } - } } try{ - SelectItem item = queryFactory.createSelectItem(op, (label==null)?null:label.identifier); + SelectItem item = queryFactory.createSelectItem(op, (label == null) ? null : label.identifier); if (label != null) item.setCaseSensitive(label.caseSensitivity); - {if (true) return item;} + { + if (true) + return item; + } }catch(Exception ex){ - {if (true) throw generateParseException(ex);} + { + if (true) + throw generateParseException(ex); + } } throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("SelectItem"); } } - final public void From() throws ParseException { + final public void From() throws ParseException{ trace_call("From"); - try { + try{ FromContent content = null, content2 = null; - try { + try{ jj_consume_token(FROM); content = TableRef(); - label_2: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + label_2: while(true){ + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ case COMMA: ; break; default: jj_la1[13] = jj_gen; break label_2; - } - jj_consume_token(COMMA); - content2 = TableRef(); - content = queryFactory.createJoin(JoinType.CROSS, content, content2); } + jj_consume_token(COMMA); + content2 = TableRef(); + content = queryFactory.createJoin(JoinType.CROSS, content, content2); + } query.setFrom(content); - } catch (Exception ex) { - {if (true) throw generateParseException(ex);} + }catch(Exception ex){ + { + if (true) + throw generateParseException(ex); + } } - } finally { + }finally{ trace_return("From"); } } - final public void Where() throws ParseException { + final public void Where() throws ParseException{ trace_call("Where"); - try { - ClauseConstraints where = query.getWhere(); ADQLConstraint condition; + try{ + ClauseConstraints where = query.getWhere(); + ADQLConstraint condition; jj_consume_token(WHERE); ConditionsList(where); - } finally { + }finally{ trace_return("Where"); } } - final public void GroupBy() throws ParseException { + final public void GroupBy() throws ParseException{ trace_call("GroupBy"); - try { - ClauseADQL<ColumnReference> groupBy = query.getGroupBy(); ColumnReference colRef = null; + try{ + ClauseADQL<ColumnReference> groupBy = query.getGroupBy(); + ColumnReference colRef = null; jj_consume_token(GROUP_BY); colRef = ColumnRef(); groupBy.add(colRef); - label_3: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + label_3: while(true){ + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ case COMMA: ; break; default: jj_la1[14] = jj_gen; break label_3; - } - jj_consume_token(COMMA); - colRef = ColumnRef(); - groupBy.add(colRef); } - } finally { + jj_consume_token(COMMA); + colRef = ColumnRef(); + groupBy.add(colRef); + } + }finally{ trace_return("GroupBy"); } } - final public void Having() throws ParseException { + final public void Having() throws ParseException{ trace_call("Having"); - try { + try{ ClauseConstraints having = query.getHaving(); jj_consume_token(HAVING); ConditionsList(having); - } finally { + }finally{ trace_return("Having"); } } - final public void OrderBy() throws ParseException { + final public void OrderBy() throws ParseException{ trace_call("OrderBy"); - try { - ClauseADQL<ADQLOrder> orderBy = query.getOrderBy(); ADQLOrder order = null; + try{ + ClauseADQL<ADQLOrder> orderBy = query.getOrderBy(); + ADQLOrder order = null; jj_consume_token(ORDER_BY); order = OrderItem(); orderBy.add(order); - label_4: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + label_4: while(true){ + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ case COMMA: ; break; default: jj_la1[15] = jj_gen; break label_4; - } - jj_consume_token(COMMA); - order = OrderItem(); - orderBy.add(order); } - } finally { + jj_consume_token(COMMA); + order = OrderItem(); + orderBy.add(order); + } + }finally{ trace_return("OrderBy"); } } @@ -849,26 +897,32 @@ public class ADQLParser implements ADQLParserConstants { /* *************************** */ /* COLUMN AND TABLE REFERENCES */ /* *************************** */ - final public IdentifierItem Identifier() throws ParseException { + final public IdentifierItem Identifier() throws ParseException{ trace_call("Identifier"); - try { + try{ Token t; - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case REGULAR_IDENTIFIER: - t = jj_consume_token(REGULAR_IDENTIFIER); - {if (true) return new IdentifierItem(t, false);} - break; - case DELIMITED_IDENTIFIER: - t = jj_consume_token(DELIMITED_IDENTIFIER); - {if (true) return new IdentifierItem(t, true);} - break; - default: - jj_la1[16] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case REGULAR_IDENTIFIER: + t = jj_consume_token(REGULAR_IDENTIFIER); + { + if (true) + return new IdentifierItem(t, false); + } + break; + case DELIMITED_IDENTIFIER: + t = jj_consume_token(DELIMITED_IDENTIFIER); + { + if (true) + return new IdentifierItem(t, true); + } + break; + default: + jj_la1[16] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); } throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("Identifier"); } } @@ -878,35 +932,39 @@ public class ADQLParser implements ADQLParserConstants { * * @return A {@link IdentifierItems} which contains at most three items: catalogName, schemaName and tableName. */ - final public IdentifierItems TableName() throws ParseException { + final public IdentifierItems TableName() throws ParseException{ trace_call("TableName"); - try { - IdentifierItems identifiers=new IdentifierItems(true); IdentifierItem id=null; + try{ + IdentifierItems identifiers = new IdentifierItems(true); + IdentifierItem id = null; id = Identifier(); identifiers.append(id); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case DOT: - jj_consume_token(DOT); - id = Identifier(); - identifiers.append(id); - break; - default: - jj_la1[17] = jj_gen; - ; - } - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case DOT: - jj_consume_token(DOT); - id = Identifier(); - identifiers.append(id); - break; - default: - jj_la1[18] = jj_gen; - ; + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case DOT: + jj_consume_token(DOT); + id = Identifier(); + identifiers.append(id); + break; + default: + jj_la1[17] = jj_gen; + ; + } + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case DOT: + jj_consume_token(DOT); + id = Identifier(); + identifiers.append(id); + break; + default: + jj_la1[18] = jj_gen; + ; + } + { + if (true) + return identifiers; } - {if (true) return identifiers;} throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("TableName"); } } @@ -916,64 +974,75 @@ public class ADQLParser implements ADQLParserConstants { * * @return A {@link IdentifierItems} which contains at most four items: catalogName, schemaName, tableName and columnName. */ - final public IdentifierItems ColumnName() throws ParseException { + final public IdentifierItems ColumnName() throws ParseException{ trace_call("ColumnName"); - try { - IdentifierItem id; IdentifierItems table=null, identifiers=new IdentifierItems(false); + try{ + IdentifierItem id; + IdentifierItems table = null, identifiers = new IdentifierItems(false); id = Identifier(); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case DOT: - jj_consume_token(DOT); - table = TableName(); - break; - default: - jj_la1[19] = jj_gen; - ; + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case DOT: + jj_consume_token(DOT); + table = TableName(); + break; + default: + jj_la1[19] = jj_gen; + ; } identifiers.append(id); if (table != null){ - for(int i=0; i<table.size(); i++) + for(int i = 0; i < table.size(); i++) identifiers.append(table.get(i)); } - {if (true) return identifiers;} + { + if (true) + return identifiers; + } throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("ColumnName"); } } - final public ADQLColumn Column() throws ParseException { + final public ADQLColumn Column() throws ParseException{ trace_call("Column"); - try { + try{ IdentifierItems identifiers; identifiers = ColumnName(); try{ - {if (true) return queryFactory.createColumn(identifiers);} + { + if (true) + return queryFactory.createColumn(identifiers); + } }catch(Exception ex){ - {if (true) throw generateParseException(ex);} + { + if (true) + throw generateParseException(ex); + } } throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("Column"); } } - final public ColumnReference ColumnRef() throws ParseException { + final public ColumnReference ColumnRef() throws ParseException{ trace_call("ColumnRef"); - try { - IdentifierItems identifiers = null; Token ind = null; - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case DELIMITED_IDENTIFIER: - case REGULAR_IDENTIFIER: - identifiers = ColumnName(); - break; - case UNSIGNED_INTEGER: - ind = jj_consume_token(UNSIGNED_INTEGER); - break; - default: - jj_la1[20] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); + try{ + IdentifierItems identifiers = null; + Token ind = null; + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case DELIMITED_IDENTIFIER: + case REGULAR_IDENTIFIER: + identifiers = ColumnName(); + break; + case UNSIGNED_INTEGER: + ind = jj_consume_token(UNSIGNED_INTEGER); + break; + default: + jj_la1[20] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); } try{ ColumnReference colRef = null; @@ -981,166 +1050,195 @@ public class ADQLParser implements ADQLParserConstants { colRef = queryFactory.createColRef(identifiers); else colRef = queryFactory.createColRef(Integer.parseInt(ind.image), new TextPosition(ind)); - {if (true) return colRef;} + { + if (true) + return colRef; + } }catch(Exception ex){ - {if (true) throw generateParseException(ex);} + { + if (true) + throw generateParseException(ex); + } } throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("ColumnRef"); } } - final public ADQLOrder OrderItem() throws ParseException { + final public ADQLOrder OrderItem() throws ParseException{ trace_call("OrderItem"); - try { - IdentifierItems identifiers = null; Token ind = null, desc = null; - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case DELIMITED_IDENTIFIER: - case REGULAR_IDENTIFIER: - identifiers = ColumnName(); - break; - case UNSIGNED_INTEGER: - ind = jj_consume_token(UNSIGNED_INTEGER); - break; - default: - jj_la1[21] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case ASC: - case DESC: - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case ASC: - jj_consume_token(ASC); + try{ + IdentifierItems identifiers = null; + Token ind = null, desc = null; + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case DELIMITED_IDENTIFIER: + case REGULAR_IDENTIFIER: + identifiers = ColumnName(); break; - case DESC: - desc = jj_consume_token(DESC); + case UNSIGNED_INTEGER: + ind = jj_consume_token(UNSIGNED_INTEGER); break; default: - jj_la1[22] = jj_gen; + jj_la1[21] = jj_gen; jj_consume_token(-1); throw new ParseException(); - } - break; - default: - jj_la1[23] = jj_gen; - ; + } + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case ASC: + case DESC: + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case ASC: + jj_consume_token(ASC); + break; + case DESC: + desc = jj_consume_token(DESC); + break; + default: + jj_la1[22] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + break; + default: + jj_la1[23] = jj_gen; + ; } try{ ADQLOrder order = null; if (identifiers != null) - order = queryFactory.createOrder(identifiers, desc!=null); + order = queryFactory.createOrder(identifiers, desc != null); else - order = queryFactory.createOrder(Integer.parseInt(ind.image), desc!=null, new TextPosition(ind)); - {if (true) return order;} + order = queryFactory.createOrder(Integer.parseInt(ind.image), desc != null, new TextPosition(ind)); + { + if (true) + return order; + } }catch(Exception ex){ - {if (true) throw generateParseException(ex);} + { + if (true) + throw generateParseException(ex); + } } throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("OrderItem"); } } - final public FromContent SimpleTableRef() throws ParseException { + final public FromContent SimpleTableRef() throws ParseException{ trace_call("SimpleTableRef"); - try { - IdentifierItem alias = null; IdentifierItems identifiers = null; ADQLQuery subQuery = null; FromContent content = null; - try { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case DELIMITED_IDENTIFIER: - case REGULAR_IDENTIFIER: - identifiers = TableName(); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case AS: + try{ + IdentifierItem alias = null; + IdentifierItems identifiers = null; + ADQLQuery subQuery = null; + FromContent content = null; + try{ + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ case DELIMITED_IDENTIFIER: case REGULAR_IDENTIFIER: - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case AS: - jj_consume_token(AS); - break; - default: - jj_la1[24] = jj_gen; - ; + identifiers = TableName(); + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case AS: + case DELIMITED_IDENTIFIER: + case REGULAR_IDENTIFIER: + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case AS: + jj_consume_token(AS); + break; + default: + jj_la1[24] = jj_gen; + ; + } + alias = Identifier(); + break; + default: + jj_la1[25] = jj_gen; + ; + } + { + if (true) + return queryFactory.createTable(identifiers, alias); } - alias = Identifier(); break; default: - jj_la1[25] = jj_gen; - ; - } - {if (true) return queryFactory.createTable(identifiers, alias);} - break; - default: - jj_la1[27] = jj_gen; - if (jj_2_2(2)) { - subQuery = SubQueryExpression(); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case AS: - jj_consume_token(AS); - break; - default: - jj_la1[26] = jj_gen; - ; - } - alias = Identifier(); - {if (true) return queryFactory.createTable(subQuery, alias);} - } else { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case LEFT_PAR: - jj_consume_token(LEFT_PAR); - content = JoinedTable(); - jj_consume_token(RIGHT_PAR); - {if (true) return content;} - break; - default: - jj_la1[28] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); + jj_la1[27] = jj_gen; + if (jj_2_2(2)){ + subQuery = SubQueryExpression(); + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case AS: + jj_consume_token(AS); + break; + default: + jj_la1[26] = jj_gen; + ; + } + alias = Identifier(); + { + if (true) + return queryFactory.createTable(subQuery, alias); + } + }else{ + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case LEFT_PAR: + jj_consume_token(LEFT_PAR); + content = JoinedTable(); + jj_consume_token(RIGHT_PAR); + { + if (true) + return content; + } + break; + default: + jj_la1[28] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } } - } } - } catch (Exception ex) { - {if (true) throw generateParseException(ex);} + }catch(Exception ex){ + { + if (true) + throw generateParseException(ex); + } } throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("SimpleTableRef"); } } - final public FromContent TableRef() throws ParseException { + final public FromContent TableRef() throws ParseException{ trace_call("TableRef"); - try { + try{ FromContent content; content = SimpleTableRef(); - label_5: - while (true) { - if (jj_2_3(2)) { - ; - } else { - break label_5; - } - content = JoinSpecification(content); + label_5: while(true){ + if (jj_2_3(2)){ + ; + }else{ + break label_5; } - {if (true) return content;} + content = JoinSpecification(content); + } + { + if (true) + return content; + } throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("TableRef"); } } - final public FromContent JoinedTable() throws ParseException { + final public FromContent JoinedTable() throws ParseException{ trace_call("JoinedTable"); - try { + try{ FromContent content; content = SimpleTableRef(); - label_6: - while (true) { - content = JoinSpecification(content); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + label_6: while(true){ + content = JoinSpecification(content); + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ case NATURAL: case INNER: case RIGHT: @@ -1152,177 +1250,196 @@ public class ADQLParser implements ADQLParserConstants { default: jj_la1[29] = jj_gen; break label_6; - } } - {if (true) return content;} + } + { + if (true) + return content; + } throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("JoinedTable"); } } - final public ADQLJoin JoinSpecification(FromContent leftTable) throws ParseException { + final public ADQLJoin JoinSpecification(FromContent leftTable) throws ParseException{ trace_call("JoinSpecification"); - try { - boolean natural = false; JoinType type = JoinType.INNER; ClauseConstraints condition = new ClauseConstraints("ON"); ArrayList<ADQLColumn> lstColumns=new ArrayList<ADQLColumn>(); IdentifierItem id; FromContent rightTable; - try { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case NATURAL: - jj_consume_token(NATURAL); - natural=true; - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case INNER: - case RIGHT: - case LEFT: - case FULL: - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case INNER: - jj_consume_token(INNER); - break; - case RIGHT: - case LEFT: - case FULL: - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case LEFT: - jj_consume_token(LEFT); - type = JoinType.OUTER_LEFT; - break; + try{ + boolean natural = false; + JoinType type = JoinType.INNER; + ClauseConstraints condition = new ClauseConstraints("ON"); + ArrayList<ADQLColumn> lstColumns = new ArrayList<ADQLColumn>(); + IdentifierItem id; + FromContent rightTable; + try{ + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case NATURAL: + jj_consume_token(NATURAL); + natural = true; + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case INNER: case RIGHT: - jj_consume_token(RIGHT); - type = JoinType.OUTER_RIGHT; - break; + case LEFT: case FULL: - jj_consume_token(FULL); - type = JoinType.OUTER_FULL; - break; - default: - jj_la1[30] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case OUTER: - jj_consume_token(OUTER); + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case INNER: + jj_consume_token(INNER); + break; + case RIGHT: + case LEFT: + case FULL: + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case LEFT: + jj_consume_token(LEFT); + type = JoinType.OUTER_LEFT; + break; + case RIGHT: + jj_consume_token(RIGHT); + type = JoinType.OUTER_RIGHT; + break; + case FULL: + jj_consume_token(FULL); + type = JoinType.OUTER_FULL; + break; + default: + jj_la1[30] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case OUTER: + jj_consume_token(OUTER); + break; + default: + jj_la1[31] = jj_gen; + ; + } + break; + default: + jj_la1[32] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } break; default: - jj_la1[31] = jj_gen; + jj_la1[33] = jj_gen; ; - } - break; - default: - jj_la1[32] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); + } + jj_consume_token(JOIN); + rightTable = TableRef(); + { + if (true) + return queryFactory.createJoin(type, leftTable, rightTable); } break; - default: - jj_la1[33] = jj_gen; - ; - } - jj_consume_token(JOIN); - rightTable = TableRef(); - {if (true) return queryFactory.createJoin(type, leftTable, rightTable);} - break; - case INNER: - case RIGHT: - case LEFT: - case FULL: - case JOIN: - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case INNER: case RIGHT: case LEFT: case FULL: - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case INNER: - jj_consume_token(INNER); - break; - case RIGHT: - case LEFT: - case FULL: - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case LEFT: - jj_consume_token(LEFT); - type = JoinType.OUTER_LEFT; - break; + case JOIN: + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case INNER: case RIGHT: - jj_consume_token(RIGHT); - type = JoinType.OUTER_RIGHT; - break; + case LEFT: case FULL: - jj_consume_token(FULL); - type = JoinType.OUTER_FULL; - break; - default: - jj_la1[34] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case OUTER: - jj_consume_token(OUTER); + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case INNER: + jj_consume_token(INNER); + break; + case RIGHT: + case LEFT: + case FULL: + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case LEFT: + jj_consume_token(LEFT); + type = JoinType.OUTER_LEFT; + break; + case RIGHT: + jj_consume_token(RIGHT); + type = JoinType.OUTER_RIGHT; + break; + case FULL: + jj_consume_token(FULL); + type = JoinType.OUTER_FULL; + break; + default: + jj_la1[34] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case OUTER: + jj_consume_token(OUTER); + break; + default: + jj_la1[35] = jj_gen; + ; + } + break; + default: + jj_la1[36] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } break; default: - jj_la1[35] = jj_gen; + jj_la1[37] = jj_gen; ; - } - break; - default: - jj_la1[36] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); } - break; - default: - jj_la1[37] = jj_gen; - ; - } - jj_consume_token(JOIN); - rightTable = TableRef(); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case ON: - jj_consume_token(ON); - ConditionsList(condition); - {if (true) return queryFactory.createJoin(type, leftTable, rightTable, condition);} - break; - case USING: - jj_consume_token(USING); - jj_consume_token(LEFT_PAR); - id = Identifier(); - lstColumns.add( queryFactory.createColumn(id) ); - label_7: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case COMMA: - ; - break; - default: - jj_la1[38] = jj_gen; - break label_7; + jj_consume_token(JOIN); + rightTable = TableRef(); + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case ON: + jj_consume_token(ON); + ConditionsList(condition); + { + if (true) + return queryFactory.createJoin(type, leftTable, rightTable, condition); } - jj_consume_token(COMMA); + break; + case USING: + jj_consume_token(USING); + jj_consume_token(LEFT_PAR); id = Identifier(); - lstColumns.add( queryFactory.createColumn(id) ); - } - jj_consume_token(RIGHT_PAR); - {if (true) return queryFactory.createJoin(type, leftTable, rightTable, lstColumns);} + lstColumns.add(queryFactory.createColumn(id)); + label_7: while(true){ + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case COMMA: + ; + break; + default: + jj_la1[38] = jj_gen; + break label_7; + } + jj_consume_token(COMMA); + id = Identifier(); + lstColumns.add(queryFactory.createColumn(id)); + } + jj_consume_token(RIGHT_PAR); + { + if (true) + return queryFactory.createJoin(type, leftTable, rightTable, lstColumns); + } + break; + default: + jj_la1[39] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } break; default: - jj_la1[39] = jj_gen; + jj_la1[40] = jj_gen; jj_consume_token(-1); throw new ParseException(); - } - break; - default: - jj_la1[40] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); } - } catch (Exception ex) { - {if (true) throw generateParseException(ex);} + }catch(Exception ex){ + { + if (true) + throw generateParseException(ex); + } } throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("JoinSpecification"); } } @@ -1330,26 +1447,29 @@ public class ADQLParser implements ADQLParserConstants { /* ****** */ /* STRING */ /* ****** */ - final public String String() throws ParseException { + final public String String() throws ParseException{ trace_call("String"); - try { - Token t; String str=""; - label_8: - while (true) { - t = jj_consume_token(STRING_LITERAL); - str += t.image; - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + try{ + Token t; + String str = ""; + label_8: while(true){ + t = jj_consume_token(STRING_LITERAL); + str += t.image; + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ case STRING_LITERAL: ; break; default: jj_la1[41] = jj_gen; break label_8; - } } - {if (true) return (str!=null)?str.substring(1,str.length()-1):str;} + } + { + if (true) + return (str != null) ? str.substring(1, str.length() - 1) : str; + } throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("String"); } } @@ -1357,83 +1477,92 @@ public class ADQLParser implements ADQLParserConstants { /* ************* */ /* NUMERIC TYPES */ /* ************* */ - final public String UnsignedNumeric() throws ParseException { + final public String UnsignedNumeric() throws ParseException{ trace_call("UnsignedNumeric"); - try { + try{ Token t; - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case SCIENTIFIC_NUMBER: - t = jj_consume_token(SCIENTIFIC_NUMBER); - break; - case UNSIGNED_FLOAT: - t = jj_consume_token(UNSIGNED_FLOAT); - break; - case UNSIGNED_INTEGER: - t = jj_consume_token(UNSIGNED_INTEGER); - break; - default: - jj_la1[42] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case SCIENTIFIC_NUMBER: + t = jj_consume_token(SCIENTIFIC_NUMBER); + break; + case UNSIGNED_FLOAT: + t = jj_consume_token(UNSIGNED_FLOAT); + break; + case UNSIGNED_INTEGER: + t = jj_consume_token(UNSIGNED_INTEGER); + break; + default: + jj_la1[42] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + { + if (true) + return t.image; } - {if (true) return t.image;} throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("UnsignedNumeric"); } } - final public String UnsignedFloat() throws ParseException { + final public String UnsignedFloat() throws ParseException{ trace_call("UnsignedFloat"); - try { + try{ Token t; - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case UNSIGNED_INTEGER: - t = jj_consume_token(UNSIGNED_INTEGER); - break; - case UNSIGNED_FLOAT: - t = jj_consume_token(UNSIGNED_FLOAT); - break; - default: - jj_la1[43] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case UNSIGNED_INTEGER: + t = jj_consume_token(UNSIGNED_INTEGER); + break; + case UNSIGNED_FLOAT: + t = jj_consume_token(UNSIGNED_FLOAT); + break; + default: + jj_la1[43] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + { + if (true) + return t.image; } - {if (true) return t.image;} throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("UnsignedFloat"); } } - final public String SignedInteger() throws ParseException { + final public String SignedInteger() throws ParseException{ trace_call("SignedInteger"); - try { - Token sign=null, number; - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case PLUS: - case MINUS: - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + try{ + Token sign = null, number; + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ case PLUS: - sign = jj_consume_token(PLUS); - break; case MINUS: - sign = jj_consume_token(MINUS); + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case PLUS: + sign = jj_consume_token(PLUS); + break; + case MINUS: + sign = jj_consume_token(MINUS); + break; + default: + jj_la1[44] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } break; default: - jj_la1[44] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - break; - default: - jj_la1[45] = jj_gen; - ; + jj_la1[45] = jj_gen; + ; } number = jj_consume_token(UNSIGNED_INTEGER); - {if (true) return ((sign==null)?"":sign.image)+number.image;} + { + if (true) + return ((sign == null) ? "" : sign.image) + number.image; + } throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("SignedInteger"); } } @@ -1441,400 +1570,459 @@ public class ADQLParser implements ADQLParserConstants { /* *********** */ /* EXPRESSIONS */ /* *********** */ - final public ADQLOperand ValueExpressionPrimary() throws ParseException { + final public ADQLOperand ValueExpressionPrimary() throws ParseException{ trace_call("ValueExpressionPrimary"); - try { - String expr; ADQLColumn column; ADQLOperand op; - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case STRING_LITERAL: - case SCIENTIFIC_NUMBER: - case UNSIGNED_FLOAT: - case UNSIGNED_INTEGER: - try { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case SCIENTIFIC_NUMBER: - case UNSIGNED_FLOAT: - case UNSIGNED_INTEGER: - // unsigned_value_specification - expr = UnsignedNumeric(); - {if (true) return queryFactory.createNumericConstant(expr);} - break; - case STRING_LITERAL: - expr = String(); - {if (true) return queryFactory.createStringConstant(expr);} - break; - default: - jj_la1[46] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); + try{ + String expr; + ADQLColumn column; + ADQLOperand op; + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case STRING_LITERAL: + case SCIENTIFIC_NUMBER: + case UNSIGNED_FLOAT: + case UNSIGNED_INTEGER: + try{ + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case SCIENTIFIC_NUMBER: + case UNSIGNED_FLOAT: + case UNSIGNED_INTEGER: + // unsigned_value_specification + expr = UnsignedNumeric(); + { + if (true) + return queryFactory.createNumericConstant(expr); + } + break; + case STRING_LITERAL: + expr = String(); + { + if (true) + return queryFactory.createStringConstant(expr); + } + break; + default: + jj_la1[46] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + }catch(Exception ex){ + { + if (true) + throw generateParseException(ex); + } } - } catch (Exception ex) { - {if (true) throw generateParseException(ex);} - } - break; - case DELIMITED_IDENTIFIER: - case REGULAR_IDENTIFIER: - column = Column(); - {if (true) return column;} - break; - case AVG: - case MAX: - case MIN: - case SUM: - case COUNT: - op = SqlFunction(); - {if (true) return op;} - break; - case LEFT_PAR: - jj_consume_token(LEFT_PAR); - op = ValueExpression(); - jj_consume_token(RIGHT_PAR); - {if (true) return op;} - break; - default: - jj_la1[47] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); + break; + case DELIMITED_IDENTIFIER: + case REGULAR_IDENTIFIER: + column = Column(); + { + if (true) + return column; + } + break; + case AVG: + case MAX: + case MIN: + case SUM: + case COUNT: + op = SqlFunction(); + { + if (true) + return op; + } + break; + case LEFT_PAR: + jj_consume_token(LEFT_PAR); + op = ValueExpression(); + jj_consume_token(RIGHT_PAR); + { + if (true) + return op; + } + break; + default: + jj_la1[47] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); } throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("ValueExpressionPrimary"); } } - final public ADQLOperand ValueExpression() throws ParseException { + final public ADQLOperand ValueExpression() throws ParseException{ trace_call("ValueExpression"); - try { + try{ ADQLOperand valueExpr = null; - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case BOX: - case CENTROID: - case CIRCLE: - case POINT: - case POLYGON: - case REGION: - valueExpr = GeometryValueFunction(); - break; - default: - jj_la1[48] = jj_gen; - if (jj_2_4(2147483647)) { - valueExpr = NumericExpression(); - } else if (jj_2_5(2147483647)) { - valueExpr = StringExpression(); - } else if (jj_2_6(2147483647)) { - valueExpr = StringExpression(); - } else { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case LEFT_PAR: - case PLUS: - case MINUS: - case AVG: - case MAX: - case MIN: - case SUM: - case COUNT: - case CONTAINS: - case INTERSECTS: - case AREA: - case COORD1: - case COORD2: - case DISTANCE: - case ABS: - case CEILING: - case DEGREES: - case EXP: - case FLOOR: - case LOG: - case LOG10: - case MOD: - case PI: - case POWER: - case RADIANS: - case RAND: - case ROUND: - case SQRT: - case TRUNCATE: - case ACOS: - case ASIN: - case ATAN: - case ATAN2: - case COS: - case COT: - case SIN: - case TAN: - case STRING_LITERAL: - case DELIMITED_IDENTIFIER: - case REGULAR_IDENTIFIER: - case SCIENTIFIC_NUMBER: - case UNSIGNED_FLOAT: - case UNSIGNED_INTEGER: + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case BOX: + case CENTROID: + case CIRCLE: + case POINT: + case POLYGON: + case REGION: + valueExpr = GeometryValueFunction(); + break; + default: + jj_la1[48] = jj_gen; + if (jj_2_4(2147483647)){ valueExpr = NumericExpression(); - break; - default: - jj_la1[49] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - } - } - {if (true) return valueExpr;} + }else if (jj_2_5(2147483647)){ + valueExpr = StringExpression(); + }else if (jj_2_6(2147483647)){ + valueExpr = StringExpression(); + }else{ + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case LEFT_PAR: + case PLUS: + case MINUS: + case AVG: + case MAX: + case MIN: + case SUM: + case COUNT: + case CONTAINS: + case INTERSECTS: + case AREA: + case COORD1: + case COORD2: + case DISTANCE: + case ABS: + case CEILING: + case DEGREES: + case EXP: + case FLOOR: + case LOG: + case LOG10: + case MOD: + case PI: + case POWER: + case RADIANS: + case RAND: + case ROUND: + case SQRT: + case TRUNCATE: + case ACOS: + case ASIN: + case ATAN: + case ATAN2: + case COS: + case COT: + case SIN: + case TAN: + case STRING_LITERAL: + case DELIMITED_IDENTIFIER: + case REGULAR_IDENTIFIER: + case SCIENTIFIC_NUMBER: + case UNSIGNED_FLOAT: + case UNSIGNED_INTEGER: + valueExpr = NumericExpression(); + break; + default: + jj_la1[49] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + } + } + { + if (true) + return valueExpr; + } throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("ValueExpression"); } } - final public ADQLOperand NumericExpression() throws ParseException { + final public ADQLOperand NumericExpression() throws ParseException{ trace_call("NumericExpression"); - try { - Token sign=null; ADQLOperand leftOp, rightOp=null; + try{ + Token sign = null; + ADQLOperand leftOp, rightOp = null; leftOp = NumericTerm(); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case PLUS: - case MINUS: - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ case PLUS: - sign = jj_consume_token(PLUS); - break; case MINUS: - sign = jj_consume_token(MINUS); + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case PLUS: + sign = jj_consume_token(PLUS); + break; + case MINUS: + sign = jj_consume_token(MINUS); + break; + default: + jj_la1[50] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + rightOp = NumericExpression(); break; default: - jj_la1[50] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - rightOp = NumericExpression(); - break; - default: - jj_la1[51] = jj_gen; - ; + jj_la1[51] = jj_gen; + ; } - if (sign == null) - {if (true) return leftOp;} - else{ + if (sign == null){ + if (true) + return leftOp; + }else{ try{ - {if (true) return queryFactory.createOperation(leftOp, OperationType.getOperator(sign.image), rightOp);} + { + if (true) + return queryFactory.createOperation(leftOp, OperationType.getOperator(sign.image), rightOp); + } }catch(Exception ex){ - {if (true) throw generateParseException(ex);} + { + if (true) + throw generateParseException(ex); + } } } throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("NumericExpression"); } } - final public ADQLOperand NumericTerm() throws ParseException { + final public ADQLOperand NumericTerm() throws ParseException{ trace_call("NumericTerm"); - try { - Token sign=null; ADQLOperand leftOp, rightOp=null; + try{ + Token sign = null; + ADQLOperand leftOp, rightOp = null; leftOp = Factor(); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case ASTERISK: - case DIVIDE: - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ case ASTERISK: - sign = jj_consume_token(ASTERISK); - break; case DIVIDE: - sign = jj_consume_token(DIVIDE); + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case ASTERISK: + sign = jj_consume_token(ASTERISK); + break; + case DIVIDE: + sign = jj_consume_token(DIVIDE); + break; + default: + jj_la1[52] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + rightOp = NumericTerm(); break; default: - jj_la1[52] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - rightOp = NumericTerm(); - break; - default: - jj_la1[53] = jj_gen; - ; + jj_la1[53] = jj_gen; + ; } - if (sign == null) - {if (true) return leftOp;} - else{ + if (sign == null){ + if (true) + return leftOp; + }else{ try{ - {if (true) return queryFactory.createOperation(leftOp, OperationType.getOperator(sign.image), rightOp);} + { + if (true) + return queryFactory.createOperation(leftOp, OperationType.getOperator(sign.image), rightOp); + } }catch(Exception ex){ - {if (true) throw generateParseException(ex);} + { + if (true) + throw generateParseException(ex); + } } } throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("NumericTerm"); } } - final public ADQLOperand Factor() throws ParseException { + final public ADQLOperand Factor() throws ParseException{ trace_call("Factor"); - try { - boolean negative = false;; ADQLOperand op; - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case PLUS: - case MINUS: - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + try{ + boolean negative = false;; + ADQLOperand op; + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ case PLUS: - jj_consume_token(PLUS); - break; case MINUS: - jj_consume_token(MINUS); - negative = true; + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case PLUS: + jj_consume_token(PLUS); + break; + case MINUS: + jj_consume_token(MINUS); + negative = true; + break; + default: + jj_la1[54] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } break; default: - jj_la1[54] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - break; - default: - jj_la1[55] = jj_gen; - ; + jj_la1[55] = jj_gen; + ; } - if (jj_2_7(2)) { + if (jj_2_7(2)){ op = NumericFunction(); - } else { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case LEFT_PAR: - case AVG: - case MAX: - case MIN: - case SUM: - case COUNT: - case STRING_LITERAL: - case DELIMITED_IDENTIFIER: - case REGULAR_IDENTIFIER: - case SCIENTIFIC_NUMBER: - case UNSIGNED_FLOAT: - case UNSIGNED_INTEGER: - op = ValueExpressionPrimary(); - break; - default: - jj_la1[56] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); + }else{ + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case LEFT_PAR: + case AVG: + case MAX: + case MIN: + case SUM: + case COUNT: + case STRING_LITERAL: + case DELIMITED_IDENTIFIER: + case REGULAR_IDENTIFIER: + case SCIENTIFIC_NUMBER: + case UNSIGNED_FLOAT: + case UNSIGNED_INTEGER: + op = ValueExpressionPrimary(); + break; + default: + jj_la1[56] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); } } if (negative){ try{ op = queryFactory.createNegativeOperand(op); }catch(Exception ex){ - {if (true) throw generateParseException(ex);} + { + if (true) + throw generateParseException(ex); + } } } - {if (true) return op;} + { + if (true) + return op; + } throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("Factor"); } } - final public ADQLOperand StringExpression() throws ParseException { + final public ADQLOperand StringExpression() throws ParseException{ trace_call("StringExpression"); - try { - ADQLOperand leftOp; ADQLOperand rightOp = null; + try{ + ADQLOperand leftOp; + ADQLOperand rightOp = null; leftOp = StringFactor(); - label_9: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + label_9: while(true){ + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ case CONCAT: ; break; default: jj_la1[57] = jj_gen; break label_9; - } - jj_consume_token(CONCAT); - rightOp = StringFactor(); - if (!(leftOp instanceof Concatenation)){ - try{ - ADQLOperand temp = leftOp; - leftOp = queryFactory.createConcatenation(); - ((Concatenation)leftOp).add(temp); - }catch(Exception ex){ - {if (true) throw generateParseException(ex);} + } + jj_consume_token(CONCAT); + rightOp = StringFactor(); + if (!(leftOp instanceof Concatenation)){ + try{ + ADQLOperand temp = leftOp; + leftOp = queryFactory.createConcatenation(); + ((Concatenation)leftOp).add(temp); + }catch(Exception ex){ + { + if (true) + throw generateParseException(ex); } } - ((Concatenation)leftOp).add(rightOp); } - {if (true) return leftOp;} + ((Concatenation)leftOp).add(rightOp); + } + { + if (true) + return leftOp; + } throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("StringExpression"); } } - final public ADQLOperand StringFactor() throws ParseException { + final public ADQLOperand StringFactor() throws ParseException{ trace_call("StringFactor"); - try { + try{ ADQLOperand op; - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case COORDSYS: - op = ExtractCoordSys(); - break; - default: - jj_la1[58] = jj_gen; - if (jj_2_8(2)) { - op = UserDefinedFunction(); - } else { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case LEFT_PAR: - case AVG: - case MAX: - case MIN: - case SUM: - case COUNT: - case STRING_LITERAL: - case DELIMITED_IDENTIFIER: - case REGULAR_IDENTIFIER: - case SCIENTIFIC_NUMBER: - case UNSIGNED_FLOAT: - case UNSIGNED_INTEGER: - op = ValueExpressionPrimary(); - break; - default: - jj_la1[59] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case COORDSYS: + op = ExtractCoordSys(); + break; + default: + jj_la1[58] = jj_gen; + if (jj_2_8(2)){ + op = UserDefinedFunction(); + }else{ + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case LEFT_PAR: + case AVG: + case MAX: + case MIN: + case SUM: + case COUNT: + case STRING_LITERAL: + case DELIMITED_IDENTIFIER: + case REGULAR_IDENTIFIER: + case SCIENTIFIC_NUMBER: + case UNSIGNED_FLOAT: + case UNSIGNED_INTEGER: + op = ValueExpressionPrimary(); + break; + default: + jj_la1[59] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } } - } } - {if (true) return op;} + { + if (true) + return op; + } throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("StringFactor"); } } - final public GeometryValue<GeometryFunction> GeometryExpression() throws ParseException { + final public GeometryValue<GeometryFunction> GeometryExpression() throws ParseException{ trace_call("GeometryExpression"); - try { - ADQLColumn col = null; GeometryFunction gf = null; - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case DELIMITED_IDENTIFIER: - case REGULAR_IDENTIFIER: - col = Column(); - break; - case BOX: - case CENTROID: - case CIRCLE: - case POINT: - case POLYGON: - case REGION: - gf = GeometryValueFunction(); - break; - default: - jj_la1[60] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); + try{ + ADQLColumn col = null; + GeometryFunction gf = null; + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case DELIMITED_IDENTIFIER: + case REGULAR_IDENTIFIER: + col = Column(); + break; + case BOX: + case CENTROID: + case CIRCLE: + case POINT: + case POLYGON: + case REGION: + gf = GeometryValueFunction(); + break; + default: + jj_la1[60] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + if (col != null){ + if (true) + return new GeometryValue<GeometryFunction>(col); + }else{ + if (true) + return new GeometryValue<GeometryFunction>(gf); } - if (col != null) - {if (true) return new GeometryValue<GeometryFunction>(col);} - else - {if (true) return new GeometryValue<GeometryFunction>(gf);} throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("GeometryExpression"); } } @@ -1842,30 +2030,32 @@ public class ADQLParser implements ADQLParserConstants { /* ********************************** */ /* BOOLEAN EXPRESSIONS (WHERE clause) */ /* ********************************** */ - final public ClauseConstraints ConditionsList(ClauseConstraints clause) throws ParseException { + final public ClauseConstraints ConditionsList(ClauseConstraints clause) throws ParseException{ trace_call("ConditionsList"); - try { - ADQLConstraint constraint = null; Token op = null; boolean notOp = false; - try { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case NOT: - jj_consume_token(NOT); - notOp = true; - break; - default: - jj_la1[61] = jj_gen; - ; + try{ + ADQLConstraint constraint = null; + Token op = null; + boolean notOp = false; + try{ + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case NOT: + jj_consume_token(NOT); + notOp = true; + break; + default: + jj_la1[61] = jj_gen; + ; } constraint = Constraint(); - if (notOp) constraint = queryFactory.createNot(constraint); + if (notOp) + constraint = queryFactory.createNot(constraint); notOp = false; if (clause instanceof ADQLConstraint) clause.add(constraint); else clause.add(constraint); - label_10: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + label_10: while(true){ + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ case AND: case OR: ; @@ -1873,8 +2063,8 @@ public class ADQLParser implements ADQLParserConstants { default: jj_la1[62] = jj_gen; break label_10; - } - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + } + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ case AND: op = jj_consume_token(AND); break; @@ -1885,8 +2075,8 @@ public class ADQLParser implements ADQLParserConstants { jj_la1[63] = jj_gen; jj_consume_token(-1); throw new ParseException(); - } - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + } + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ case NOT: jj_consume_token(NOT); notOp = true; @@ -1894,317 +2084,373 @@ public class ADQLParser implements ADQLParserConstants { default: jj_la1[64] = jj_gen; ; - } - constraint = Constraint(); - if (notOp) constraint = queryFactory.createNot(constraint); - notOp = false; - if (clause instanceof ADQLConstraint) - clause.add(op.image, constraint); - else - clause.add(op.image, constraint); } - } catch (Exception ex) { - {if (true) throw generateParseException(ex);} + constraint = Constraint(); + if (notOp) + constraint = queryFactory.createNot(constraint); + notOp = false; + if (clause instanceof ADQLConstraint) + clause.add(op.image, constraint); + else + clause.add(op.image, constraint); + } + }catch(Exception ex){ + { + if (true) + throw generateParseException(ex); + } + } + { + if (true) + return clause; } - {if (true) return clause;} throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("ConditionsList"); } } - final public ADQLConstraint Constraint() throws ParseException { + final public ADQLConstraint Constraint() throws ParseException{ trace_call("Constraint"); - try { - ADQLConstraint constraint = null; - if (jj_2_9(2147483647)) { + try{ + ADQLConstraint constraint = null; + if (jj_2_9(2147483647)){ constraint = Predicate(); - } else { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case LEFT_PAR: - jj_consume_token(LEFT_PAR); - try{ - constraint = queryFactory.createGroupOfConstraints(); - }catch(Exception ex){ - {if (true) throw generateParseException(ex);} - } - ConditionsList((ConstraintsGroup)constraint); - jj_consume_token(RIGHT_PAR); - break; - default: - jj_la1[65] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); + }else{ + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case LEFT_PAR: + jj_consume_token(LEFT_PAR); + try{ + constraint = queryFactory.createGroupOfConstraints(); + }catch(Exception ex){ + { + if (true) + throw generateParseException(ex); + } + } + ConditionsList((ConstraintsGroup)constraint); + jj_consume_token(RIGHT_PAR); + break; + default: + jj_la1[65] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); } } - {if (true) return constraint;} + { + if (true) + return constraint; + } throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("Constraint"); } } - final public ADQLConstraint Predicate() throws ParseException { + final public ADQLConstraint Predicate() throws ParseException{ trace_call("Predicate"); - try { - ADQLQuery q=null; ADQLColumn column=null; ADQLOperand strExpr1=null, strExpr2=null; ADQLOperand op; Token notToken = null; ADQLConstraint constraint = null; - try { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case EXISTS: - jj_consume_token(EXISTS); - q = SubQueryExpression(); - {if (true) return queryFactory.createExists(q);} - break; - default: - jj_la1[70] = jj_gen; - if (jj_2_11(2147483647)) { - column = Column(); - jj_consume_token(IS); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case NOT: - notToken = jj_consume_token(NOT); - break; - default: - jj_la1[66] = jj_gen; - ; - } - jj_consume_token(NULL); - {if (true) return queryFactory.createIsNull((notToken!=null), column);} - } else if (jj_2_12(2147483647)) { - strExpr1 = StringExpression(); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case NOT: - notToken = jj_consume_token(NOT); - break; - default: - jj_la1[67] = jj_gen; - ; + try{ + ADQLQuery q = null; + ADQLColumn column = null; + ADQLOperand strExpr1 = null, strExpr2 = null; + ADQLOperand op; + Token notToken = null; + ADQLConstraint constraint = null; + try{ + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case EXISTS: + jj_consume_token(EXISTS); + q = SubQueryExpression(); + { + if (true) + return queryFactory.createExists(q); } - jj_consume_token(LIKE); - strExpr2 = StringExpression(); - {if (true) return queryFactory.createComparison(strExpr1, (notToken==null)?ComparisonOperator.LIKE:ComparisonOperator.NOTLIKE, strExpr2);} - } else { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case LEFT_PAR: - case PLUS: - case MINUS: - case AVG: - case MAX: - case MIN: - case SUM: - case COUNT: - case BOX: - case CENTROID: - case CIRCLE: - case POINT: - case POLYGON: - case REGION: - case CONTAINS: - case INTERSECTS: - case AREA: - case COORD1: - case COORD2: - case COORDSYS: - case DISTANCE: - case ABS: - case CEILING: - case DEGREES: - case EXP: - case FLOOR: - case LOG: - case LOG10: - case MOD: - case PI: - case POWER: - case RADIANS: - case RAND: - case ROUND: - case SQRT: - case TRUNCATE: - case ACOS: - case ASIN: - case ATAN: - case ATAN2: - case COS: - case COT: - case SIN: - case TAN: - case STRING_LITERAL: - case DELIMITED_IDENTIFIER: - case REGULAR_IDENTIFIER: - case SCIENTIFIC_NUMBER: - case UNSIGNED_FLOAT: - case UNSIGNED_INTEGER: - op = ValueExpression(); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case EQUAL: - case NOT_EQUAL: - case LESS_THAN: - case LESS_EQUAL_THAN: - case GREATER_THAN: - case GREATER_EQUAL_THAN: - constraint = ComparisonEnd(op); - break; - default: - jj_la1[68] = jj_gen; - if (jj_2_10(2)) { - constraint = BetweenEnd(op); - } else { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case NOT: - case IN: - constraint = InEnd(op); - break; - default: - jj_la1[69] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); + break; + default: + jj_la1[70] = jj_gen; + if (jj_2_11(2147483647)){ + column = Column(); + jj_consume_token(IS); + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case NOT: + notToken = jj_consume_token(NOT); + break; + default: + jj_la1[66] = jj_gen; + ; + } + jj_consume_token(NULL); + { + if (true) + return queryFactory.createIsNull((notToken != null), column); + } + }else if (jj_2_12(2147483647)){ + strExpr1 = StringExpression(); + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case NOT: + notToken = jj_consume_token(NOT); + break; + default: + jj_la1[67] = jj_gen; + ; + } + jj_consume_token(LIKE); + strExpr2 = StringExpression(); + { + if (true) + return queryFactory.createComparison(strExpr1, (notToken == null) ? ComparisonOperator.LIKE : ComparisonOperator.NOTLIKE, strExpr2); + } + }else{ + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case LEFT_PAR: + case PLUS: + case MINUS: + case AVG: + case MAX: + case MIN: + case SUM: + case COUNT: + case BOX: + case CENTROID: + case CIRCLE: + case POINT: + case POLYGON: + case REGION: + case CONTAINS: + case INTERSECTS: + case AREA: + case COORD1: + case COORD2: + case COORDSYS: + case DISTANCE: + case ABS: + case CEILING: + case DEGREES: + case EXP: + case FLOOR: + case LOG: + case LOG10: + case MOD: + case PI: + case POWER: + case RADIANS: + case RAND: + case ROUND: + case SQRT: + case TRUNCATE: + case ACOS: + case ASIN: + case ATAN: + case ATAN2: + case COS: + case COT: + case SIN: + case TAN: + case STRING_LITERAL: + case DELIMITED_IDENTIFIER: + case REGULAR_IDENTIFIER: + case SCIENTIFIC_NUMBER: + case UNSIGNED_FLOAT: + case UNSIGNED_INTEGER: + op = ValueExpression(); + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case EQUAL: + case NOT_EQUAL: + case LESS_THAN: + case LESS_EQUAL_THAN: + case GREATER_THAN: + case GREATER_EQUAL_THAN: + constraint = ComparisonEnd(op); + break; + default: + jj_la1[68] = jj_gen; + if (jj_2_10(2)){ + constraint = BetweenEnd(op); + }else{ + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case NOT: + case IN: + constraint = InEnd(op); + break; + default: + jj_la1[69] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + } } - } + break; + default: + jj_la1[71] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); } - break; - default: - jj_la1[71] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); } - } } - } catch (Exception ex) { - {if (true) throw generateParseException(ex);} + }catch(Exception ex){ + { + if (true) + throw generateParseException(ex); + } + } + { + if (true) + return constraint; } - {if (true) return constraint;} throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("Predicate"); } } - final public Comparison ComparisonEnd(ADQLOperand leftOp) throws ParseException { + final public Comparison ComparisonEnd(ADQLOperand leftOp) throws ParseException{ trace_call("ComparisonEnd"); - try { - Token comp; ADQLOperand rightOp; - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case EQUAL: - comp = jj_consume_token(EQUAL); - break; - case NOT_EQUAL: - comp = jj_consume_token(NOT_EQUAL); - break; - case LESS_THAN: - comp = jj_consume_token(LESS_THAN); - break; - case LESS_EQUAL_THAN: - comp = jj_consume_token(LESS_EQUAL_THAN); - break; - case GREATER_THAN: - comp = jj_consume_token(GREATER_THAN); - break; - case GREATER_EQUAL_THAN: - comp = jj_consume_token(GREATER_EQUAL_THAN); - break; - default: - jj_la1[72] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); + try{ + Token comp; + ADQLOperand rightOp; + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case EQUAL: + comp = jj_consume_token(EQUAL); + break; + case NOT_EQUAL: + comp = jj_consume_token(NOT_EQUAL); + break; + case LESS_THAN: + comp = jj_consume_token(LESS_THAN); + break; + case LESS_EQUAL_THAN: + comp = jj_consume_token(LESS_EQUAL_THAN); + break; + case GREATER_THAN: + comp = jj_consume_token(GREATER_THAN); + break; + case GREATER_EQUAL_THAN: + comp = jj_consume_token(GREATER_EQUAL_THAN); + break; + default: + jj_la1[72] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); } rightOp = ValueExpression(); try{ - {if (true) return queryFactory.createComparison(leftOp, ComparisonOperator.getOperator(comp.image), rightOp);} + { + if (true) + return queryFactory.createComparison(leftOp, ComparisonOperator.getOperator(comp.image), rightOp); + } }catch(Exception ex){ - {if (true) throw generateParseException(ex);} + { + if (true) + throw generateParseException(ex); + } } throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("ComparisonEnd"); } } - final public Between BetweenEnd(ADQLOperand leftOp) throws ParseException { + final public Between BetweenEnd(ADQLOperand leftOp) throws ParseException{ trace_call("BetweenEnd"); - try { - Token notToken=null; ADQLOperand min, max; - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case NOT: - notToken = jj_consume_token(NOT); - break; - default: - jj_la1[73] = jj_gen; - ; + try{ + Token notToken = null; + ADQLOperand min, max; + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case NOT: + notToken = jj_consume_token(NOT); + break; + default: + jj_la1[73] = jj_gen; + ; } jj_consume_token(BETWEEN); min = ValueExpression(); jj_consume_token(AND); max = ValueExpression(); try{ - {if (true) return queryFactory.createBetween((notToken!=null), leftOp, min, max);} + { + if (true) + return queryFactory.createBetween((notToken != null), leftOp, min, max); + } }catch(Exception ex){ - {if (true) throw generateParseException(ex);} + { + if (true) + throw generateParseException(ex); + } } throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("BetweenEnd"); } } - final public In InEnd(ADQLOperand leftOp) throws ParseException { + final public In InEnd(ADQLOperand leftOp) throws ParseException{ trace_call("InEnd"); - try { - Token not=null; ADQLQuery q = null; ADQLOperand item; Vector<ADQLOperand> items = new Vector<ADQLOperand>(); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case NOT: - not = jj_consume_token(NOT); - break; - default: - jj_la1[74] = jj_gen; - ; - } - jj_consume_token(IN); - if (jj_2_13(2)) { - q = SubQueryExpression(); - } else { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case LEFT_PAR: - jj_consume_token(LEFT_PAR); - item = ValueExpression(); - items.add(item); - label_11: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case COMMA: - ; - break; - default: - jj_la1[75] = jj_gen; - break label_11; + try{ + Token not = null; + ADQLQuery q = null; + ADQLOperand item; + Vector<ADQLOperand> items = new Vector<ADQLOperand>(); + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case NOT: + not = jj_consume_token(NOT); + break; + default: + jj_la1[74] = jj_gen; + ; + } + jj_consume_token(IN); + if (jj_2_13(2)){ + q = SubQueryExpression(); + }else{ + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case LEFT_PAR: + jj_consume_token(LEFT_PAR); + item = ValueExpression(); + items.add(item); + label_11: while(true){ + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case COMMA: + ; + break; + default: + jj_la1[75] = jj_gen; + break label_11; } jj_consume_token(COMMA); item = ValueExpression(); items.add(item); } - jj_consume_token(RIGHT_PAR); - break; - default: - jj_la1[76] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); + jj_consume_token(RIGHT_PAR); + break; + default: + jj_la1[76] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); } } try{ - if (q != null) - {if (true) return queryFactory.createIn(leftOp, q, not!=null);} - else{ + if (q != null){ + if (true) + return queryFactory.createIn(leftOp, q, not != null); + }else{ ADQLOperand[] list = new ADQLOperand[items.size()]; - int i=0; + int i = 0; for(ADQLOperand op : items) list[i++] = op; - {if (true) return queryFactory.createIn(leftOp, list, not!=null);} + { + if (true) + return queryFactory.createIn(leftOp, list, not != null); + } } }catch(Exception ex){ - {if (true) throw generateParseException(ex);} + { + if (true) + throw generateParseException(ex); + } } throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("InEnd"); } } @@ -2212,133 +2458,141 @@ public class ADQLParser implements ADQLParserConstants { /* ************* */ /* SQL FUNCTIONS */ /* ************* */ - final public SQLFunction SqlFunction() throws ParseException { + final public SQLFunction SqlFunction() throws ParseException{ trace_call("SqlFunction"); - try { - Token fct, all=null, distinct=null; ADQLOperand op=null; SQLFunction funct = null; - try { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case COUNT: - jj_consume_token(COUNT); - jj_consume_token(LEFT_PAR); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case QUANTIFIER: - distinct = jj_consume_token(QUANTIFIER); - break; - default: - jj_la1[77] = jj_gen; - ; - } - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case ASTERISK: - all = jj_consume_token(ASTERISK); - break; - case LEFT_PAR: - case PLUS: - case MINUS: - case AVG: - case MAX: - case MIN: - case SUM: + try{ + Token fct, all = null, distinct = null; + ADQLOperand op = null; + SQLFunction funct = null; + try{ + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ case COUNT: - case BOX: - case CENTROID: - case CIRCLE: - case POINT: - case POLYGON: - case REGION: - case CONTAINS: - case INTERSECTS: - case AREA: - case COORD1: - case COORD2: - case COORDSYS: - case DISTANCE: - case ABS: - case CEILING: - case DEGREES: - case EXP: - case FLOOR: - case LOG: - case LOG10: - case MOD: - case PI: - case POWER: - case RADIANS: - case RAND: - case ROUND: - case SQRT: - case TRUNCATE: - case ACOS: - case ASIN: - case ATAN: - case ATAN2: - case COS: - case COT: - case SIN: - case TAN: - case STRING_LITERAL: - case DELIMITED_IDENTIFIER: - case REGULAR_IDENTIFIER: - case SCIENTIFIC_NUMBER: - case UNSIGNED_FLOAT: - case UNSIGNED_INTEGER: - op = ValueExpression(); + jj_consume_token(COUNT); + jj_consume_token(LEFT_PAR); + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case QUANTIFIER: + distinct = jj_consume_token(QUANTIFIER); + break; + default: + jj_la1[77] = jj_gen; + ; + } + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case ASTERISK: + all = jj_consume_token(ASTERISK); + break; + case LEFT_PAR: + case PLUS: + case MINUS: + case AVG: + case MAX: + case MIN: + case SUM: + case COUNT: + case BOX: + case CENTROID: + case CIRCLE: + case POINT: + case POLYGON: + case REGION: + case CONTAINS: + case INTERSECTS: + case AREA: + case COORD1: + case COORD2: + case COORDSYS: + case DISTANCE: + case ABS: + case CEILING: + case DEGREES: + case EXP: + case FLOOR: + case LOG: + case LOG10: + case MOD: + case PI: + case POWER: + case RADIANS: + case RAND: + case ROUND: + case SQRT: + case TRUNCATE: + case ACOS: + case ASIN: + case ATAN: + case ATAN2: + case COS: + case COT: + case SIN: + case TAN: + case STRING_LITERAL: + case DELIMITED_IDENTIFIER: + case REGULAR_IDENTIFIER: + case SCIENTIFIC_NUMBER: + case UNSIGNED_FLOAT: + case UNSIGNED_INTEGER: + op = ValueExpression(); + break; + default: + jj_la1[78] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + jj_consume_token(RIGHT_PAR); + funct = queryFactory.createSQLFunction((all != null) ? SQLFunctionType.COUNT_ALL : SQLFunctionType.COUNT, op, distinct != null && distinct.image.equalsIgnoreCase("distinct")); break; - default: - jj_la1[78] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - jj_consume_token(RIGHT_PAR); - funct = queryFactory.createSQLFunction((all!=null)?SQLFunctionType.COUNT_ALL:SQLFunctionType.COUNT, op, distinct != null && distinct.image.equalsIgnoreCase("distinct")); - break; - case AVG: - case MAX: - case MIN: - case SUM: - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case AVG: - fct = jj_consume_token(AVG); - break; case MAX: - fct = jj_consume_token(MAX); - break; case MIN: - fct = jj_consume_token(MIN); - break; case SUM: - fct = jj_consume_token(SUM); + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case AVG: + fct = jj_consume_token(AVG); + break; + case MAX: + fct = jj_consume_token(MAX); + break; + case MIN: + fct = jj_consume_token(MIN); + break; + case SUM: + fct = jj_consume_token(SUM); + break; + default: + jj_la1[79] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + jj_consume_token(LEFT_PAR); + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case QUANTIFIER: + distinct = jj_consume_token(QUANTIFIER); + break; + default: + jj_la1[80] = jj_gen; + ; + } + op = ValueExpression(); + jj_consume_token(RIGHT_PAR); + funct = queryFactory.createSQLFunction(SQLFunctionType.valueOf(fct.image.toUpperCase()), op, distinct != null && distinct.image.equalsIgnoreCase("distinct")); break; default: - jj_la1[79] = jj_gen; + jj_la1[81] = jj_gen; jj_consume_token(-1); throw new ParseException(); - } - jj_consume_token(LEFT_PAR); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case QUANTIFIER: - distinct = jj_consume_token(QUANTIFIER); - break; - default: - jj_la1[80] = jj_gen; - ; - } - op = ValueExpression(); - jj_consume_token(RIGHT_PAR); - funct = queryFactory.createSQLFunction(SQLFunctionType.valueOf(fct.image.toUpperCase()), op, distinct != null && distinct.image.equalsIgnoreCase("distinct")); - break; - default: - jj_la1[81] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); } - } catch (Exception ex) { - {if (true) throw generateParseException(ex);} + }catch(Exception ex){ + { + if (true) + throw generateParseException(ex); + } + } + { + if (true) + return funct; } - {if (true) return funct;} throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("SqlFunction"); } } @@ -2346,270 +2600,308 @@ public class ADQLParser implements ADQLParserConstants { /* ************** */ /* ADQL FUNCTIONS */ /* ************** */ - final public ADQLOperand[] Coordinates() throws ParseException { + final public ADQLOperand[] Coordinates() throws ParseException{ trace_call("Coordinates"); - try { + try{ ADQLOperand[] ops = new ADQLOperand[2]; ops[0] = NumericExpression(); jj_consume_token(COMMA); ops[1] = NumericExpression(); - {if (true) return ops;} + { + if (true) + return ops; + } throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("Coordinates"); } } - final public GeometryFunction GeometryFunction() throws ParseException { + final public GeometryFunction GeometryFunction() throws ParseException{ trace_call("GeometryFunction"); - try { - Token t=null; GeometryValue<GeometryFunction> gvf1, gvf2; GeometryValue<PointFunction> gvp1, gvp2; GeometryFunction gf = null; PointFunction p1=null, p2=null; ADQLColumn col1 = null, col2 = null; - try { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case CONTAINS: - case INTERSECTS: - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + try{ + Token t = null; + GeometryValue<GeometryFunction> gvf1, gvf2; + GeometryValue<PointFunction> gvp1, gvp2; + GeometryFunction gf = null; + PointFunction p1 = null, p2 = null; + ADQLColumn col1 = null, col2 = null; + try{ + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ case CONTAINS: - t = jj_consume_token(CONTAINS); - break; case INTERSECTS: - t = jj_consume_token(INTERSECTS); - break; - default: - jj_la1[82] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - jj_consume_token(LEFT_PAR); - gvf1 = GeometryExpression(); - jj_consume_token(COMMA); - gvf2 = GeometryExpression(); - jj_consume_token(RIGHT_PAR); - if (t.image.equalsIgnoreCase("contains")) - gf = queryFactory.createContains(gvf1, gvf2); - else - gf = queryFactory.createIntersects(gvf1, gvf2); - break; - case AREA: - jj_consume_token(AREA); - jj_consume_token(LEFT_PAR); - gvf1 = GeometryExpression(); - jj_consume_token(RIGHT_PAR); - gf = queryFactory.createArea(gvf1); - break; - case COORD1: - jj_consume_token(COORD1); - jj_consume_token(LEFT_PAR); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case POINT: - p1 = Point(); - gf = queryFactory.createCoord1(p1); - break; - case DELIMITED_IDENTIFIER: - case REGULAR_IDENTIFIER: - col1 = Column(); - gf = queryFactory.createCoord1(col1); - break; - default: - jj_la1[83] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - jj_consume_token(RIGHT_PAR); - break; - case COORD2: - jj_consume_token(COORD2); - jj_consume_token(LEFT_PAR); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case POINT: - p1 = Point(); - gf = queryFactory.createCoord2(p1); - break; - case DELIMITED_IDENTIFIER: - case REGULAR_IDENTIFIER: - col1 = Column(); - gf = queryFactory.createCoord2(col1); + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case CONTAINS: + t = jj_consume_token(CONTAINS); + break; + case INTERSECTS: + t = jj_consume_token(INTERSECTS); + break; + default: + jj_la1[82] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + jj_consume_token(LEFT_PAR); + gvf1 = GeometryExpression(); + jj_consume_token(COMMA); + gvf2 = GeometryExpression(); + jj_consume_token(RIGHT_PAR); + if (t.image.equalsIgnoreCase("contains")) + gf = queryFactory.createContains(gvf1, gvf2); + else + gf = queryFactory.createIntersects(gvf1, gvf2); break; - default: - jj_la1[84] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - jj_consume_token(RIGHT_PAR); - break; - case DISTANCE: - jj_consume_token(DISTANCE); - jj_consume_token(LEFT_PAR); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case POINT: - p1 = Point(); + case AREA: + jj_consume_token(AREA); + jj_consume_token(LEFT_PAR); + gvf1 = GeometryExpression(); + jj_consume_token(RIGHT_PAR); + gf = queryFactory.createArea(gvf1); break; - case DELIMITED_IDENTIFIER: - case REGULAR_IDENTIFIER: - col1 = Column(); + case COORD1: + jj_consume_token(COORD1); + jj_consume_token(LEFT_PAR); + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case POINT: + p1 = Point(); + gf = queryFactory.createCoord1(p1); + break; + case DELIMITED_IDENTIFIER: + case REGULAR_IDENTIFIER: + col1 = Column(); + gf = queryFactory.createCoord1(col1); + break; + default: + jj_la1[83] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + jj_consume_token(RIGHT_PAR); break; - default: - jj_la1[85] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - if (p1 != null) - gvp1 = new GeometryValue<PointFunction>(p1); - else - gvp1 = new GeometryValue<PointFunction>(col1); - jj_consume_token(COMMA); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case POINT: - p2 = Point(); + case COORD2: + jj_consume_token(COORD2); + jj_consume_token(LEFT_PAR); + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case POINT: + p1 = Point(); + gf = queryFactory.createCoord2(p1); + break; + case DELIMITED_IDENTIFIER: + case REGULAR_IDENTIFIER: + col1 = Column(); + gf = queryFactory.createCoord2(col1); + break; + default: + jj_la1[84] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + jj_consume_token(RIGHT_PAR); break; - case DELIMITED_IDENTIFIER: - case REGULAR_IDENTIFIER: - col2 = Column(); + case DISTANCE: + jj_consume_token(DISTANCE); + jj_consume_token(LEFT_PAR); + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case POINT: + p1 = Point(); + break; + case DELIMITED_IDENTIFIER: + case REGULAR_IDENTIFIER: + col1 = Column(); + break; + default: + jj_la1[85] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + if (p1 != null) + gvp1 = new GeometryValue<PointFunction>(p1); + else + gvp1 = new GeometryValue<PointFunction>(col1); + jj_consume_token(COMMA); + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case POINT: + p2 = Point(); + break; + case DELIMITED_IDENTIFIER: + case REGULAR_IDENTIFIER: + col2 = Column(); + break; + default: + jj_la1[86] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + if (p2 != null) + gvp2 = new GeometryValue<PointFunction>(p2); + else + gvp2 = new GeometryValue<PointFunction>(col2); + jj_consume_token(RIGHT_PAR); + gf = queryFactory.createDistance(gvp1, gvp2); break; default: - jj_la1[86] = jj_gen; + jj_la1[87] = jj_gen; jj_consume_token(-1); throw new ParseException(); - } - if (p2 != null) - gvp2 = new GeometryValue<PointFunction>(p2); - else - gvp2 = new GeometryValue<PointFunction>(col2); - jj_consume_token(RIGHT_PAR); - gf = queryFactory.createDistance(gvp1, gvp2); - break; - default: - jj_la1[87] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); } - } catch (Exception ex) { - {if (true) throw generateParseException(ex);} + }catch(Exception ex){ + { + if (true) + throw generateParseException(ex); + } + } + { + if (true) + return gf; } - {if (true) return gf;} throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("GeometryFunction"); } } - final public ADQLOperand CoordinateSystem() throws ParseException { + final public ADQLOperand CoordinateSystem() throws ParseException{ trace_call("CoordinateSystem"); - try { - Token oldToken = token; ADQLOperand coordSys=null; + try{ + Token oldToken = token; + ADQLOperand coordSys = null; coordSys = StringExpression(); if (allowedCoordSys.size() > 0){ TextPosition position = new TextPosition(oldToken.next, token); - if (coordSys == null) - {if (true) throw new ParseException("A coordinate system must always be provided !", position);} - if (coordSys instanceof StringConstant && !isAllowedCoordSys(((StringConstant)coordSys).getValue())) - {if (true) throw new ParseException("\u005c""+coordSys.toADQL()+"\u005c" is not an allowed coordinate systems !", position);} + if (coordSys == null){ + if (true) + throw new ParseException("A coordinate system must always be provided !", position); + } + if (coordSys instanceof StringConstant && !isAllowedCoordSys(((StringConstant)coordSys).getValue())){ + if (true) + throw new ParseException("\u005c"" + coordSys.toADQL() + "\u005c" is not an allowed coordinate systems !", position); + } } - {if (true) return coordSys;} + { + if (true) + return coordSys; + } throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("CoordinateSystem"); } } - final public GeometryFunction GeometryValueFunction() throws ParseException { + final public GeometryFunction GeometryValueFunction() throws ParseException{ trace_call("GeometryValueFunction"); - try { - ADQLOperand coordSys; ADQLOperand width, height; ADQLOperand[] coords, tmp; Vector<ADQLOperand> vCoords; ADQLOperand op=null; GeometryValue<GeometryFunction> gvf = null; GeometryFunction gf = null; - try { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case BOX: - jj_consume_token(BOX); - jj_consume_token(LEFT_PAR); - coordSys = CoordinateSystem(); - jj_consume_token(COMMA); - coords = Coordinates(); - jj_consume_token(COMMA); - width = NumericExpression(); - jj_consume_token(COMMA); - height = NumericExpression(); - jj_consume_token(RIGHT_PAR); - gf = queryFactory.createBox(coordSys, coords[0], coords[1], width, height); - break; - case CENTROID: - jj_consume_token(CENTROID); - jj_consume_token(LEFT_PAR); - gvf = GeometryExpression(); - jj_consume_token(RIGHT_PAR); - gf = queryFactory.createCentroid(gvf); - break; - case CIRCLE: - jj_consume_token(CIRCLE); - jj_consume_token(LEFT_PAR); - coordSys = CoordinateSystem(); - jj_consume_token(COMMA); - coords = Coordinates(); - jj_consume_token(COMMA); - width = NumericExpression(); - jj_consume_token(RIGHT_PAR); - gf = queryFactory.createCircle(coordSys, coords[0], coords[1], width); - break; - case POINT: - gf = Point(); - break; - case POLYGON: - jj_consume_token(POLYGON); - jj_consume_token(LEFT_PAR); - coordSys = CoordinateSystem(); - vCoords = new Vector<ADQLOperand>(); - jj_consume_token(COMMA); - tmp = Coordinates(); - vCoords.add(tmp[0]); vCoords.add(tmp[1]); - jj_consume_token(COMMA); - tmp = Coordinates(); - vCoords.add(tmp[0]); vCoords.add(tmp[1]); - jj_consume_token(COMMA); - tmp = Coordinates(); - vCoords.add(tmp[0]); vCoords.add(tmp[1]); - label_12: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case COMMA: - ; - break; - default: - jj_la1[88] = jj_gen; - break label_12; + try{ + ADQLOperand coordSys; + ADQLOperand width, height; + ADQLOperand[] coords, tmp; + Vector<ADQLOperand> vCoords; + ADQLOperand op = null; + GeometryValue<GeometryFunction> gvf = null; + GeometryFunction gf = null; + try{ + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case BOX: + jj_consume_token(BOX); + jj_consume_token(LEFT_PAR); + coordSys = CoordinateSystem(); + jj_consume_token(COMMA); + coords = Coordinates(); + jj_consume_token(COMMA); + width = NumericExpression(); + jj_consume_token(COMMA); + height = NumericExpression(); + jj_consume_token(RIGHT_PAR); + gf = queryFactory.createBox(coordSys, coords[0], coords[1], width, height); + break; + case CENTROID: + jj_consume_token(CENTROID); + jj_consume_token(LEFT_PAR); + gvf = GeometryExpression(); + jj_consume_token(RIGHT_PAR); + gf = queryFactory.createCentroid(gvf); + break; + case CIRCLE: + jj_consume_token(CIRCLE); + jj_consume_token(LEFT_PAR); + coordSys = CoordinateSystem(); + jj_consume_token(COMMA); + coords = Coordinates(); + jj_consume_token(COMMA); + width = NumericExpression(); + jj_consume_token(RIGHT_PAR); + gf = queryFactory.createCircle(coordSys, coords[0], coords[1], width); + break; + case POINT: + gf = Point(); + break; + case POLYGON: + jj_consume_token(POLYGON); + jj_consume_token(LEFT_PAR); + coordSys = CoordinateSystem(); + vCoords = new Vector<ADQLOperand>(); + jj_consume_token(COMMA); + tmp = Coordinates(); + vCoords.add(tmp[0]); + vCoords.add(tmp[1]); + jj_consume_token(COMMA); + tmp = Coordinates(); + vCoords.add(tmp[0]); + vCoords.add(tmp[1]); + jj_consume_token(COMMA); + tmp = Coordinates(); + vCoords.add(tmp[0]); + vCoords.add(tmp[1]); + label_12: while(true){ + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case COMMA: + ; + break; + default: + jj_la1[88] = jj_gen; + break label_12; } jj_consume_token(COMMA); tmp = Coordinates(); - vCoords.add(tmp[0]); vCoords.add(tmp[1]); + vCoords.add(tmp[0]); + vCoords.add(tmp[1]); } - jj_consume_token(RIGHT_PAR); - gf = queryFactory.createPolygon(coordSys, vCoords); - break; - case REGION: - jj_consume_token(REGION); - jj_consume_token(LEFT_PAR); - op = StringExpression(); - jj_consume_token(RIGHT_PAR); - gf = queryFactory.createRegion(op); - break; - default: - jj_la1[89] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); + jj_consume_token(RIGHT_PAR); + gf = queryFactory.createPolygon(coordSys, vCoords); + break; + case REGION: + jj_consume_token(REGION); + jj_consume_token(LEFT_PAR); + op = StringExpression(); + jj_consume_token(RIGHT_PAR); + gf = queryFactory.createRegion(op); + break; + default: + jj_la1[89] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); } - } catch (Exception ex) { - {if (true) throw generateParseException(ex);} + }catch(Exception ex){ + { + if (true) + throw generateParseException(ex); + } + } + { + if (true) + return gf; } - {if (true) return gf;} throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("GeometryValueFunction"); } } - final public PointFunction Point() throws ParseException { + final public PointFunction Point() throws ParseException{ trace_call("Point"); - try { - ADQLOperand coordSys; ADQLOperand[] coords; + try{ + ADQLOperand coordSys; + ADQLOperand[] coords; jj_consume_token(POINT); jj_consume_token(LEFT_PAR); coordSys = CoordinateSystem(); @@ -2617,31 +2909,43 @@ public class ADQLParser implements ADQLParserConstants { coords = Coordinates(); jj_consume_token(RIGHT_PAR); try{ - {if (true) return queryFactory.createPoint(coordSys, coords[0], coords[1]);} + { + if (true) + return queryFactory.createPoint(coordSys, coords[0], coords[1]); + } }catch(Exception ex){ - {if (true) throw generateParseException(ex);} + { + if (true) + throw generateParseException(ex); + } } throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("Point"); } } - final public GeometryFunction ExtractCoordSys() throws ParseException { + final public GeometryFunction ExtractCoordSys() throws ParseException{ trace_call("ExtractCoordSys"); - try { + try{ GeometryValue<GeometryFunction> gvf; jj_consume_token(COORDSYS); jj_consume_token(LEFT_PAR); gvf = GeometryExpression(); jj_consume_token(RIGHT_PAR); try{ - {if (true) return queryFactory.createExtractCoordSys(gvf);} + { + if (true) + return queryFactory.createExtractCoordSys(gvf); + } }catch(Exception ex){ - {if (true) throw generateParseException(ex);} + { + if (true) + throw generateParseException(ex); + } } throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("ExtractCoordSys"); } } @@ -2649,850 +2953,1045 @@ public class ADQLParser implements ADQLParserConstants { /* ***************** */ /* NUMERIC FUNCTIONS */ /* ***************** */ - final public ADQLFunction NumericFunction() throws ParseException { + final public ADQLFunction NumericFunction() throws ParseException{ trace_call("NumericFunction"); - try { + try{ ADQLFunction fct; - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case ABS: - case CEILING: - case DEGREES: - case EXP: - case FLOOR: - case LOG: - case LOG10: - case MOD: - case PI: - case POWER: - case RADIANS: - case RAND: - case ROUND: - case SQRT: - case TRUNCATE: - fct = MathFunction(); - break; - case ACOS: - case ASIN: - case ATAN: - case ATAN2: - case COS: - case COT: - case SIN: - case TAN: - fct = TrigFunction(); - break; - case CONTAINS: - case INTERSECTS: - case AREA: - case COORD1: - case COORD2: - case DISTANCE: - fct = GeometryFunction(); - break; - case REGULAR_IDENTIFIER: - fct = UserDefinedFunction(); - break; - default: - jj_la1[90] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); - } - {if (true) return fct;} - throw new Error("Missing return statement in function"); - } finally { - trace_return("NumericFunction"); - } - } - - final public MathFunction MathFunction() throws ParseException { - trace_call("MathFunction"); - try { - Token fct=null; ADQLOperand param1=null, param2=null; String integerValue = null; - try { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ case ABS: - fct = jj_consume_token(ABS); - jj_consume_token(LEFT_PAR); - param1 = NumericExpression(); - jj_consume_token(RIGHT_PAR); - break; case CEILING: - fct = jj_consume_token(CEILING); - jj_consume_token(LEFT_PAR); - param1 = NumericExpression(); - jj_consume_token(RIGHT_PAR); - break; case DEGREES: - fct = jj_consume_token(DEGREES); - jj_consume_token(LEFT_PAR); - param1 = NumericExpression(); - jj_consume_token(RIGHT_PAR); - break; case EXP: - fct = jj_consume_token(EXP); - jj_consume_token(LEFT_PAR); - param1 = NumericExpression(); - jj_consume_token(RIGHT_PAR); - break; case FLOOR: - fct = jj_consume_token(FLOOR); - jj_consume_token(LEFT_PAR); - param1 = NumericExpression(); - jj_consume_token(RIGHT_PAR); - break; case LOG: - fct = jj_consume_token(LOG); - jj_consume_token(LEFT_PAR); - param1 = NumericExpression(); - jj_consume_token(RIGHT_PAR); - break; case LOG10: - fct = jj_consume_token(LOG10); - jj_consume_token(LEFT_PAR); - param1 = NumericExpression(); - jj_consume_token(RIGHT_PAR); - break; case MOD: - fct = jj_consume_token(MOD); - jj_consume_token(LEFT_PAR); - param1 = NumericExpression(); - jj_consume_token(COMMA); - param2 = NumericExpression(); - jj_consume_token(RIGHT_PAR); - break; case PI: - fct = jj_consume_token(PI); - jj_consume_token(LEFT_PAR); - jj_consume_token(RIGHT_PAR); - break; case POWER: - fct = jj_consume_token(POWER); - jj_consume_token(LEFT_PAR); - param1 = NumericExpression(); - jj_consume_token(COMMA); - param2 = NumericExpression(); - jj_consume_token(RIGHT_PAR); - break; case RADIANS: - fct = jj_consume_token(RADIANS); - jj_consume_token(LEFT_PAR); - param1 = NumericExpression(); - jj_consume_token(RIGHT_PAR); - break; case RAND: - fct = jj_consume_token(RAND); - jj_consume_token(LEFT_PAR); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case LEFT_PAR: - case PLUS: - case MINUS: - case AVG: - case MAX: - case MIN: - case SUM: - case COUNT: - case CONTAINS: - case INTERSECTS: - case AREA: - case COORD1: - case COORD2: - case DISTANCE: + case ROUND: + case SQRT: + case TRUNCATE: + fct = MathFunction(); + break; + case ACOS: + case ASIN: + case ATAN: + case ATAN2: + case COS: + case COT: + case SIN: + case TAN: + fct = TrigFunction(); + break; + case CONTAINS: + case INTERSECTS: + case AREA: + case COORD1: + case COORD2: + case DISTANCE: + fct = GeometryFunction(); + break; + case REGULAR_IDENTIFIER: + fct = UserDefinedFunction(); + break; + default: + jj_la1[90] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + { + if (true) + return fct; + } + throw new Error("Missing return statement in function"); + }finally{ + trace_return("NumericFunction"); + } + } + + final public MathFunction MathFunction() throws ParseException{ + trace_call("MathFunction"); + try{ + Token fct = null; + ADQLOperand param1 = null, param2 = null; + String integerValue = null; + try{ + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ case ABS: + fct = jj_consume_token(ABS); + jj_consume_token(LEFT_PAR); + param1 = NumericExpression(); + jj_consume_token(RIGHT_PAR); + break; case CEILING: + fct = jj_consume_token(CEILING); + jj_consume_token(LEFT_PAR); + param1 = NumericExpression(); + jj_consume_token(RIGHT_PAR); + break; case DEGREES: + fct = jj_consume_token(DEGREES); + jj_consume_token(LEFT_PAR); + param1 = NumericExpression(); + jj_consume_token(RIGHT_PAR); + break; case EXP: + fct = jj_consume_token(EXP); + jj_consume_token(LEFT_PAR); + param1 = NumericExpression(); + jj_consume_token(RIGHT_PAR); + break; case FLOOR: + fct = jj_consume_token(FLOOR); + jj_consume_token(LEFT_PAR); + param1 = NumericExpression(); + jj_consume_token(RIGHT_PAR); + break; case LOG: + fct = jj_consume_token(LOG); + jj_consume_token(LEFT_PAR); + param1 = NumericExpression(); + jj_consume_token(RIGHT_PAR); + break; case LOG10: + fct = jj_consume_token(LOG10); + jj_consume_token(LEFT_PAR); + param1 = NumericExpression(); + jj_consume_token(RIGHT_PAR); + break; case MOD: + fct = jj_consume_token(MOD); + jj_consume_token(LEFT_PAR); + param1 = NumericExpression(); + jj_consume_token(COMMA); + param2 = NumericExpression(); + jj_consume_token(RIGHT_PAR); + break; case PI: + fct = jj_consume_token(PI); + jj_consume_token(LEFT_PAR); + jj_consume_token(RIGHT_PAR); + break; case POWER: + fct = jj_consume_token(POWER); + jj_consume_token(LEFT_PAR); + param1 = NumericExpression(); + jj_consume_token(COMMA); + param2 = NumericExpression(); + jj_consume_token(RIGHT_PAR); + break; case RADIANS: + fct = jj_consume_token(RADIANS); + jj_consume_token(LEFT_PAR); + param1 = NumericExpression(); + jj_consume_token(RIGHT_PAR); + break; case RAND: + fct = jj_consume_token(RAND); + jj_consume_token(LEFT_PAR); + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case LEFT_PAR: + case PLUS: + case MINUS: + case AVG: + case MAX: + case MIN: + case SUM: + case COUNT: + case CONTAINS: + case INTERSECTS: + case AREA: + case COORD1: + case COORD2: + case DISTANCE: + case ABS: + case CEILING: + case DEGREES: + case EXP: + case FLOOR: + case LOG: + case LOG10: + case MOD: + case PI: + case POWER: + case RADIANS: + case RAND: + case ROUND: + case SQRT: + case TRUNCATE: + case ACOS: + case ASIN: + case ATAN: + case ATAN2: + case COS: + case COT: + case SIN: + case TAN: + case STRING_LITERAL: + case DELIMITED_IDENTIFIER: + case REGULAR_IDENTIFIER: + case SCIENTIFIC_NUMBER: + case UNSIGNED_FLOAT: + case UNSIGNED_INTEGER: + param1 = NumericExpression(); + break; + default: + jj_la1[91] = jj_gen; + ; + } + jj_consume_token(RIGHT_PAR); + break; case ROUND: + fct = jj_consume_token(ROUND); + jj_consume_token(LEFT_PAR); + param1 = NumericExpression(); + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case COMMA: + jj_consume_token(COMMA); + integerValue = SignedInteger(); + param2 = queryFactory.createOperation(queryFactory.createNumericConstant(integerValue), null, null); + break; + default: + jj_la1[92] = jj_gen; + ; + } + jj_consume_token(RIGHT_PAR); + break; case SQRT: + fct = jj_consume_token(SQRT); + jj_consume_token(LEFT_PAR); + param1 = NumericExpression(); + jj_consume_token(RIGHT_PAR); + break; case TRUNCATE: - case ACOS: - case ASIN: - case ATAN: - case ATAN2: - case COS: - case COT: - case SIN: - case TAN: - case STRING_LITERAL: - case DELIMITED_IDENTIFIER: - case REGULAR_IDENTIFIER: - case SCIENTIFIC_NUMBER: - case UNSIGNED_FLOAT: - case UNSIGNED_INTEGER: + fct = jj_consume_token(TRUNCATE); + jj_consume_token(LEFT_PAR); param1 = NumericExpression(); + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case COMMA: + jj_consume_token(COMMA); + integerValue = SignedInteger(); + param2 = queryFactory.createOperation(queryFactory.createNumericConstant(integerValue), null, null); + break; + default: + jj_la1[93] = jj_gen; + ; + } + jj_consume_token(RIGHT_PAR); break; default: - jj_la1[91] = jj_gen; - ; - } + jj_la1[94] = jj_gen; + jj_consume_token(-1); + throw new ParseException(); + } + if (param1 != null){ + if (true) + return queryFactory.createMathFunction(MathFunctionType.valueOf(fct.image.toUpperCase()), param1, param2); + }else{ + if (true) + return null; + } + }catch(Exception ex){ + { + if (true) + throw generateParseException(ex); + } + } + throw new Error("Missing return statement in function"); + }finally{ + trace_return("MathFunction"); + } + } + + final public MathFunction TrigFunction() throws ParseException{ + trace_call("TrigFunction"); + try{ + Token fct = null; + ADQLOperand param1 = null, param2 = null; + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case ACOS: + fct = jj_consume_token(ACOS); + jj_consume_token(LEFT_PAR); + param1 = NumericExpression(); + jj_consume_token(RIGHT_PAR); + break; + case ASIN: + fct = jj_consume_token(ASIN); + jj_consume_token(LEFT_PAR); + param1 = NumericExpression(); + jj_consume_token(RIGHT_PAR); + break; + case ATAN: + fct = jj_consume_token(ATAN); + jj_consume_token(LEFT_PAR); + param1 = NumericExpression(); + jj_consume_token(RIGHT_PAR); + break; + case ATAN2: + fct = jj_consume_token(ATAN2); + jj_consume_token(LEFT_PAR); + param1 = NumericExpression(); + jj_consume_token(COMMA); + param2 = NumericExpression(); jj_consume_token(RIGHT_PAR); break; - case ROUND: - fct = jj_consume_token(ROUND); + case COS: + fct = jj_consume_token(COS); jj_consume_token(LEFT_PAR); param1 = NumericExpression(); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case COMMA: - jj_consume_token(COMMA); - integerValue = SignedInteger(); - param2 = queryFactory.createOperation(queryFactory.createNumericConstant(integerValue), null, null); - break; - default: - jj_la1[92] = jj_gen; - ; - } jj_consume_token(RIGHT_PAR); break; - case SQRT: - fct = jj_consume_token(SQRT); + case COT: + fct = jj_consume_token(COT); jj_consume_token(LEFT_PAR); param1 = NumericExpression(); jj_consume_token(RIGHT_PAR); break; - case TRUNCATE: - fct = jj_consume_token(TRUNCATE); + case SIN: + fct = jj_consume_token(SIN); + jj_consume_token(LEFT_PAR); + param1 = NumericExpression(); + jj_consume_token(RIGHT_PAR); + break; + case TAN: + fct = jj_consume_token(TAN); jj_consume_token(LEFT_PAR); param1 = NumericExpression(); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case COMMA: - jj_consume_token(COMMA); - integerValue = SignedInteger(); - param2 = queryFactory.createOperation(queryFactory.createNumericConstant(integerValue), null, null); - break; - default: - jj_la1[93] = jj_gen; - ; - } jj_consume_token(RIGHT_PAR); break; default: - jj_la1[94] = jj_gen; + jj_la1[95] = jj_gen; jj_consume_token(-1); throw new ParseException(); - } - if (param1 != null) - {if (true) return queryFactory.createMathFunction(MathFunctionType.valueOf(fct.image.toUpperCase()), param1, param2);} - else - {if (true) return null;} - } catch (Exception ex) { - {if (true) throw generateParseException(ex);} - } - throw new Error("Missing return statement in function"); - } finally { - trace_return("MathFunction"); - } - } - - final public MathFunction TrigFunction() throws ParseException { - trace_call("TrigFunction"); - try { - Token fct=null; ADQLOperand param1=null, param2=null; - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case ACOS: - fct = jj_consume_token(ACOS); - jj_consume_token(LEFT_PAR); - param1 = NumericExpression(); - jj_consume_token(RIGHT_PAR); - break; - case ASIN: - fct = jj_consume_token(ASIN); - jj_consume_token(LEFT_PAR); - param1 = NumericExpression(); - jj_consume_token(RIGHT_PAR); - break; - case ATAN: - fct = jj_consume_token(ATAN); - jj_consume_token(LEFT_PAR); - param1 = NumericExpression(); - jj_consume_token(RIGHT_PAR); - break; - case ATAN2: - fct = jj_consume_token(ATAN2); - jj_consume_token(LEFT_PAR); - param1 = NumericExpression(); - jj_consume_token(COMMA); - param2 = NumericExpression(); - jj_consume_token(RIGHT_PAR); - break; - case COS: - fct = jj_consume_token(COS); - jj_consume_token(LEFT_PAR); - param1 = NumericExpression(); - jj_consume_token(RIGHT_PAR); - break; - case COT: - fct = jj_consume_token(COT); - jj_consume_token(LEFT_PAR); - param1 = NumericExpression(); - jj_consume_token(RIGHT_PAR); - break; - case SIN: - fct = jj_consume_token(SIN); - jj_consume_token(LEFT_PAR); - param1 = NumericExpression(); - jj_consume_token(RIGHT_PAR); - break; - case TAN: - fct = jj_consume_token(TAN); - jj_consume_token(LEFT_PAR); - param1 = NumericExpression(); - jj_consume_token(RIGHT_PAR); - break; - default: - jj_la1[95] = jj_gen; - jj_consume_token(-1); - throw new ParseException(); } try{ - if (param1 != null) - {if (true) return queryFactory.createMathFunction(MathFunctionType.valueOf(fct.image.toUpperCase()), param1, param2);} - else - {if (true) return null;} + if (param1 != null){ + if (true) + return queryFactory.createMathFunction(MathFunctionType.valueOf(fct.image.toUpperCase()), param1, param2); + }else{ + if (true) + return null; + } }catch(Exception ex){ - {if (true) throw generateParseException(ex);} + { + if (true) + throw generateParseException(ex); + } } throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("TrigFunction"); } } /* /!\ WARNING: The function name may be prefixed by "udf_" but there is no way to check it here ! */ - final public UserDefinedFunction UserDefinedFunction() throws ParseException { + final public UserDefinedFunction UserDefinedFunction() throws ParseException{ trace_call("UserDefinedFunction"); - try { - Token fct; Vector<ADQLOperand> params = new Vector<ADQLOperand>(); ADQLOperand op; + try{ + Token fct; + Vector<ADQLOperand> params = new Vector<ADQLOperand>(); + ADQLOperand op; fct = jj_consume_token(REGULAR_IDENTIFIER); jj_consume_token(LEFT_PAR); - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case LEFT_PAR: - case PLUS: - case MINUS: - case AVG: - case MAX: - case MIN: - case SUM: - case COUNT: - case BOX: - case CENTROID: - case CIRCLE: - case POINT: - case POLYGON: - case REGION: - case CONTAINS: - case INTERSECTS: - case AREA: - case COORD1: - case COORD2: - case COORDSYS: - case DISTANCE: - case ABS: - case CEILING: - case DEGREES: - case EXP: - case FLOOR: - case LOG: - case LOG10: - case MOD: - case PI: - case POWER: - case RADIANS: - case RAND: - case ROUND: - case SQRT: - case TRUNCATE: - case ACOS: - case ASIN: - case ATAN: - case ATAN2: - case COS: - case COT: - case SIN: - case TAN: - case STRING_LITERAL: - case DELIMITED_IDENTIFIER: - case REGULAR_IDENTIFIER: - case SCIENTIFIC_NUMBER: - case UNSIGNED_FLOAT: - case UNSIGNED_INTEGER: - op = ValueExpression(); - params.add(op); - label_13: - while (true) { - switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { - case COMMA: - ; - break; - default: - jj_la1[96] = jj_gen; - break label_13; + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case LEFT_PAR: + case PLUS: + case MINUS: + case AVG: + case MAX: + case MIN: + case SUM: + case COUNT: + case BOX: + case CENTROID: + case CIRCLE: + case POINT: + case POLYGON: + case REGION: + case CONTAINS: + case INTERSECTS: + case AREA: + case COORD1: + case COORD2: + case COORDSYS: + case DISTANCE: + case ABS: + case CEILING: + case DEGREES: + case EXP: + case FLOOR: + case LOG: + case LOG10: + case MOD: + case PI: + case POWER: + case RADIANS: + case RAND: + case ROUND: + case SQRT: + case TRUNCATE: + case ACOS: + case ASIN: + case ATAN: + case ATAN2: + case COS: + case COT: + case SIN: + case TAN: + case STRING_LITERAL: + case DELIMITED_IDENTIFIER: + case REGULAR_IDENTIFIER: + case SCIENTIFIC_NUMBER: + case UNSIGNED_FLOAT: + case UNSIGNED_INTEGER: + op = ValueExpression(); + params.add(op); + label_13: while(true){ + switch((jj_ntk == -1) ? jj_ntk() : jj_ntk){ + case COMMA: + ; + break; + default: + jj_la1[96] = jj_gen; + break label_13; } jj_consume_token(COMMA); op = ValueExpression(); params.add(op); } - break; - default: - jj_la1[97] = jj_gen; - ; + break; + default: + jj_la1[97] = jj_gen; + ; } jj_consume_token(RIGHT_PAR); //System.out.println("INFO [ADQLParser]: \""+fct.image+"\" (from line "+fct.beginLine+" and column "+fct.beginColumn+" to line "+token.endLine+" and column "+(token.endColumn+1)+") is considered as an user defined function !"); try{ ADQLOperand[] parameters = new ADQLOperand[params.size()]; - for(int i=0; i<params.size(); i++) + for(int i = 0; i < params.size(); i++) parameters[i] = params.get(i); - {if (true) return queryFactory.createUserDefinedFunction(fct.image, parameters);} + { + if (true) + return queryFactory.createUserDefinedFunction(fct.image, parameters); + } }catch(UnsupportedOperationException uoe){ - {if (true) throw new ParseException(uoe.getMessage(), new TextPosition(fct, token));} + { + if (true) + throw new ParseException(uoe.getMessage(), new TextPosition(fct, token)); + } }catch(Exception ex){ - {if (true) throw generateParseException(ex);} + { + if (true) + throw generateParseException(ex); + } } throw new Error("Missing return statement in function"); - } finally { + }finally{ trace_return("UserDefinedFunction"); } } - private boolean jj_2_1(int xla) { - jj_la = xla; jj_lastpos = jj_scanpos = token; - try { return !jj_3_1(); } - catch(LookaheadSuccess ls) { return true; } - finally { jj_save(0, xla); } + private boolean jj_2_1(int xla){ + jj_la = xla; + jj_lastpos = jj_scanpos = token; + try{ + return !jj_3_1(); + }catch(LookaheadSuccess ls){ + return true; + }finally{ + jj_save(0, xla); + } } - private boolean jj_2_2(int xla) { - jj_la = xla; jj_lastpos = jj_scanpos = token; - try { return !jj_3_2(); } - catch(LookaheadSuccess ls) { return true; } - finally { jj_save(1, xla); } + private boolean jj_2_2(int xla){ + jj_la = xla; + jj_lastpos = jj_scanpos = token; + try{ + return !jj_3_2(); + }catch(LookaheadSuccess ls){ + return true; + }finally{ + jj_save(1, xla); + } } - private boolean jj_2_3(int xla) { - jj_la = xla; jj_lastpos = jj_scanpos = token; - try { return !jj_3_3(); } - catch(LookaheadSuccess ls) { return true; } - finally { jj_save(2, xla); } + private boolean jj_2_3(int xla){ + jj_la = xla; + jj_lastpos = jj_scanpos = token; + try{ + return !jj_3_3(); + }catch(LookaheadSuccess ls){ + return true; + }finally{ + jj_save(2, xla); + } } - private boolean jj_2_4(int xla) { - jj_la = xla; jj_lastpos = jj_scanpos = token; - try { return !jj_3_4(); } - catch(LookaheadSuccess ls) { return true; } - finally { jj_save(3, xla); } + private boolean jj_2_4(int xla){ + jj_la = xla; + jj_lastpos = jj_scanpos = token; + try{ + return !jj_3_4(); + }catch(LookaheadSuccess ls){ + return true; + }finally{ + jj_save(3, xla); + } } - private boolean jj_2_5(int xla) { - jj_la = xla; jj_lastpos = jj_scanpos = token; - try { return !jj_3_5(); } - catch(LookaheadSuccess ls) { return true; } - finally { jj_save(4, xla); } + private boolean jj_2_5(int xla){ + jj_la = xla; + jj_lastpos = jj_scanpos = token; + try{ + return !jj_3_5(); + }catch(LookaheadSuccess ls){ + return true; + }finally{ + jj_save(4, xla); + } } - private boolean jj_2_6(int xla) { - jj_la = xla; jj_lastpos = jj_scanpos = token; - try { return !jj_3_6(); } - catch(LookaheadSuccess ls) { return true; } - finally { jj_save(5, xla); } + private boolean jj_2_6(int xla){ + jj_la = xla; + jj_lastpos = jj_scanpos = token; + try{ + return !jj_3_6(); + }catch(LookaheadSuccess ls){ + return true; + }finally{ + jj_save(5, xla); + } } - private boolean jj_2_7(int xla) { - jj_la = xla; jj_lastpos = jj_scanpos = token; - try { return !jj_3_7(); } - catch(LookaheadSuccess ls) { return true; } - finally { jj_save(6, xla); } + private boolean jj_2_7(int xla){ + jj_la = xla; + jj_lastpos = jj_scanpos = token; + try{ + return !jj_3_7(); + }catch(LookaheadSuccess ls){ + return true; + }finally{ + jj_save(6, xla); + } } - private boolean jj_2_8(int xla) { - jj_la = xla; jj_lastpos = jj_scanpos = token; - try { return !jj_3_8(); } - catch(LookaheadSuccess ls) { return true; } - finally { jj_save(7, xla); } + private boolean jj_2_8(int xla){ + jj_la = xla; + jj_lastpos = jj_scanpos = token; + try{ + return !jj_3_8(); + }catch(LookaheadSuccess ls){ + return true; + }finally{ + jj_save(7, xla); + } } - private boolean jj_2_9(int xla) { - jj_la = xla; jj_lastpos = jj_scanpos = token; - try { return !jj_3_9(); } - catch(LookaheadSuccess ls) { return true; } - finally { jj_save(8, xla); } + private boolean jj_2_9(int xla){ + jj_la = xla; + jj_lastpos = jj_scanpos = token; + try{ + return !jj_3_9(); + }catch(LookaheadSuccess ls){ + return true; + }finally{ + jj_save(8, xla); + } } - private boolean jj_2_10(int xla) { - jj_la = xla; jj_lastpos = jj_scanpos = token; - try { return !jj_3_10(); } - catch(LookaheadSuccess ls) { return true; } - finally { jj_save(9, xla); } + private boolean jj_2_10(int xla){ + jj_la = xla; + jj_lastpos = jj_scanpos = token; + try{ + return !jj_3_10(); + }catch(LookaheadSuccess ls){ + return true; + }finally{ + jj_save(9, xla); + } } - private boolean jj_2_11(int xla) { - jj_la = xla; jj_lastpos = jj_scanpos = token; - try { return !jj_3_11(); } - catch(LookaheadSuccess ls) { return true; } - finally { jj_save(10, xla); } + private boolean jj_2_11(int xla){ + jj_la = xla; + jj_lastpos = jj_scanpos = token; + try{ + return !jj_3_11(); + }catch(LookaheadSuccess ls){ + return true; + }finally{ + jj_save(10, xla); + } } - private boolean jj_2_12(int xla) { - jj_la = xla; jj_lastpos = jj_scanpos = token; - try { return !jj_3_12(); } - catch(LookaheadSuccess ls) { return true; } - finally { jj_save(11, xla); } + private boolean jj_2_12(int xla){ + jj_la = xla; + jj_lastpos = jj_scanpos = token; + try{ + return !jj_3_12(); + }catch(LookaheadSuccess ls){ + return true; + }finally{ + jj_save(11, xla); + } } - private boolean jj_2_13(int xla) { - jj_la = xla; jj_lastpos = jj_scanpos = token; - try { return !jj_3_13(); } - catch(LookaheadSuccess ls) { return true; } - finally { jj_save(12, xla); } + private boolean jj_2_13(int xla){ + jj_la = xla; + jj_lastpos = jj_scanpos = token; + try{ + return !jj_3_13(); + }catch(LookaheadSuccess ls){ + return true; + }finally{ + jj_save(12, xla); + } } - private boolean jj_3R_165() { - if (jj_scan_token(NOT)) return true; + private boolean jj_3R_165(){ + if (jj_scan_token(NOT)) + return true; return false; } - private boolean jj_3R_44() { - if (jj_scan_token(SELECT)) return true; + private boolean jj_3R_44(){ + if (jj_scan_token(SELECT)) + return true; Token xsp; xsp = jj_scanpos; - if (jj_3R_136()) jj_scanpos = xsp; + if (jj_3R_136()) + jj_scanpos = xsp; xsp = jj_scanpos; - if (jj_3R_137()) jj_scanpos = xsp; - if (jj_3R_138()) return true; - while (true) { + if (jj_3R_137()) + jj_scanpos = xsp; + if (jj_3R_138()) + return true; + while(true){ xsp = jj_scanpos; - if (jj_3R_139()) { jj_scanpos = xsp; break; } + if (jj_3R_139()){ + jj_scanpos = xsp; + break; + } } return false; } - private boolean jj_3R_16() { - if (jj_scan_token(LEFT_PAR)) return true; - if (jj_3R_28()) return true; - if (jj_scan_token(RIGHT_PAR)) return true; + private boolean jj_3R_16(){ + if (jj_scan_token(LEFT_PAR)) + return true; + if (jj_3R_28()) + return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_112() { - if (jj_3R_100()) return true; + private boolean jj_3R_112(){ + if (jj_3R_100()) + return true; return false; } - private boolean jj_3R_153() { + private boolean jj_3R_153(){ Token xsp; xsp = jj_scanpos; - if (jj_3R_165()) jj_scanpos = xsp; - if (jj_3R_166()) return true; - while (true) { + if (jj_3R_165()) + jj_scanpos = xsp; + if (jj_3R_166()) + return true; + while(true){ xsp = jj_scanpos; - if (jj_3R_167()) { jj_scanpos = xsp; break; } + if (jj_3R_167()){ + jj_scanpos = xsp; + break; + } } return false; } - private boolean jj_3R_121() { - if (jj_3R_144()) return true; + private boolean jj_3R_121(){ + if (jj_3R_144()) + return true; return false; } - private boolean jj_3R_111() { - if (jj_3R_23()) return true; + private boolean jj_3R_111(){ + if (jj_3R_23()) + return true; return false; } - private boolean jj_3R_163() { - if (jj_3R_49()) return true; + private boolean jj_3R_163(){ + if (jj_3R_49()) + return true; return false; } - private boolean jj_3R_120() { - if (jj_3R_143()) return true; + private boolean jj_3R_120(){ + if (jj_3R_143()) + return true; return false; } - private boolean jj_3R_64() { + private boolean jj_3R_64(){ Token xsp; xsp = jj_scanpos; - if (jj_3R_111()) { + if (jj_3R_111()){ jj_scanpos = xsp; - if (jj_3R_112()) return true; + if (jj_3R_112()) + return true; } return false; } - private boolean jj_3R_119() { - if (jj_3R_142()) return true; + private boolean jj_3R_119(){ + if (jj_3R_142()) + return true; return false; } - private boolean jj_3R_118() { - if (jj_3R_141()) return true; + private boolean jj_3R_118(){ + if (jj_3R_141()) + return true; return false; } - private boolean jj_3R_32() { - if (jj_3R_49()) return true; + private boolean jj_3R_32(){ + if (jj_3R_49()) + return true; return false; } - private boolean jj_3_8() { - if (jj_3R_20()) return true; + private boolean jj_3_8(){ + if (jj_3R_20()) + return true; return false; } - private boolean jj_3R_31() { - if (jj_3R_48()) return true; + private boolean jj_3R_31(){ + if (jj_3R_48()) + return true; return false; } - private boolean jj_3R_18() { + private boolean jj_3R_18(){ Token xsp; xsp = jj_scanpos; - if (jj_3R_31()) { + if (jj_3R_31()){ jj_scanpos = xsp; - if (jj_3_8()) { + if (jj_3_8()){ jj_scanpos = xsp; - if (jj_3R_32()) return true; + if (jj_3R_32()) + return true; } } return false; } - private boolean jj_3R_65() { - if (jj_3R_41()) return true; + private boolean jj_3R_65(){ + if (jj_3R_41()) + return true; Token xsp; - while (true) { + while(true){ xsp = jj_scanpos; - if (jj_3R_113()) { jj_scanpos = xsp; break; } + if (jj_3R_113()){ + jj_scanpos = xsp; + break; + } } return false; } - private boolean jj_3R_28() { - if (jj_3R_44()) return true; - if (jj_3R_117()) return true; + private boolean jj_3R_28(){ + if (jj_3R_44()) + return true; + if (jj_3R_117()) + return true; Token xsp; xsp = jj_scanpos; - if (jj_3R_118()) jj_scanpos = xsp; + if (jj_3R_118()) + jj_scanpos = xsp; xsp = jj_scanpos; - if (jj_3R_119()) jj_scanpos = xsp; + if (jj_3R_119()) + jj_scanpos = xsp; xsp = jj_scanpos; - if (jj_3R_120()) jj_scanpos = xsp; + if (jj_3R_120()) + jj_scanpos = xsp; xsp = jj_scanpos; - if (jj_3R_121()) jj_scanpos = xsp; + if (jj_3R_121()) + jj_scanpos = xsp; return false; } - private boolean jj_3R_183() { - if (jj_scan_token(COMMA)) return true; - if (jj_3R_192()) return true; + private boolean jj_3R_183(){ + if (jj_scan_token(COMMA)) + return true; + if (jj_3R_192()) + return true; return false; } - private boolean jj_3R_43() { - if (jj_scan_token(CONCAT)) return true; - if (jj_3R_18()) return true; + private boolean jj_3R_43(){ + if (jj_scan_token(CONCAT)) + return true; + if (jj_3R_18()) + return true; return false; } - private boolean jj_3R_182() { - if (jj_scan_token(COMMA)) return true; - if (jj_3R_192()) return true; + private boolean jj_3R_182(){ + if (jj_scan_token(COMMA)) + return true; + if (jj_3R_192()) + return true; return false; } - private boolean jj_3R_105() { - if (jj_scan_token(FULL)) return true; + private boolean jj_3R_105(){ + if (jj_scan_token(FULL)) + return true; return false; } - private boolean jj_3R_171() { - if (jj_scan_token(MINUS)) return true; + private boolean jj_3R_171(){ + if (jj_scan_token(MINUS)) + return true; return false; } - private boolean jj_3R_24() { - if (jj_3R_18()) return true; + private boolean jj_3R_24(){ + if (jj_3R_18()) + return true; Token xsp; - while (true) { + while(true){ xsp = jj_scanpos; - if (jj_3R_43()) { jj_scanpos = xsp; break; } + if (jj_3R_43()){ + jj_scanpos = xsp; + break; + } } return false; } - private boolean jj_3_7() { - if (jj_3R_19()) return true; + private boolean jj_3_7(){ + if (jj_3R_19()) + return true; return false; } - private boolean jj_3R_162() { + private boolean jj_3R_162(){ Token xsp; xsp = jj_scanpos; - if (jj_scan_token(8)) { + if (jj_scan_token(8)){ jj_scanpos = xsp; - if (jj_3R_171()) return true; + if (jj_3R_171()) + return true; } return false; } - private boolean jj_3R_161() { + private boolean jj_3R_161(){ Token xsp; xsp = jj_scanpos; - if (jj_scan_token(10)) { + if (jj_scan_token(10)){ jj_scanpos = xsp; - if (jj_scan_token(11)) return true; + if (jj_scan_token(11)) + return true; } - if (jj_3R_129()) return true; + if (jj_3R_129()) + return true; return false; } - private boolean jj_3R_148() { + private boolean jj_3R_148(){ Token xsp; xsp = jj_scanpos; - if (jj_3R_162()) jj_scanpos = xsp; + if (jj_3R_162()) + jj_scanpos = xsp; xsp = jj_scanpos; - if (jj_3_7()) { + if (jj_3_7()){ jj_scanpos = xsp; - if (jj_3R_163()) return true; + if (jj_3R_163()) + return true; } return false; } - private boolean jj_3R_20() { - if (jj_scan_token(REGULAR_IDENTIFIER)) return true; - if (jj_scan_token(LEFT_PAR)) return true; + private boolean jj_3R_20(){ + if (jj_scan_token(REGULAR_IDENTIFIER)) + return true; + if (jj_scan_token(LEFT_PAR)) + return true; Token xsp; xsp = jj_scanpos; - if (jj_3R_65()) jj_scanpos = xsp; - if (jj_scan_token(RIGHT_PAR)) return true; + if (jj_3R_65()) + jj_scanpos = xsp; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_108() { - if (jj_scan_token(FULL)) return true; + private boolean jj_3R_108(){ + if (jj_scan_token(FULL)) + return true; return false; } - private boolean jj_3R_181() { - if (jj_3R_101()) return true; + private boolean jj_3R_181(){ + if (jj_3R_101()) + return true; return false; } - private boolean jj_3R_145() { + private boolean jj_3R_145(){ Token xsp; xsp = jj_scanpos; - if (jj_scan_token(8)) { + if (jj_scan_token(8)){ jj_scanpos = xsp; - if (jj_scan_token(9)) return true; + if (jj_scan_token(9)) + return true; } - if (jj_3R_101()) return true; + if (jj_3R_101()) + return true; return false; } - private boolean jj_3R_92() { - if (jj_scan_token(TAN)) return true; - if (jj_scan_token(LEFT_PAR)) return true; - if (jj_3R_101()) return true; - if (jj_scan_token(RIGHT_PAR)) return true; + private boolean jj_3R_92(){ + if (jj_scan_token(TAN)) + return true; + if (jj_scan_token(LEFT_PAR)) + return true; + if (jj_3R_101()) + return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_91() { - if (jj_scan_token(SIN)) return true; - if (jj_scan_token(LEFT_PAR)) return true; - if (jj_3R_101()) return true; - if (jj_scan_token(RIGHT_PAR)) return true; + private boolean jj_3R_91(){ + if (jj_scan_token(SIN)) + return true; + if (jj_scan_token(LEFT_PAR)) + return true; + if (jj_3R_101()) + return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_129() { - if (jj_3R_148()) return true; + private boolean jj_3R_129(){ + if (jj_3R_148()) + return true; Token xsp; xsp = jj_scanpos; - if (jj_3R_161()) jj_scanpos = xsp; + if (jj_3R_161()) + jj_scanpos = xsp; return false; } - private boolean jj_3R_90() { - if (jj_scan_token(COT)) return true; - if (jj_scan_token(LEFT_PAR)) return true; - if (jj_3R_101()) return true; - if (jj_scan_token(RIGHT_PAR)) return true; + private boolean jj_3R_90(){ + if (jj_scan_token(COT)) + return true; + if (jj_scan_token(LEFT_PAR)) + return true; + if (jj_3R_101()) + return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_89() { - if (jj_scan_token(COS)) return true; - if (jj_scan_token(LEFT_PAR)) return true; - if (jj_3R_101()) return true; - if (jj_scan_token(RIGHT_PAR)) return true; + private boolean jj_3R_89(){ + if (jj_scan_token(COS)) + return true; + if (jj_scan_token(LEFT_PAR)) + return true; + if (jj_3R_101()) + return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_88() { - if (jj_scan_token(ATAN2)) return true; - if (jj_scan_token(LEFT_PAR)) return true; - if (jj_3R_101()) return true; - if (jj_scan_token(COMMA)) return true; - if (jj_3R_101()) return true; - if (jj_scan_token(RIGHT_PAR)) return true; + private boolean jj_3R_88(){ + if (jj_scan_token(ATAN2)) + return true; + if (jj_scan_token(LEFT_PAR)) + return true; + if (jj_3R_101()) + return true; + if (jj_scan_token(COMMA)) + return true; + if (jj_3R_101()) + return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_87() { - if (jj_scan_token(ATAN)) return true; - if (jj_scan_token(LEFT_PAR)) return true; - if (jj_3R_101()) return true; - if (jj_scan_token(RIGHT_PAR)) return true; + private boolean jj_3R_87(){ + if (jj_scan_token(ATAN)) + return true; + if (jj_scan_token(LEFT_PAR)) + return true; + if (jj_3R_101()) + return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_104() { - if (jj_scan_token(RIGHT)) return true; + private boolean jj_3R_104(){ + if (jj_scan_token(RIGHT)) + return true; return false; } - private boolean jj_3R_86() { - if (jj_scan_token(ASIN)) return true; - if (jj_scan_token(LEFT_PAR)) return true; - if (jj_3R_101()) return true; - if (jj_scan_token(RIGHT_PAR)) return true; + private boolean jj_3R_86(){ + if (jj_scan_token(ASIN)) + return true; + if (jj_scan_token(LEFT_PAR)) + return true; + if (jj_3R_101()) + return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_85() { - if (jj_scan_token(ACOS)) return true; - if (jj_scan_token(LEFT_PAR)) return true; - if (jj_3R_101()) return true; - if (jj_scan_token(RIGHT_PAR)) return true; + private boolean jj_3R_85(){ + if (jj_scan_token(ACOS)) + return true; + if (jj_scan_token(LEFT_PAR)) + return true; + if (jj_3R_101()) + return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_51() { + private boolean jj_3R_51(){ Token xsp; xsp = jj_scanpos; - if (jj_3R_85()) { + if (jj_3R_85()){ jj_scanpos = xsp; - if (jj_3R_86()) { + if (jj_3R_86()){ jj_scanpos = xsp; - if (jj_3R_87()) { + if (jj_3R_87()){ jj_scanpos = xsp; - if (jj_3R_88()) { + if (jj_3R_88()){ jj_scanpos = xsp; - if (jj_3R_89()) { + if (jj_3R_89()){ jj_scanpos = xsp; - if (jj_3R_90()) { + if (jj_3R_90()){ jj_scanpos = xsp; - if (jj_3R_91()) { + if (jj_3R_91()){ jj_scanpos = xsp; - if (jj_3R_92()) return true; + if (jj_3R_92()) + return true; } } } @@ -3503,205 +4002,280 @@ public class ADQLParser implements ADQLParserConstants { return false; } - private boolean jj_3_6() { - if (jj_3R_18()) return true; - if (jj_scan_token(CONCAT)) return true; + private boolean jj_3_6(){ + if (jj_3R_18()) + return true; + if (jj_scan_token(CONCAT)) + return true; return false; } - private boolean jj_3_5() { - if (jj_scan_token(COORDSYS)) return true; + private boolean jj_3_5(){ + if (jj_scan_token(COORDSYS)) + return true; return false; } - private boolean jj_3R_84() { - if (jj_scan_token(TRUNCATE)) return true; - if (jj_scan_token(LEFT_PAR)) return true; - if (jj_3R_101()) return true; + private boolean jj_3R_84(){ + if (jj_scan_token(TRUNCATE)) + return true; + if (jj_scan_token(LEFT_PAR)) + return true; + if (jj_3R_101()) + return true; Token xsp; xsp = jj_scanpos; - if (jj_3R_183()) jj_scanpos = xsp; - if (jj_scan_token(RIGHT_PAR)) return true; + if (jj_3R_183()) + jj_scanpos = xsp; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3_4() { + private boolean jj_3_4(){ Token xsp; xsp = jj_scanpos; - if (jj_scan_token(8)) { + if (jj_scan_token(8)){ jj_scanpos = xsp; - if (jj_scan_token(9)) return true; + if (jj_scan_token(9)) + return true; } return false; } - private boolean jj_3R_83() { - if (jj_scan_token(SQRT)) return true; - if (jj_scan_token(LEFT_PAR)) return true; - if (jj_3R_101()) return true; - if (jj_scan_token(RIGHT_PAR)) return true; + private boolean jj_3R_83(){ + if (jj_scan_token(SQRT)) + return true; + if (jj_scan_token(LEFT_PAR)) + return true; + if (jj_3R_101()) + return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_82() { - if (jj_scan_token(ROUND)) return true; - if (jj_scan_token(LEFT_PAR)) return true; - if (jj_3R_101()) return true; + private boolean jj_3R_82(){ + if (jj_scan_token(ROUND)) + return true; + if (jj_scan_token(LEFT_PAR)) + return true; + if (jj_3R_101()) + return true; Token xsp; xsp = jj_scanpos; - if (jj_3R_182()) jj_scanpos = xsp; - if (jj_scan_token(RIGHT_PAR)) return true; + if (jj_3R_182()) + jj_scanpos = xsp; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_81() { - if (jj_scan_token(RAND)) return true; - if (jj_scan_token(LEFT_PAR)) return true; + private boolean jj_3R_81(){ + if (jj_scan_token(RAND)) + return true; + if (jj_scan_token(LEFT_PAR)) + return true; Token xsp; xsp = jj_scanpos; - if (jj_3R_181()) jj_scanpos = xsp; - if (jj_scan_token(RIGHT_PAR)) return true; + if (jj_3R_181()) + jj_scanpos = xsp; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_80() { - if (jj_scan_token(RADIANS)) return true; - if (jj_scan_token(LEFT_PAR)) return true; - if (jj_3R_101()) return true; - if (jj_scan_token(RIGHT_PAR)) return true; + private boolean jj_3R_80(){ + if (jj_scan_token(RADIANS)) + return true; + if (jj_scan_token(LEFT_PAR)) + return true; + if (jj_3R_101()) + return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_101() { - if (jj_3R_129()) return true; + private boolean jj_3R_101(){ + if (jj_3R_129()) + return true; Token xsp; xsp = jj_scanpos; - if (jj_3R_145()) jj_scanpos = xsp; + if (jj_3R_145()) + jj_scanpos = xsp; return false; } - private boolean jj_3R_79() { - if (jj_scan_token(POWER)) return true; - if (jj_scan_token(LEFT_PAR)) return true; - if (jj_3R_101()) return true; - if (jj_scan_token(COMMA)) return true; - if (jj_3R_101()) return true; - if (jj_scan_token(RIGHT_PAR)) return true; + private boolean jj_3R_79(){ + if (jj_scan_token(POWER)) + return true; + if (jj_scan_token(LEFT_PAR)) + return true; + if (jj_3R_101()) + return true; + if (jj_scan_token(COMMA)) + return true; + if (jj_3R_101()) + return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_78() { - if (jj_scan_token(PI)) return true; - if (jj_scan_token(LEFT_PAR)) return true; - if (jj_scan_token(RIGHT_PAR)) return true; + private boolean jj_3R_78(){ + if (jj_scan_token(PI)) + return true; + if (jj_scan_token(LEFT_PAR)) + return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_77() { - if (jj_scan_token(MOD)) return true; - if (jj_scan_token(LEFT_PAR)) return true; - if (jj_3R_101()) return true; - if (jj_scan_token(COMMA)) return true; - if (jj_3R_101()) return true; - if (jj_scan_token(RIGHT_PAR)) return true; + private boolean jj_3R_77(){ + if (jj_scan_token(MOD)) + return true; + if (jj_scan_token(LEFT_PAR)) + return true; + if (jj_3R_101()) + return true; + if (jj_scan_token(COMMA)) + return true; + if (jj_3R_101()) + return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_59() { - if (jj_3R_101()) return true; + private boolean jj_3R_59(){ + if (jj_3R_101()) + return true; return false; } - private boolean jj_3R_76() { - if (jj_scan_token(LOG10)) return true; - if (jj_scan_token(LEFT_PAR)) return true; - if (jj_3R_101()) return true; - if (jj_scan_token(RIGHT_PAR)) return true; + private boolean jj_3R_76(){ + if (jj_scan_token(LOG10)) + return true; + if (jj_scan_token(LEFT_PAR)) + return true; + if (jj_3R_101()) + return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_58() { - if (jj_3R_24()) return true; + private boolean jj_3R_58(){ + if (jj_3R_24()) + return true; return false; } - private boolean jj_3R_75() { - if (jj_scan_token(LOG)) return true; - if (jj_scan_token(LEFT_PAR)) return true; - if (jj_3R_101()) return true; - if (jj_scan_token(RIGHT_PAR)) return true; + private boolean jj_3R_75(){ + if (jj_scan_token(LOG)) + return true; + if (jj_scan_token(LEFT_PAR)) + return true; + if (jj_3R_101()) + return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_57() { - if (jj_3R_24()) return true; + private boolean jj_3R_57(){ + if (jj_3R_24()) + return true; return false; } - private boolean jj_3R_74() { - if (jj_scan_token(FLOOR)) return true; - if (jj_scan_token(LEFT_PAR)) return true; - if (jj_3R_101()) return true; - if (jj_scan_token(RIGHT_PAR)) return true; + private boolean jj_3R_74(){ + if (jj_scan_token(FLOOR)) + return true; + if (jj_scan_token(LEFT_PAR)) + return true; + if (jj_3R_101()) + return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_56() { - if (jj_3R_101()) return true; + private boolean jj_3R_56(){ + if (jj_3R_101()) + return true; return false; } - private boolean jj_3R_115() { - if (jj_3R_133()) return true; + private boolean jj_3R_115(){ + if (jj_3R_133()) + return true; return false; } - private boolean jj_3R_73() { - if (jj_scan_token(EXP)) return true; - if (jj_scan_token(LEFT_PAR)) return true; - if (jj_3R_101()) return true; - if (jj_scan_token(RIGHT_PAR)) return true; + private boolean jj_3R_73(){ + if (jj_scan_token(EXP)) + return true; + if (jj_scan_token(LEFT_PAR)) + return true; + if (jj_3R_101()) + return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_114() { - if (jj_3R_132()) return true; + private boolean jj_3R_114(){ + if (jj_3R_132()) + return true; return false; } - private boolean jj_3R_72() { - if (jj_scan_token(DEGREES)) return true; - if (jj_scan_token(LEFT_PAR)) return true; - if (jj_3R_101()) return true; - if (jj_scan_token(RIGHT_PAR)) return true; + private boolean jj_3R_72(){ + if (jj_scan_token(DEGREES)) + return true; + if (jj_scan_token(LEFT_PAR)) + return true; + if (jj_3R_101()) + return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_55() { - if (jj_3R_100()) return true; + private boolean jj_3R_55(){ + if (jj_3R_100()) + return true; return false; } - private boolean jj_3R_71() { - if (jj_scan_token(CEILING)) return true; - if (jj_scan_token(LEFT_PAR)) return true; - if (jj_3R_101()) return true; - if (jj_scan_token(RIGHT_PAR)) return true; + private boolean jj_3R_71(){ + if (jj_scan_token(CEILING)) + return true; + if (jj_scan_token(LEFT_PAR)) + return true; + if (jj_3R_101()) + return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_41() { + private boolean jj_3R_41(){ Token xsp; xsp = jj_scanpos; - if (jj_3R_55()) { + if (jj_3R_55()){ jj_scanpos = xsp; - if (jj_3R_56()) { + if (jj_3R_56()){ jj_scanpos = xsp; - if (jj_3R_57()) { + if (jj_3R_57()){ jj_scanpos = xsp; - if (jj_3R_58()) { + if (jj_3R_58()){ jj_scanpos = xsp; - if (jj_3R_59()) return true; + if (jj_3R_59()) + return true; } } } @@ -3709,78 +4283,90 @@ public class ADQLParser implements ADQLParserConstants { return false; } - private boolean jj_3R_70() { - if (jj_scan_token(ABS)) return true; - if (jj_scan_token(LEFT_PAR)) return true; - if (jj_3R_101()) return true; - if (jj_scan_token(RIGHT_PAR)) return true; + private boolean jj_3R_70(){ + if (jj_scan_token(ABS)) + return true; + if (jj_scan_token(LEFT_PAR)) + return true; + if (jj_3R_101()) + return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_69() { - if (jj_scan_token(LEFT_PAR)) return true; - if (jj_3R_41()) return true; - if (jj_scan_token(RIGHT_PAR)) return true; + private boolean jj_3R_69(){ + if (jj_scan_token(LEFT_PAR)) + return true; + if (jj_3R_41()) + return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_107() { - if (jj_scan_token(RIGHT)) return true; + private boolean jj_3R_107(){ + if (jj_scan_token(RIGHT)) + return true; return false; } - private boolean jj_3R_68() { - if (jj_3R_116()) return true; + private boolean jj_3R_68(){ + if (jj_3R_116()) + return true; return false; } - private boolean jj_3R_67() { - if (jj_3R_23()) return true; + private boolean jj_3R_67(){ + if (jj_3R_23()) + return true; return false; } - private boolean jj_3R_66() { + private boolean jj_3R_66(){ Token xsp; xsp = jj_scanpos; - if (jj_3R_114()) { + if (jj_3R_114()){ jj_scanpos = xsp; - if (jj_3R_115()) return true; + if (jj_3R_115()) + return true; } return false; } - private boolean jj_3R_50() { + private boolean jj_3R_50(){ Token xsp; xsp = jj_scanpos; - if (jj_3R_70()) { + if (jj_3R_70()){ jj_scanpos = xsp; - if (jj_3R_71()) { + if (jj_3R_71()){ jj_scanpos = xsp; - if (jj_3R_72()) { + if (jj_3R_72()){ jj_scanpos = xsp; - if (jj_3R_73()) { + if (jj_3R_73()){ jj_scanpos = xsp; - if (jj_3R_74()) { + if (jj_3R_74()){ jj_scanpos = xsp; - if (jj_3R_75()) { + if (jj_3R_75()){ jj_scanpos = xsp; - if (jj_3R_76()) { + if (jj_3R_76()){ jj_scanpos = xsp; - if (jj_3R_77()) { + if (jj_3R_77()){ jj_scanpos = xsp; - if (jj_3R_78()) { + if (jj_3R_78()){ jj_scanpos = xsp; - if (jj_3R_79()) { + if (jj_3R_79()){ jj_scanpos = xsp; - if (jj_3R_80()) { + if (jj_3R_80()){ jj_scanpos = xsp; - if (jj_3R_81()) { + if (jj_3R_81()){ jj_scanpos = xsp; - if (jj_3R_82()) { + if (jj_3R_82()){ jj_scanpos = xsp; - if (jj_3R_83()) { + if (jj_3R_83()){ jj_scanpos = xsp; - if (jj_3R_84()) return true; + if (jj_3R_84()) + return true; } } } @@ -3798,383 +4384,494 @@ public class ADQLParser implements ADQLParserConstants { return false; } - private boolean jj_3R_180() { - if (jj_scan_token(COMMA)) return true; - if (jj_3R_14()) return true; + private boolean jj_3R_180(){ + if (jj_scan_token(COMMA)) + return true; + if (jj_3R_14()) + return true; return false; } - private boolean jj_3R_36() { - if (jj_3R_20()) return true; + private boolean jj_3R_36(){ + if (jj_3R_20()) + return true; return false; } - private boolean jj_3R_35() { - if (jj_3R_52()) return true; + private boolean jj_3R_35(){ + if (jj_3R_52()) + return true; return false; } - private boolean jj_3R_34() { - if (jj_3R_51()) return true; + private boolean jj_3R_34(){ + if (jj_3R_51()) + return true; return false; } - private boolean jj_3R_49() { + private boolean jj_3R_49(){ Token xsp; xsp = jj_scanpos; - if (jj_3R_66()) { + if (jj_3R_66()){ jj_scanpos = xsp; - if (jj_3R_67()) { + if (jj_3R_67()){ jj_scanpos = xsp; - if (jj_3R_68()) { + if (jj_3R_68()){ jj_scanpos = xsp; - if (jj_3R_69()) return true; + if (jj_3R_69()) + return true; } } } return false; } - private boolean jj_3R_103() { - if (jj_scan_token(LEFT)) return true; + private boolean jj_3R_103(){ + if (jj_scan_token(LEFT)) + return true; return false; } - private boolean jj_3R_33() { - if (jj_3R_50()) return true; + private boolean jj_3R_33(){ + if (jj_3R_50()) + return true; return false; } - private boolean jj_3R_61() { + private boolean jj_3R_61(){ Token xsp; xsp = jj_scanpos; - if (jj_3R_103()) { + if (jj_3R_103()){ jj_scanpos = xsp; - if (jj_3R_104()) { + if (jj_3R_104()){ jj_scanpos = xsp; - if (jj_3R_105()) return true; + if (jj_3R_105()) + return true; } } xsp = jj_scanpos; - if (jj_scan_token(25)) jj_scanpos = xsp; + if (jj_scan_token(25)) + jj_scanpos = xsp; return false; } - private boolean jj_3R_19() { + private boolean jj_3R_19(){ Token xsp; xsp = jj_scanpos; - if (jj_3R_33()) { + if (jj_3R_33()){ jj_scanpos = xsp; - if (jj_3R_34()) { + if (jj_3R_34()){ jj_scanpos = xsp; - if (jj_3R_35()) { + if (jj_3R_35()){ jj_scanpos = xsp; - if (jj_3R_36()) return true; + if (jj_3R_36()) + return true; } } } return false; } - private boolean jj_3R_193() { + private boolean jj_3R_193(){ Token xsp; xsp = jj_scanpos; - if (jj_scan_token(8)) { + if (jj_scan_token(8)){ jj_scanpos = xsp; - if (jj_scan_token(9)) return true; + if (jj_scan_token(9)) + return true; } return false; } - private boolean jj_3R_192() { + private boolean jj_3R_192(){ Token xsp; xsp = jj_scanpos; - if (jj_3R_193()) jj_scanpos = xsp; - if (jj_scan_token(UNSIGNED_INTEGER)) return true; + if (jj_3R_193()) + jj_scanpos = xsp; + if (jj_scan_token(UNSIGNED_INTEGER)) + return true; return false; } - private boolean jj_3R_45() { + private boolean jj_3R_45(){ Token xsp; xsp = jj_scanpos; - if (jj_scan_token(24)) { + if (jj_scan_token(24)){ jj_scanpos = xsp; - if (jj_3R_61()) return true; + if (jj_3R_61()) + return true; } return false; } - private boolean jj_3R_48() { - if (jj_scan_token(COORDSYS)) return true; - if (jj_scan_token(LEFT_PAR)) return true; - if (jj_3R_64()) return true; - if (jj_scan_token(RIGHT_PAR)) return true; + private boolean jj_3R_48(){ + if (jj_scan_token(COORDSYS)) + return true; + if (jj_scan_token(LEFT_PAR)) + return true; + if (jj_3R_64()) + return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_160() { - if (jj_scan_token(COMMA)) return true; - if (jj_3R_159()) return true; + private boolean jj_3R_160(){ + if (jj_scan_token(COMMA)) + return true; + if (jj_3R_159()) + return true; return false; } - private boolean jj_3R_132() { + private boolean jj_3R_132(){ Token xsp; xsp = jj_scanpos; - if (jj_scan_token(99)) { + if (jj_scan_token(99)){ jj_scanpos = xsp; - if (jj_scan_token(100)) { + if (jj_scan_token(100)){ jj_scanpos = xsp; - if (jj_scan_token(101)) return true; + if (jj_scan_token(101)) + return true; } } return false; } - private boolean jj_3R_187() { - if (jj_3R_23()) return true; + private boolean jj_3R_187(){ + if (jj_3R_23()) + return true; return false; } - private boolean jj_3R_179() { - if (jj_scan_token(USING)) return true; - if (jj_scan_token(LEFT_PAR)) return true; - if (jj_3R_14()) return true; + private boolean jj_3R_179(){ + if (jj_scan_token(USING)) + return true; + if (jj_scan_token(LEFT_PAR)) + return true; + if (jj_3R_14()) + return true; Token xsp; - while (true) { + while(true){ xsp = jj_scanpos; - if (jj_3R_180()) { jj_scanpos = xsp; break; } + if (jj_3R_180()){ + jj_scanpos = xsp; + break; + } } - if (jj_scan_token(RIGHT_PAR)) return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_106() { - if (jj_scan_token(LEFT)) return true; + private boolean jj_3R_106(){ + if (jj_scan_token(LEFT)) + return true; return false; } - private boolean jj_3R_185() { - if (jj_3R_23()) return true; + private boolean jj_3R_185(){ + if (jj_3R_23()) + return true; return false; } - private boolean jj_3R_62() { + private boolean jj_3R_62(){ Token xsp; xsp = jj_scanpos; - if (jj_3R_106()) { + if (jj_3R_106()){ jj_scanpos = xsp; - if (jj_3R_107()) { + if (jj_3R_107()){ jj_scanpos = xsp; - if (jj_3R_108()) return true; + if (jj_3R_108()) + return true; } } xsp = jj_scanpos; - if (jj_scan_token(25)) jj_scanpos = xsp; + if (jj_scan_token(25)) + jj_scanpos = xsp; return false; } - private boolean jj_3R_178() { - if (jj_scan_token(ON)) return true; - if (jj_3R_153()) return true; + private boolean jj_3R_178(){ + if (jj_scan_token(ON)) + return true; + if (jj_3R_153()) + return true; return false; } - private boolean jj_3R_128() { - if (jj_scan_token(REGION)) return true; - if (jj_scan_token(LEFT_PAR)) return true; - if (jj_3R_24()) return true; - if (jj_scan_token(RIGHT_PAR)) return true; + private boolean jj_3R_128(){ + if (jj_scan_token(REGION)) + return true; + if (jj_scan_token(LEFT_PAR)) + return true; + if (jj_3R_24()) + return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_149() { - if (jj_scan_token(STRING_LITERAL)) return true; + private boolean jj_3R_149(){ + if (jj_scan_token(STRING_LITERAL)) + return true; return false; } - private boolean jj_3R_147() { - if (jj_scan_token(POINT)) return true; - if (jj_scan_token(LEFT_PAR)) return true; - if (jj_3R_158()) return true; - if (jj_scan_token(COMMA)) return true; - if (jj_3R_159()) return true; - if (jj_scan_token(RIGHT_PAR)) return true; + private boolean jj_3R_147(){ + if (jj_scan_token(POINT)) + return true; + if (jj_scan_token(LEFT_PAR)) + return true; + if (jj_3R_158()) + return true; + if (jj_scan_token(COMMA)) + return true; + if (jj_3R_159()) + return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_133() { + private boolean jj_3R_133(){ Token xsp; - if (jj_3R_149()) return true; - while (true) { + if (jj_3R_149()) + return true; + while(true){ xsp = jj_scanpos; - if (jj_3R_149()) { jj_scanpos = xsp; break; } + if (jj_3R_149()){ + jj_scanpos = xsp; + break; + } } return false; } - private boolean jj_3R_46() { + private boolean jj_3R_46(){ Token xsp; xsp = jj_scanpos; - if (jj_scan_token(24)) { + if (jj_scan_token(24)){ jj_scanpos = xsp; - if (jj_3R_62()) return true; + if (jj_3R_62()) + return true; } return false; } - private boolean jj_3R_30() { + private boolean jj_3R_30(){ Token xsp; xsp = jj_scanpos; - if (jj_3R_46()) jj_scanpos = xsp; - if (jj_scan_token(JOIN)) return true; - if (jj_3R_47()) return true; + if (jj_3R_46()) + jj_scanpos = xsp; + if (jj_scan_token(JOIN)) + return true; + if (jj_3R_47()) + return true; xsp = jj_scanpos; - if (jj_3R_178()) { + if (jj_3R_178()){ jj_scanpos = xsp; - if (jj_3R_179()) return true; + if (jj_3R_179()) + return true; } return false; } - private boolean jj_3R_127() { - if (jj_scan_token(POLYGON)) return true; - if (jj_scan_token(LEFT_PAR)) return true; - if (jj_3R_158()) return true; - if (jj_scan_token(COMMA)) return true; - if (jj_3R_159()) return true; - if (jj_scan_token(COMMA)) return true; - if (jj_3R_159()) return true; - if (jj_scan_token(COMMA)) return true; - if (jj_3R_159()) return true; + private boolean jj_3R_127(){ + if (jj_scan_token(POLYGON)) + return true; + if (jj_scan_token(LEFT_PAR)) + return true; + if (jj_3R_158()) + return true; + if (jj_scan_token(COMMA)) + return true; + if (jj_3R_159()) + return true; + if (jj_scan_token(COMMA)) + return true; + if (jj_3R_159()) + return true; + if (jj_scan_token(COMMA)) + return true; + if (jj_3R_159()) + return true; Token xsp; - while (true) { + while(true){ xsp = jj_scanpos; - if (jj_3R_160()) { jj_scanpos = xsp; break; } + if (jj_3R_160()){ + jj_scanpos = xsp; + break; + } } - if (jj_scan_token(RIGHT_PAR)) return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_29() { - if (jj_scan_token(NATURAL)) return true; + private boolean jj_3R_29(){ + if (jj_scan_token(NATURAL)) + return true; Token xsp; xsp = jj_scanpos; - if (jj_3R_45()) jj_scanpos = xsp; - if (jj_scan_token(JOIN)) return true; - if (jj_3R_47()) return true; + if (jj_3R_45()) + jj_scanpos = xsp; + if (jj_scan_token(JOIN)) + return true; + if (jj_3R_47()) + return true; return false; } - private boolean jj_3R_126() { - if (jj_3R_147()) return true; + private boolean jj_3R_126(){ + if (jj_3R_147()) + return true; return false; } - private boolean jj_3R_172() { + private boolean jj_3R_172(){ Token xsp; xsp = jj_scanpos; - if (jj_scan_token(22)) jj_scanpos = xsp; - if (jj_3R_14()) return true; + if (jj_scan_token(22)) + jj_scanpos = xsp; + if (jj_3R_14()) + return true; return false; } - private boolean jj_3R_125() { - if (jj_scan_token(CIRCLE)) return true; - if (jj_scan_token(LEFT_PAR)) return true; - if (jj_3R_158()) return true; - if (jj_scan_token(COMMA)) return true; - if (jj_3R_159()) return true; - if (jj_scan_token(COMMA)) return true; - if (jj_3R_101()) return true; - if (jj_scan_token(RIGHT_PAR)) return true; + private boolean jj_3R_125(){ + if (jj_scan_token(CIRCLE)) + return true; + if (jj_scan_token(LEFT_PAR)) + return true; + if (jj_3R_158()) + return true; + if (jj_scan_token(COMMA)) + return true; + if (jj_3R_159()) + return true; + if (jj_scan_token(COMMA)) + return true; + if (jj_3R_101()) + return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_124() { - if (jj_scan_token(CENTROID)) return true; - if (jj_scan_token(LEFT_PAR)) return true; - if (jj_3R_64()) return true; - if (jj_scan_token(RIGHT_PAR)) return true; + private boolean jj_3R_124(){ + if (jj_scan_token(CENTROID)) + return true; + if (jj_scan_token(LEFT_PAR)) + return true; + if (jj_3R_64()) + return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_170() { + private boolean jj_3R_170(){ Token xsp; xsp = jj_scanpos; - if (jj_scan_token(45)) { + if (jj_scan_token(45)){ jj_scanpos = xsp; - if (jj_scan_token(46)) return true; + if (jj_scan_token(46)) + return true; } return false; } - private boolean jj_3R_123() { - if (jj_scan_token(BOX)) return true; - if (jj_scan_token(LEFT_PAR)) return true; - if (jj_3R_158()) return true; - if (jj_scan_token(COMMA)) return true; - if (jj_3R_159()) return true; - if (jj_scan_token(COMMA)) return true; - if (jj_3R_101()) return true; - if (jj_scan_token(COMMA)) return true; - if (jj_3R_101()) return true; - if (jj_scan_token(RIGHT_PAR)) return true; - return false; - } - - private boolean jj_3R_17() { + private boolean jj_3R_123(){ + if (jj_scan_token(BOX)) + return true; + if (jj_scan_token(LEFT_PAR)) + return true; + if (jj_3R_158()) + return true; + if (jj_scan_token(COMMA)) + return true; + if (jj_3R_159()) + return true; + if (jj_scan_token(COMMA)) + return true; + if (jj_3R_101()) + return true; + if (jj_scan_token(COMMA)) + return true; + if (jj_3R_101()) + return true; + if (jj_scan_token(RIGHT_PAR)) + return true; + return false; + } + + private boolean jj_3R_17(){ Token xsp; xsp = jj_scanpos; - if (jj_3R_29()) { + if (jj_3R_29()){ jj_scanpos = xsp; - if (jj_3R_30()) return true; + if (jj_3R_30()) + return true; } return false; } - private boolean jj_3R_177() { - if (jj_3R_17()) return true; + private boolean jj_3R_177(){ + if (jj_3R_17()) + return true; return false; } - private boolean jj_3R_110() { - if (jj_scan_token(LEFT_PAR)) return true; - if (jj_3R_173()) return true; - if (jj_scan_token(RIGHT_PAR)) return true; + private boolean jj_3R_110(){ + if (jj_scan_token(LEFT_PAR)) + return true; + if (jj_3R_173()) + return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_173() { - if (jj_3R_63()) return true; + private boolean jj_3R_173(){ + if (jj_3R_63()) + return true; Token xsp; - if (jj_3R_177()) return true; - while (true) { + if (jj_3R_177()) + return true; + while(true){ xsp = jj_scanpos; - if (jj_3R_177()) { jj_scanpos = xsp; break; } + if (jj_3R_177()){ + jj_scanpos = xsp; + break; + } } return false; } - private boolean jj_3R_191() { - if (jj_3R_23()) return true; + private boolean jj_3R_191(){ + if (jj_3R_23()) + return true; return false; } - private boolean jj_3R_100() { + private boolean jj_3R_100(){ Token xsp; xsp = jj_scanpos; - if (jj_3R_123()) { + if (jj_3R_123()){ jj_scanpos = xsp; - if (jj_3R_124()) { + if (jj_3R_124()){ jj_scanpos = xsp; - if (jj_3R_125()) { + if (jj_3R_125()){ jj_scanpos = xsp; - if (jj_3R_126()) { + if (jj_3R_126()){ jj_scanpos = xsp; - if (jj_3R_127()) { + if (jj_3R_127()){ jj_scanpos = xsp; - if (jj_3R_128()) return true; + if (jj_3R_128()) + return true; } } } @@ -4183,210 +4880,262 @@ public class ADQLParser implements ADQLParserConstants { return false; } - private boolean jj_3_3() { - if (jj_3R_17()) return true; + private boolean jj_3_3(){ + if (jj_3R_17()) + return true; return false; } - private boolean jj_3R_150() { - if (jj_3R_41()) return true; + private boolean jj_3R_150(){ + if (jj_3R_41()) + return true; return false; } - private boolean jj_3R_109() { - if (jj_3R_102()) return true; + private boolean jj_3R_109(){ + if (jj_3R_102()) + return true; Token xsp; xsp = jj_scanpos; - if (jj_3R_172()) jj_scanpos = xsp; + if (jj_3R_172()) + jj_scanpos = xsp; return false; } - private boolean jj_3R_47() { - if (jj_3R_63()) return true; + private boolean jj_3R_47(){ + if (jj_3R_63()) + return true; Token xsp; - while (true) { + while(true){ xsp = jj_scanpos; - if (jj_3_3()) { jj_scanpos = xsp; break; } + if (jj_3_3()){ + jj_scanpos = xsp; + break; + } } return false; } - private boolean jj_3R_189() { - if (jj_3R_23()) return true; + private boolean jj_3R_189(){ + if (jj_3R_23()) + return true; return false; } - private boolean jj_3R_186() { - if (jj_3R_147()) return true; + private boolean jj_3R_186(){ + if (jj_3R_147()) + return true; return false; } - private boolean jj_3_2() { - if (jj_3R_16()) return true; + private boolean jj_3_2(){ + if (jj_3R_16()) + return true; Token xsp; xsp = jj_scanpos; - if (jj_scan_token(22)) jj_scanpos = xsp; - if (jj_3R_14()) return true; + if (jj_scan_token(22)) + jj_scanpos = xsp; + if (jj_3R_14()) + return true; return false; } - private boolean jj_3R_184() { - if (jj_3R_147()) return true; + private boolean jj_3R_184(){ + if (jj_3R_147()) + return true; return false; } - private boolean jj_3R_190() { - if (jj_3R_147()) return true; + private boolean jj_3R_190(){ + if (jj_3R_147()) + return true; return false; } - private boolean jj_3R_158() { - if (jj_3R_24()) return true; + private boolean jj_3R_158(){ + if (jj_3R_24()) + return true; return false; } - private boolean jj_3R_188() { - if (jj_3R_147()) return true; + private boolean jj_3R_188(){ + if (jj_3R_147()) + return true; return false; } - private boolean jj_3R_63() { + private boolean jj_3R_63(){ Token xsp; xsp = jj_scanpos; - if (jj_3R_109()) { + if (jj_3R_109()){ jj_scanpos = xsp; - if (jj_3_2()) { + if (jj_3_2()){ jj_scanpos = xsp; - if (jj_3R_110()) return true; + if (jj_3R_110()) + return true; } } return false; } - private boolean jj_3R_97() { - if (jj_scan_token(DISTANCE)) return true; - if (jj_scan_token(LEFT_PAR)) return true; + private boolean jj_3R_97(){ + if (jj_scan_token(DISTANCE)) + return true; + if (jj_scan_token(LEFT_PAR)) + return true; Token xsp; xsp = jj_scanpos; - if (jj_3R_188()) { + if (jj_3R_188()){ jj_scanpos = xsp; - if (jj_3R_189()) return true; + if (jj_3R_189()) + return true; } - if (jj_scan_token(COMMA)) return true; + if (jj_scan_token(COMMA)) + return true; xsp = jj_scanpos; - if (jj_3R_190()) { + if (jj_3R_190()){ jj_scanpos = xsp; - if (jj_3R_191()) return true; + if (jj_3R_191()) + return true; } - if (jj_scan_token(RIGHT_PAR)) return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_96() { - if (jj_scan_token(COORD2)) return true; - if (jj_scan_token(LEFT_PAR)) return true; + private boolean jj_3R_96(){ + if (jj_scan_token(COORD2)) + return true; + if (jj_scan_token(LEFT_PAR)) + return true; Token xsp; xsp = jj_scanpos; - if (jj_3R_186()) { + if (jj_3R_186()){ jj_scanpos = xsp; - if (jj_3R_187()) return true; + if (jj_3R_187()) + return true; } - if (jj_scan_token(RIGHT_PAR)) return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_95() { - if (jj_scan_token(COORD1)) return true; - if (jj_scan_token(LEFT_PAR)) return true; + private boolean jj_3R_95(){ + if (jj_scan_token(COORD1)) + return true; + if (jj_scan_token(LEFT_PAR)) + return true; Token xsp; xsp = jj_scanpos; - if (jj_3R_184()) { + if (jj_3R_184()){ jj_scanpos = xsp; - if (jj_3R_185()) return true; + if (jj_3R_185()) + return true; } - if (jj_scan_token(RIGHT_PAR)) return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_94() { - if (jj_scan_token(AREA)) return true; - if (jj_scan_token(LEFT_PAR)) return true; - if (jj_3R_64()) return true; - if (jj_scan_token(RIGHT_PAR)) return true; + private boolean jj_3R_94(){ + if (jj_scan_token(AREA)) + return true; + if (jj_scan_token(LEFT_PAR)) + return true; + if (jj_3R_64()) + return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_169() { - if (jj_3R_42()) return true; + private boolean jj_3R_169(){ + if (jj_3R_42()) + return true; return false; } - private boolean jj_3R_156() { + private boolean jj_3R_156(){ Token xsp; xsp = jj_scanpos; - if (jj_3R_169()) { + if (jj_3R_169()){ jj_scanpos = xsp; - if (jj_scan_token(101)) return true; + if (jj_scan_token(101)) + return true; } xsp = jj_scanpos; - if (jj_3R_170()) jj_scanpos = xsp; + if (jj_3R_170()) + jj_scanpos = xsp; return false; } - private boolean jj_3R_93() { + private boolean jj_3R_93(){ Token xsp; xsp = jj_scanpos; - if (jj_scan_token(58)) { + if (jj_scan_token(58)){ jj_scanpos = xsp; - if (jj_scan_token(59)) return true; + if (jj_scan_token(59)) + return true; } - if (jj_scan_token(LEFT_PAR)) return true; - if (jj_3R_64()) return true; - if (jj_scan_token(COMMA)) return true; - if (jj_3R_64()) return true; - if (jj_scan_token(RIGHT_PAR)) return true; + if (jj_scan_token(LEFT_PAR)) + return true; + if (jj_3R_64()) + return true; + if (jj_scan_token(COMMA)) + return true; + if (jj_3R_64()) + return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_146() { - if (jj_scan_token(COMMA)) return true; - if (jj_3R_41()) return true; + private boolean jj_3R_146(){ + if (jj_scan_token(COMMA)) + return true; + if (jj_3R_41()) + return true; return false; } - private boolean jj_3R_168() { - if (jj_3R_42()) return true; + private boolean jj_3R_168(){ + if (jj_3R_42()) + return true; return false; } - private boolean jj_3R_154() { + private boolean jj_3R_154(){ Token xsp; xsp = jj_scanpos; - if (jj_3R_168()) { + if (jj_3R_168()){ jj_scanpos = xsp; - if (jj_scan_token(101)) return true; + if (jj_scan_token(101)) + return true; } return false; } - private boolean jj_3R_60() { - if (jj_scan_token(DOT)) return true; - if (jj_3R_102()) return true; + private boolean jj_3R_60(){ + if (jj_scan_token(DOT)) + return true; + if (jj_3R_102()) + return true; return false; } - private boolean jj_3R_52() { + private boolean jj_3R_52(){ Token xsp; xsp = jj_scanpos; - if (jj_3R_93()) { + if (jj_3R_93()){ jj_scanpos = xsp; - if (jj_3R_94()) { + if (jj_3R_94()){ jj_scanpos = xsp; - if (jj_3R_95()) { + if (jj_3R_95()){ jj_scanpos = xsp; - if (jj_3R_96()) { + if (jj_3R_96()){ jj_scanpos = xsp; - if (jj_3R_97()) return true; + if (jj_3R_97()) + return true; } } } @@ -4394,449 +5143,571 @@ public class ADQLParser implements ADQLParserConstants { return false; } - private boolean jj_3R_135() { + private boolean jj_3R_135(){ Token xsp; xsp = jj_scanpos; - if (jj_scan_token(47)) { + if (jj_scan_token(47)){ jj_scanpos = xsp; - if (jj_scan_token(48)) { + if (jj_scan_token(48)){ jj_scanpos = xsp; - if (jj_scan_token(49)) { + if (jj_scan_token(49)){ jj_scanpos = xsp; - if (jj_scan_token(50)) return true; + if (jj_scan_token(50)) + return true; } } } - if (jj_scan_token(LEFT_PAR)) return true; + if (jj_scan_token(LEFT_PAR)) + return true; xsp = jj_scanpos; - if (jj_scan_token(19)) jj_scanpos = xsp; - if (jj_3R_41()) return true; - if (jj_scan_token(RIGHT_PAR)) return true; + if (jj_scan_token(19)) + jj_scanpos = xsp; + if (jj_3R_41()) + return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_159() { - if (jj_3R_101()) return true; - if (jj_scan_token(COMMA)) return true; - if (jj_3R_101()) return true; + private boolean jj_3R_159(){ + if (jj_3R_101()) + return true; + if (jj_scan_token(COMMA)) + return true; + if (jj_3R_101()) + return true; return false; } - private boolean jj_3R_23() { - if (jj_3R_42()) return true; + private boolean jj_3R_23(){ + if (jj_3R_42()) + return true; return false; } - private boolean jj_3R_134() { - if (jj_scan_token(COUNT)) return true; - if (jj_scan_token(LEFT_PAR)) return true; + private boolean jj_3R_134(){ + if (jj_scan_token(COUNT)) + return true; + if (jj_scan_token(LEFT_PAR)) + return true; Token xsp; xsp = jj_scanpos; - if (jj_scan_token(19)) jj_scanpos = xsp; + if (jj_scan_token(19)) + jj_scanpos = xsp; xsp = jj_scanpos; - if (jj_scan_token(10)) { + if (jj_scan_token(10)){ jj_scanpos = xsp; - if (jj_3R_150()) return true; + if (jj_3R_150()) + return true; } - if (jj_scan_token(RIGHT_PAR)) return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_42() { - if (jj_3R_14()) return true; + private boolean jj_3R_42(){ + if (jj_3R_14()) + return true; Token xsp; xsp = jj_scanpos; - if (jj_3R_60()) jj_scanpos = xsp; + if (jj_3R_60()) + jj_scanpos = xsp; return false; } - private boolean jj_3R_131() { - if (jj_scan_token(DOT)) return true; - if (jj_3R_14()) return true; + private boolean jj_3R_131(){ + if (jj_scan_token(DOT)) + return true; + if (jj_3R_14()) + return true; return false; } - private boolean jj_3R_130() { - if (jj_scan_token(DOT)) return true; - if (jj_3R_14()) return true; + private boolean jj_3R_130(){ + if (jj_scan_token(DOT)) + return true; + if (jj_3R_14()) + return true; return false; } - private boolean jj_3R_116() { + private boolean jj_3R_116(){ Token xsp; xsp = jj_scanpos; - if (jj_3R_134()) { + if (jj_3R_134()){ jj_scanpos = xsp; - if (jj_3R_135()) return true; + if (jj_3R_135()) + return true; } return false; } - private boolean jj_3R_102() { - if (jj_3R_14()) return true; + private boolean jj_3R_102(){ + if (jj_3R_14()) + return true; Token xsp; xsp = jj_scanpos; - if (jj_3R_130()) jj_scanpos = xsp; + if (jj_3R_130()) + jj_scanpos = xsp; xsp = jj_scanpos; - if (jj_3R_131()) jj_scanpos = xsp; + if (jj_3R_131()) + jj_scanpos = xsp; return false; } - private boolean jj_3R_26() { - if (jj_scan_token(DELIMITED_IDENTIFIER)) return true; + private boolean jj_3R_26(){ + if (jj_scan_token(DELIMITED_IDENTIFIER)) + return true; return false; } - private boolean jj_3R_25() { - if (jj_scan_token(REGULAR_IDENTIFIER)) return true; + private boolean jj_3R_25(){ + if (jj_scan_token(REGULAR_IDENTIFIER)) + return true; return false; } - private boolean jj_3R_122() { - if (jj_scan_token(LEFT_PAR)) return true; - if (jj_3R_41()) return true; + private boolean jj_3R_122(){ + if (jj_scan_token(LEFT_PAR)) + return true; + if (jj_3R_41()) + return true; Token xsp; - while (true) { + while(true){ xsp = jj_scanpos; - if (jj_3R_146()) { jj_scanpos = xsp; break; } + if (jj_3R_146()){ + jj_scanpos = xsp; + break; + } } - if (jj_scan_token(RIGHT_PAR)) return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_14() { + private boolean jj_3R_14(){ Token xsp; xsp = jj_scanpos; - if (jj_3R_25()) { + if (jj_3R_25()){ jj_scanpos = xsp; - if (jj_3R_26()) return true; + if (jj_3R_26()) + return true; } return false; } - private boolean jj_3_13() { - if (jj_3R_16()) return true; + private boolean jj_3_13(){ + if (jj_3R_16()) + return true; return false; } - private boolean jj_3R_99() { + private boolean jj_3R_99(){ Token xsp; xsp = jj_scanpos; - if (jj_scan_token(35)) jj_scanpos = xsp; - if (jj_scan_token(IN)) return true; + if (jj_scan_token(35)) + jj_scanpos = xsp; + if (jj_scan_token(IN)) + return true; xsp = jj_scanpos; - if (jj_3_13()) { + if (jj_3_13()){ jj_scanpos = xsp; - if (jj_3R_122()) return true; + if (jj_3R_122()) + return true; } return false; } - private boolean jj_3R_157() { - if (jj_scan_token(COMMA)) return true; - if (jj_3R_156()) return true; + private boolean jj_3R_157(){ + if (jj_scan_token(COMMA)) + return true; + if (jj_3R_156()) + return true; return false; } - private boolean jj_3R_144() { - if (jj_scan_token(ORDER_BY)) return true; - if (jj_3R_156()) return true; + private boolean jj_3R_144(){ + if (jj_scan_token(ORDER_BY)) + return true; + if (jj_3R_156()) + return true; Token xsp; - while (true) { + while(true){ xsp = jj_scanpos; - if (jj_3R_157()) { jj_scanpos = xsp; break; } + if (jj_3R_157()){ + jj_scanpos = xsp; + break; + } } return false; } - private boolean jj_3R_143() { - if (jj_scan_token(HAVING)) return true; - if (jj_3R_153()) return true; + private boolean jj_3R_143(){ + if (jj_scan_token(HAVING)) + return true; + if (jj_3R_153()) + return true; return false; } - private boolean jj_3R_155() { - if (jj_scan_token(COMMA)) return true; - if (jj_3R_154()) return true; + private boolean jj_3R_155(){ + if (jj_scan_token(COMMA)) + return true; + if (jj_3R_154()) + return true; return false; } - private boolean jj_3R_22() { + private boolean jj_3R_22(){ Token xsp; xsp = jj_scanpos; - if (jj_scan_token(35)) jj_scanpos = xsp; - if (jj_scan_token(BETWEEN)) return true; - if (jj_3R_41()) return true; - if (jj_scan_token(AND)) return true; - if (jj_3R_41()) return true; + if (jj_scan_token(35)) + jj_scanpos = xsp; + if (jj_scan_token(BETWEEN)) + return true; + if (jj_3R_41()) + return true; + if (jj_scan_token(AND)) + return true; + if (jj_3R_41()) + return true; return false; } - private boolean jj_3R_164() { - if (jj_scan_token(AS)) return true; - if (jj_3R_14()) return true; + private boolean jj_3R_164(){ + if (jj_scan_token(AS)) + return true; + if (jj_3R_14()) + return true; return false; } - private boolean jj_3R_142() { - if (jj_scan_token(GROUP_BY)) return true; - if (jj_3R_154()) return true; + private boolean jj_3R_142(){ + if (jj_scan_token(GROUP_BY)) + return true; + if (jj_3R_154()) + return true; Token xsp; - while (true) { + while(true){ xsp = jj_scanpos; - if (jj_3R_155()) { jj_scanpos = xsp; break; } + if (jj_3R_155()){ + jj_scanpos = xsp; + break; + } } return false; } - private boolean jj_3R_54() { - if (jj_3R_99()) return true; + private boolean jj_3R_54(){ + if (jj_3R_99()) + return true; return false; } - private boolean jj_3_10() { - if (jj_3R_22()) return true; + private boolean jj_3_10(){ + if (jj_3R_22()) + return true; return false; } - private boolean jj_3R_140() { - if (jj_scan_token(COMMA)) return true; - if (jj_3R_47()) return true; + private boolean jj_3R_140(){ + if (jj_scan_token(COMMA)) + return true; + if (jj_3R_47()) + return true; return false; } - private boolean jj_3R_141() { - if (jj_scan_token(WHERE)) return true; - if (jj_3R_153()) return true; + private boolean jj_3R_141(){ + if (jj_scan_token(WHERE)) + return true; + if (jj_3R_153()) + return true; return false; } - private boolean jj_3_12() { - if (jj_3R_24()) return true; + private boolean jj_3_12(){ + if (jj_3R_24()) + return true; Token xsp; xsp = jj_scanpos; - if (jj_scan_token(35)) jj_scanpos = xsp; - if (jj_scan_token(LIKE)) return true; + if (jj_scan_token(35)) + jj_scanpos = xsp; + if (jj_scan_token(LIKE)) + return true; return false; } - private boolean jj_3R_53() { - if (jj_3R_98()) return true; + private boolean jj_3R_53(){ + if (jj_3R_98()) + return true; return false; } - private boolean jj_3_11() { - if (jj_3R_23()) return true; - if (jj_scan_token(IS)) return true; + private boolean jj_3_11(){ + if (jj_3R_23()) + return true; + if (jj_scan_token(IS)) + return true; return false; } - private boolean jj_3R_98() { + private boolean jj_3R_98(){ Token xsp; xsp = jj_scanpos; - if (jj_scan_token(12)) { + if (jj_scan_token(12)){ jj_scanpos = xsp; - if (jj_scan_token(13)) { + if (jj_scan_token(13)){ jj_scanpos = xsp; - if (jj_scan_token(14)) { + if (jj_scan_token(14)){ jj_scanpos = xsp; - if (jj_scan_token(15)) { + if (jj_scan_token(15)){ jj_scanpos = xsp; - if (jj_scan_token(16)) { + if (jj_scan_token(16)){ jj_scanpos = xsp; - if (jj_scan_token(17)) return true; + if (jj_scan_token(17)) + return true; } } } } } - if (jj_3R_41()) return true; + if (jj_3R_41()) + return true; return false; } - private boolean jj_3R_27() { - if (jj_3R_14()) return true; - if (jj_scan_token(DOT)) return true; + private boolean jj_3R_27(){ + if (jj_3R_14()) + return true; + if (jj_scan_token(DOT)) + return true; return false; } - private boolean jj_3R_117() { - if (jj_scan_token(FROM)) return true; - if (jj_3R_47()) return true; + private boolean jj_3R_117(){ + if (jj_scan_token(FROM)) + return true; + if (jj_3R_47()) + return true; Token xsp; - while (true) { + while(true){ xsp = jj_scanpos; - if (jj_3R_140()) { jj_scanpos = xsp; break; } + if (jj_3R_140()){ + jj_scanpos = xsp; + break; + } } return false; } - private boolean jj_3R_40() { - if (jj_3R_41()) return true; + private boolean jj_3R_40(){ + if (jj_3R_41()) + return true; Token xsp; xsp = jj_scanpos; - if (jj_3R_53()) { + if (jj_3R_53()){ jj_scanpos = xsp; - if (jj_3_10()) { + if (jj_3_10()){ jj_scanpos = xsp; - if (jj_3R_54()) return true; + if (jj_3R_54()) + return true; } } return false; } - private boolean jj_3R_39() { - if (jj_3R_24()) return true; + private boolean jj_3R_39(){ + if (jj_3R_24()) + return true; Token xsp; xsp = jj_scanpos; - if (jj_scan_token(35)) jj_scanpos = xsp; - if (jj_scan_token(LIKE)) return true; - if (jj_3R_24()) return true; + if (jj_scan_token(35)) + jj_scanpos = xsp; + if (jj_scan_token(LIKE)) + return true; + if (jj_3R_24()) + return true; return false; } - private boolean jj_3R_38() { - if (jj_3R_23()) return true; - if (jj_scan_token(IS)) return true; + private boolean jj_3R_38(){ + if (jj_3R_23()) + return true; + if (jj_scan_token(IS)) + return true; Token xsp; xsp = jj_scanpos; - if (jj_scan_token(35)) jj_scanpos = xsp; - if (jj_scan_token(NULL)) return true; + if (jj_scan_token(35)) + jj_scanpos = xsp; + if (jj_scan_token(NULL)) + return true; return false; } - private boolean jj_3R_37() { - if (jj_scan_token(EXISTS)) return true; - if (jj_3R_16()) return true; + private boolean jj_3R_37(){ + if (jj_scan_token(EXISTS)) + return true; + if (jj_3R_16()) + return true; return false; } - private boolean jj_3R_152() { - if (jj_3R_41()) return true; + private boolean jj_3R_152(){ + if (jj_3R_41()) + return true; Token xsp; xsp = jj_scanpos; - if (jj_3R_164()) jj_scanpos = xsp; + if (jj_3R_164()) + jj_scanpos = xsp; return false; } - private boolean jj_3R_15() { - if (jj_3R_14()) return true; - if (jj_scan_token(DOT)) return true; + private boolean jj_3R_15(){ + if (jj_3R_14()) + return true; + if (jj_scan_token(DOT)) + return true; Token xsp; xsp = jj_scanpos; - if (jj_3R_27()) jj_scanpos = xsp; + if (jj_3R_27()) + jj_scanpos = xsp; return false; } - private boolean jj_3R_21() { + private boolean jj_3R_21(){ Token xsp; xsp = jj_scanpos; - if (jj_3R_37()) { + if (jj_3R_37()){ jj_scanpos = xsp; - if (jj_3R_38()) { + if (jj_3R_38()){ jj_scanpos = xsp; - if (jj_3R_39()) { + if (jj_3R_39()){ jj_scanpos = xsp; - if (jj_3R_40()) return true; + if (jj_3R_40()) + return true; } } } return false; } - private boolean jj_3_9() { - if (jj_3R_21()) return true; + private boolean jj_3_9(){ + if (jj_3R_21()) + return true; return false; } - private boolean jj_3R_151() { - if (jj_scan_token(ASTERISK)) return true; + private boolean jj_3R_151(){ + if (jj_scan_token(ASTERISK)) + return true; return false; } - private boolean jj_3R_175() { - if (jj_scan_token(LEFT_PAR)) return true; - if (jj_3R_153()) return true; - if (jj_scan_token(RIGHT_PAR)) return true; + private boolean jj_3R_175(){ + if (jj_scan_token(LEFT_PAR)) + return true; + if (jj_3R_153()) + return true; + if (jj_scan_token(RIGHT_PAR)) + return true; return false; } - private boolean jj_3R_174() { - if (jj_3R_21()) return true; + private boolean jj_3R_174(){ + if (jj_3R_21()) + return true; return false; } - private boolean jj_3R_166() { + private boolean jj_3R_166(){ Token xsp; xsp = jj_scanpos; - if (jj_3R_174()) { + if (jj_3R_174()){ jj_scanpos = xsp; - if (jj_3R_175()) return true; + if (jj_3R_175()) + return true; } return false; } - private boolean jj_3R_176() { - if (jj_scan_token(NOT)) return true; + private boolean jj_3R_176(){ + if (jj_scan_token(NOT)) + return true; return false; } - private boolean jj_3_1() { - if (jj_3R_14()) return true; - if (jj_scan_token(DOT)) return true; + private boolean jj_3_1(){ + if (jj_3R_14()) + return true; + if (jj_scan_token(DOT)) + return true; Token xsp; xsp = jj_scanpos; - if (jj_3R_15()) jj_scanpos = xsp; - if (jj_scan_token(ASTERISK)) return true; + if (jj_3R_15()) + jj_scanpos = xsp; + if (jj_scan_token(ASTERISK)) + return true; return false; } - private boolean jj_3R_167() { + private boolean jj_3R_167(){ Token xsp; xsp = jj_scanpos; - if (jj_scan_token(33)) { + if (jj_scan_token(33)){ jj_scanpos = xsp; - if (jj_scan_token(34)) return true; + if (jj_scan_token(34)) + return true; } xsp = jj_scanpos; - if (jj_3R_176()) jj_scanpos = xsp; - if (jj_3R_166()) return true; + if (jj_3R_176()) + jj_scanpos = xsp; + if (jj_3R_166()) + return true; return false; } - private boolean jj_3R_138() { + private boolean jj_3R_138(){ Token xsp; xsp = jj_scanpos; - if (jj_3R_151()) { + if (jj_3R_151()){ jj_scanpos = xsp; - if (jj_3_1()) { + if (jj_3_1()){ jj_scanpos = xsp; - if (jj_3R_152()) return true; + if (jj_3R_152()) + return true; } } return false; } - private boolean jj_3R_139() { - if (jj_scan_token(COMMA)) return true; - if (jj_3R_138()) return true; + private boolean jj_3R_139(){ + if (jj_scan_token(COMMA)) + return true; + if (jj_3R_138()) + return true; return false; } - private boolean jj_3R_113() { - if (jj_scan_token(COMMA)) return true; - if (jj_3R_41()) return true; + private boolean jj_3R_113(){ + if (jj_scan_token(COMMA)) + return true; + if (jj_3R_41()) + return true; return false; } - private boolean jj_3R_137() { - if (jj_scan_token(TOP)) return true; - if (jj_scan_token(UNSIGNED_INTEGER)) return true; + private boolean jj_3R_137(){ + if (jj_scan_token(TOP)) + return true; + if (jj_scan_token(UNSIGNED_INTEGER)) + return true; return false; } - private boolean jj_3R_136() { - if (jj_scan_token(QUANTIFIER)) return true; + private boolean jj_3R_136(){ + if (jj_scan_token(QUANTIFIER)) + return true; return false; } @@ -4856,113 +5727,143 @@ public class ADQLParser implements ADQLParserConstants { static private int[] jj_la1_1; static private int[] jj_la1_2; static private int[] jj_la1_3; - static { + static{ jj_la1_init_0(); jj_la1_init_1(); jj_la1_init_2(); jj_la1_init_3(); } - private static void jj_la1_init_0() { - jj_la1_0 = new int[] {0x41,0x0,0x0,0x0,0x0,0x80000,0x100000,0x20,0x0,0x0,0x400000,0x400,0x304,0x20,0x20,0x20,0x0,0x10,0x10,0x10,0x0,0x0,0x0,0x0,0x400000,0x400000,0x400000,0x0,0x4,0x3d800000,0x1c000000,0x2000000,0x1d000000,0x1d000000,0x1c000000,0x2000000,0x1d000000,0x1d000000,0x20,0xc0000000,0x3d800000,0x0,0x0,0x0,0x300,0x300,0x0,0x4,0x0,0x304,0x300,0x300,0xc00,0xc00,0x300,0x300,0x4,0x80,0x0,0x4,0x0,0x0,0x0,0x0,0x0,0x4,0x0,0x0,0x3f000,0x0,0x0,0x304,0x3f000,0x0,0x0,0x20,0x4,0x80000,0x704,0x0,0x80000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x20,0x0,0x0,0x304,0x20,0x20,0x0,0x0,0x20,0x304,}; + + private static void jj_la1_init_0(){ + jj_la1_0 = new int[]{0x41,0x0,0x0,0x0,0x0,0x80000,0x100000,0x20,0x0,0x0,0x400000,0x400,0x304,0x20,0x20,0x20,0x0,0x10,0x10,0x10,0x0,0x0,0x0,0x0,0x400000,0x400000,0x400000,0x0,0x4,0x3d800000,0x1c000000,0x2000000,0x1d000000,0x1d000000,0x1c000000,0x2000000,0x1d000000,0x1d000000,0x20,0xc0000000,0x3d800000,0x0,0x0,0x0,0x300,0x300,0x0,0x4,0x0,0x304,0x300,0x300,0xc00,0xc00,0x300,0x300,0x4,0x80,0x0,0x4,0x0,0x0,0x0,0x0,0x0,0x4,0x0,0x0,0x3f000,0x0,0x0,0x304,0x3f000,0x0,0x0,0x20,0x4,0x80000,0x704,0x0,0x80000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x20,0x0,0x0,0x304,0x20,0x20,0x0,0x0,0x20,0x304,}; } - private static void jj_la1_init_1() { - jj_la1_1 = new int[] {0x0,0x1,0x400,0x800,0x1000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xffff8000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x6000,0x6000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xf8000,0x3f00000,0x7c0f8000,0x0,0x0,0x0,0x0,0x0,0x0,0xf8000,0x0,0x80000000,0xf8000,0x3f00000,0x8,0x6,0x6,0x8,0x0,0x8,0x8,0x0,0x108,0x200,0xffff8000,0x0,0x8,0x8,0x0,0x0,0x0,0xffff8000,0x78000,0x0,0xf8000,0xc000000,0x800000,0x800000,0x800000,0x800000,0x7c000000,0x0,0x3f00000,0x7c000000,0x7c0f8000,0x0,0x0,0x0,0x0,0x0,0xffff8000,}; + + private static void jj_la1_init_1(){ + jj_la1_1 = new int[]{0x0,0x1,0x400,0x800,0x1000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xffff8000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x6000,0x6000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xf8000,0x3f00000,0x7c0f8000,0x0,0x0,0x0,0x0,0x0,0x0,0xf8000,0x0,0x80000000,0xf8000,0x3f00000,0x8,0x6,0x6,0x8,0x0,0x8,0x8,0x0,0x108,0x200,0xffff8000,0x0,0x8,0x8,0x0,0x0,0x0,0xffff8000,0x78000,0x0,0xf8000,0xc000000,0x800000,0x800000,0x800000,0x800000,0x7c000000,0x0,0x3f00000,0x7c000000,0x7c0f8000,0x0,0x0,0x0,0x0,0x0,0xffff8000,}; } - private static void jj_la1_init_2() { - jj_la1_2 = new int[] {0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x20ffffff,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x20000000,0x0,0x0,0x0,0x0,0x20000000,0x20000000,0x0,0x20ffffff,0x0,0x0,0x0,0x0,0x0,0x0,0x20000000,0x0,0x0,0x20000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x20ffffff,0x0,0x0,0x0,0x0,0x0,0x0,0x20ffffff,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0xffffff,0x20ffffff,0x0,0x0,0xfffe,0xff0000,0x0,0x20ffffff,}; + + private static void jj_la1_init_2(){ + jj_la1_2 = new int[]{0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x20ffffff,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x20000000,0x0,0x0,0x0,0x0,0x20000000,0x20000000,0x0,0x20ffffff,0x0,0x0,0x0,0x0,0x0,0x0,0x20000000,0x0,0x0,0x20000000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x20ffffff,0x0,0x0,0x0,0x0,0x0,0x0,0x20ffffff,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0xffffff,0x20ffffff,0x0,0x0,0xfffe,0xff0000,0x0,0x20ffffff,}; } - private static void jj_la1_init_3() { - jj_la1_3 = new int[] {0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3,0x3,0x0,0x0,0x3b,0x0,0x0,0x0,0x3,0x0,0x0,0x0,0x23,0x23,0x0,0x0,0x0,0x3,0x0,0x3,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x38,0x30,0x0,0x0,0x38,0x3b,0x0,0x3b,0x0,0x0,0x0,0x0,0x0,0x0,0x3b,0x0,0x0,0x3b,0x3,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3b,0x0,0x0,0x0,0x0,0x0,0x0,0x3b,0x0,0x0,0x0,0x0,0x3,0x3,0x3,0x3,0x0,0x0,0x0,0x2,0x3b,0x0,0x0,0x0,0x0,0x0,0x3b,}; + + private static void jj_la1_init_3(){ + jj_la1_3 = new int[]{0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3,0x3,0x0,0x0,0x3b,0x0,0x0,0x0,0x3,0x0,0x0,0x0,0x23,0x23,0x0,0x0,0x0,0x3,0x0,0x3,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x38,0x30,0x0,0x0,0x38,0x3b,0x0,0x3b,0x0,0x0,0x0,0x0,0x0,0x0,0x3b,0x0,0x0,0x3b,0x3,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x3b,0x0,0x0,0x0,0x0,0x0,0x0,0x3b,0x0,0x0,0x0,0x0,0x3,0x3,0x3,0x3,0x0,0x0,0x0,0x2,0x3b,0x0,0x0,0x0,0x0,0x0,0x3b,}; } + final private JJCalls[] jj_2_rtns = new JJCalls[13]; private boolean jj_rescan = false; private int jj_gc = 0; /** Constructor with InputStream. */ - public ADQLParser(java.io.InputStream stream) { + public ADQLParser(java.io.InputStream stream){ this(stream, (String)null); } + /** Constructor with InputStream and supplied encoding */ - public ADQLParser(java.io.InputStream stream, String encoding) { - try { jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); } + public ADQLParser(java.io.InputStream stream, String encoding){ + try{ + jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1); + }catch(java.io.UnsupportedEncodingException e){ + throw new RuntimeException(e); + } token_source = new ADQLParserTokenManager(jj_input_stream); token = new Token(); jj_ntk = -1; jj_gen = 0; - for (int i = 0; i < 98; i++) jj_la1[i] = -1; - for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); + for(int i = 0; i < 98; i++) + jj_la1[i] = -1; + for(int i = 0; i < jj_2_rtns.length; i++) + jj_2_rtns[i] = new JJCalls(); } /** Reinitialise. */ - public void ReInit(java.io.InputStream stream) { + public void ReInit(java.io.InputStream stream){ ReInit(stream, null); } + /** Reinitialise. */ - public void ReInit(java.io.InputStream stream, String encoding) { - try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); } + public void ReInit(java.io.InputStream stream, String encoding){ + try{ + jj_input_stream.ReInit(stream, encoding, 1, 1); + }catch(java.io.UnsupportedEncodingException e){ + throw new RuntimeException(e); + } token_source.ReInit(jj_input_stream); token = new Token(); jj_ntk = -1; jj_gen = 0; - for (int i = 0; i < 98; i++) jj_la1[i] = -1; - for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); + for(int i = 0; i < 98; i++) + jj_la1[i] = -1; + for(int i = 0; i < jj_2_rtns.length; i++) + jj_2_rtns[i] = new JJCalls(); } /** Constructor. */ - public ADQLParser(java.io.Reader stream) { + public ADQLParser(java.io.Reader stream){ jj_input_stream = new SimpleCharStream(stream, 1, 1); token_source = new ADQLParserTokenManager(jj_input_stream); token = new Token(); jj_ntk = -1; jj_gen = 0; - for (int i = 0; i < 98; i++) jj_la1[i] = -1; - for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); + for(int i = 0; i < 98; i++) + jj_la1[i] = -1; + for(int i = 0; i < jj_2_rtns.length; i++) + jj_2_rtns[i] = new JJCalls(); } /** Reinitialise. */ - public void ReInit(java.io.Reader stream) { + public void ReInit(java.io.Reader stream){ jj_input_stream.ReInit(stream, 1, 1); token_source.ReInit(jj_input_stream); token = new Token(); jj_ntk = -1; jj_gen = 0; - for (int i = 0; i < 98; i++) jj_la1[i] = -1; - for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); + for(int i = 0; i < 98; i++) + jj_la1[i] = -1; + for(int i = 0; i < jj_2_rtns.length; i++) + jj_2_rtns[i] = new JJCalls(); } /** Constructor with generated Token Manager. */ - public ADQLParser(ADQLParserTokenManager tm) { + public ADQLParser(ADQLParserTokenManager tm){ token_source = tm; token = new Token(); jj_ntk = -1; jj_gen = 0; - for (int i = 0; i < 98; i++) jj_la1[i] = -1; - for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); + for(int i = 0; i < 98; i++) + jj_la1[i] = -1; + for(int i = 0; i < jj_2_rtns.length; i++) + jj_2_rtns[i] = new JJCalls(); } /** Reinitialise. */ - public void ReInit(ADQLParserTokenManager tm) { + public void ReInit(ADQLParserTokenManager tm){ token_source = tm; token = new Token(); jj_ntk = -1; jj_gen = 0; - for (int i = 0; i < 98; i++) jj_la1[i] = -1; - for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); + for(int i = 0; i < 98; i++) + jj_la1[i] = -1; + for(int i = 0; i < jj_2_rtns.length; i++) + jj_2_rtns[i] = new JJCalls(); } - private Token jj_consume_token(int kind) throws ParseException { + private Token jj_consume_token(int kind) throws ParseException{ Token oldToken; - if ((oldToken = token).next != null) token = token.next; - else token = token.next = token_source.getNextToken(); + if ((oldToken = token).next != null) + token = token.next; + else + token = token.next = token_source.getNextToken(); jj_ntk = -1; - if (token.kind == kind) { + if (token.kind == kind){ jj_gen++; - if (++jj_gc > 100) { + if (++jj_gc > 100){ jj_gc = 0; - for (int i = 0; i < jj_2_rtns.length; i++) { + for(int i = 0; i < jj_2_rtns.length; i++){ JJCalls c = jj_2_rtns[i]; - while (c != null) { - if (c.gen < jj_gen) c.first = null; + while(c != null){ + if (c.gen < jj_gen) + c.first = null; c = c.next; } } @@ -4975,34 +5876,44 @@ public class ADQLParser implements ADQLParserConstants { throw generateParseException(); } - static private final class LookaheadSuccess extends java.lang.Error { } + static private final class LookaheadSuccess extends java.lang.Error {} + final private LookaheadSuccess jj_ls = new LookaheadSuccess(); - private boolean jj_scan_token(int kind) { - if (jj_scanpos == jj_lastpos) { + + private boolean jj_scan_token(int kind){ + if (jj_scanpos == jj_lastpos){ jj_la--; - if (jj_scanpos.next == null) { + if (jj_scanpos.next == null){ jj_lastpos = jj_scanpos = jj_scanpos.next = token_source.getNextToken(); - } else { + }else{ jj_lastpos = jj_scanpos = jj_scanpos.next; } - } else { + }else{ jj_scanpos = jj_scanpos.next; } - if (jj_rescan) { - int i = 0; Token tok = token; - while (tok != null && tok != jj_scanpos) { i++; tok = tok.next; } - if (tok != null) jj_add_error_token(kind, i); + if (jj_rescan){ + int i = 0; + Token tok = token; + while(tok != null && tok != jj_scanpos){ + i++; + tok = tok.next; + } + if (tok != null) + jj_add_error_token(kind, i); } - if (jj_scanpos.kind != kind) return true; - if (jj_la == 0 && jj_scanpos == jj_lastpos) throw jj_ls; + if (jj_scanpos.kind != kind) + return true; + if (jj_la == 0 && jj_scanpos == jj_lastpos) + throw jj_ls; return false; } - /** Get the next Token. */ - final public Token getNextToken() { - if (token.next != null) token = token.next; - else token = token.next = token_source.getNextToken(); + final public Token getNextToken(){ + if (token.next != null) + token = token.next; + else + token = token.next = token_source.getNextToken(); jj_ntk = -1; jj_gen++; trace_token(token, " (in getNextToken)"); @@ -5010,18 +5921,20 @@ public class ADQLParser implements ADQLParserConstants { } /** Get the specific Token. */ - final public Token getToken(int index) { + final public Token getToken(int index){ Token t = token; - for (int i = 0; i < index; i++) { - if (t.next != null) t = t.next; - else t = t.next = token_source.getNextToken(); + for(int i = 0; i < index; i++){ + if (t.next != null) + t = t.next; + else + t = t.next = token_source.getNextToken(); } return t; } - private int jj_ntk() { - if ((jj_nt=token.next) == null) - return (jj_ntk = (token.next=token_source.getNextToken()).kind); + private int jj_ntk(){ + if ((jj_nt = token.next) == null) + return (jj_ntk = (token.next = token_source.getNextToken()).kind); else return (jj_ntk = jj_nt.kind); } @@ -5032,20 +5945,21 @@ public class ADQLParser implements ADQLParserConstants { private int[] jj_lasttokens = new int[100]; private int jj_endpos; - private void jj_add_error_token(int kind, int pos) { - if (pos >= 100) return; - if (pos == jj_endpos + 1) { + private void jj_add_error_token(int kind, int pos){ + if (pos >= 100) + return; + if (pos == jj_endpos + 1){ jj_lasttokens[jj_endpos++] = kind; - } else if (jj_endpos != 0) { + }else if (jj_endpos != 0){ jj_expentry = new int[jj_endpos]; - for (int i = 0; i < jj_endpos; i++) { + for(int i = 0; i < jj_endpos; i++){ jj_expentry[i] = jj_lasttokens[i]; } - jj_entries_loop: for (java.util.Iterator<?> it = jj_expentries.iterator(); it.hasNext();) { + jj_entries_loop: for(java.util.Iterator<?> it = jj_expentries.iterator(); it.hasNext();){ int[] oldentry = (int[])(it.next()); - if (oldentry.length == jj_expentry.length) { - for (int i = 0; i < jj_expentry.length; i++) { - if (oldentry[i] != jj_expentry[i]) { + if (oldentry.length == jj_expentry.length){ + for(int i = 0; i < jj_expentry.length; i++){ + if (oldentry[i] != jj_expentry[i]){ continue jj_entries_loop; } } @@ -5053,38 +5967,39 @@ public class ADQLParser implements ADQLParserConstants { break jj_entries_loop; } } - if (pos != 0) jj_lasttokens[(jj_endpos = pos) - 1] = kind; + if (pos != 0) + jj_lasttokens[(jj_endpos = pos) - 1] = kind; } } /** Generate ParseException. */ - public ParseException generateParseException() { + public ParseException generateParseException(){ jj_expentries.clear(); boolean[] la1tokens = new boolean[103]; - if (jj_kind >= 0) { + if (jj_kind >= 0){ la1tokens[jj_kind] = true; jj_kind = -1; } - for (int i = 0; i < 98; i++) { - if (jj_la1[i] == jj_gen) { - for (int j = 0; j < 32; j++) { - if ((jj_la1_0[i] & (1<<j)) != 0) { + for(int i = 0; i < 98; i++){ + if (jj_la1[i] == jj_gen){ + for(int j = 0; j < 32; j++){ + if ((jj_la1_0[i] & (1 << j)) != 0){ la1tokens[j] = true; } - if ((jj_la1_1[i] & (1<<j)) != 0) { - la1tokens[32+j] = true; + if ((jj_la1_1[i] & (1 << j)) != 0){ + la1tokens[32 + j] = true; } - if ((jj_la1_2[i] & (1<<j)) != 0) { - la1tokens[64+j] = true; + if ((jj_la1_2[i] & (1 << j)) != 0){ + la1tokens[64 + j] = true; } - if ((jj_la1_3[i] & (1<<j)) != 0) { - la1tokens[96+j] = true; + if ((jj_la1_3[i] & (1 << j)) != 0){ + la1tokens[96 + j] = true; } } } } - for (int i = 0; i < 103; i++) { - if (la1tokens[i]) { + for(int i = 0; i < 103; i++){ + if (la1tokens[i]){ jj_expentry = new int[1]; jj_expentry[0] = i; jj_expentries.add(jj_expentry); @@ -5094,7 +6009,7 @@ public class ADQLParser implements ADQLParserConstants { jj_rescan_token(); jj_add_error_token(0, 0); int[][] exptokseq = new int[jj_expentries.size()][]; - for (int i = 0; i < jj_expentries.size(); i++) { + for(int i = 0; i < jj_expentries.size(); i++){ exptokseq[i] = jj_expentries.get(i); } return new ParseException(token, exptokseq, tokenImage); @@ -5104,91 +6019,131 @@ public class ADQLParser implements ADQLParserConstants { private boolean trace_enabled = true; /** Enable tracing. */ - final public void enable_tracing() { + final public void enable_tracing(){ trace_enabled = true; } /** Disable tracing. */ - final public void disable_tracing() { + final public void disable_tracing(){ trace_enabled = false; } - private void trace_call(String s) { - if (trace_enabled) { - for (int i = 0; i < trace_indent; i++) { System.out.print(" "); } + private void trace_call(String s){ + if (trace_enabled){ + for(int i = 0; i < trace_indent; i++){ + System.out.print(" "); + } System.out.println("Call: " + s); } trace_indent = trace_indent + 2; } - private void trace_return(String s) { + private void trace_return(String s){ trace_indent = trace_indent - 2; - if (trace_enabled) { - for (int i = 0; i < trace_indent; i++) { System.out.print(" "); } + if (trace_enabled){ + for(int i = 0; i < trace_indent; i++){ + System.out.print(" "); + } System.out.println("Return: " + s); } } - private void trace_token(Token t, String where) { - if (trace_enabled) { - for (int i = 0; i < trace_indent; i++) { System.out.print(" "); } + private void trace_token(Token t, String where){ + if (trace_enabled){ + for(int i = 0; i < trace_indent; i++){ + System.out.print(" "); + } System.out.print("Consumed token: <" + tokenImage[t.kind]); - if (t.kind != 0 && !tokenImage[t.kind].equals("\"" + t.image + "\"")) { + if (t.kind != 0 && !tokenImage[t.kind].equals("\"" + t.image + "\"")){ System.out.print(": \"" + t.image + "\""); } System.out.println(" at line " + t.beginLine + " column " + t.beginColumn + ">" + where); } } - private void trace_scan(Token t1, int t2) { - if (trace_enabled) { - for (int i = 0; i < trace_indent; i++) { System.out.print(" "); } + private void trace_scan(Token t1, int t2){ + if (trace_enabled){ + for(int i = 0; i < trace_indent; i++){ + System.out.print(" "); + } System.out.print("Visited token: <" + tokenImage[t1.kind]); - if (t1.kind != 0 && !tokenImage[t1.kind].equals("\"" + t1.image + "\"")) { + if (t1.kind != 0 && !tokenImage[t1.kind].equals("\"" + t1.image + "\"")){ System.out.print(": \"" + t1.image + "\""); } System.out.println(" at line " + t1.beginLine + " column " + t1.beginColumn + ">; Expected token: <" + tokenImage[t2] + ">"); } } - private void jj_rescan_token() { + private void jj_rescan_token(){ jj_rescan = true; - for (int i = 0; i < 13; i++) { - try { + for(int i = 0; i < 13; i++){ + try{ JJCalls p = jj_2_rtns[i]; - do { - if (p.gen > jj_gen) { - jj_la = p.arg; jj_lastpos = jj_scanpos = p.first; - switch (i) { - case 0: jj_3_1(); break; - case 1: jj_3_2(); break; - case 2: jj_3_3(); break; - case 3: jj_3_4(); break; - case 4: jj_3_5(); break; - case 5: jj_3_6(); break; - case 6: jj_3_7(); break; - case 7: jj_3_8(); break; - case 8: jj_3_9(); break; - case 9: jj_3_10(); break; - case 10: jj_3_11(); break; - case 11: jj_3_12(); break; - case 12: jj_3_13(); break; + do{ + if (p.gen > jj_gen){ + jj_la = p.arg; + jj_lastpos = jj_scanpos = p.first; + switch(i){ + case 0: + jj_3_1(); + break; + case 1: + jj_3_2(); + break; + case 2: + jj_3_3(); + break; + case 3: + jj_3_4(); + break; + case 4: + jj_3_5(); + break; + case 5: + jj_3_6(); + break; + case 6: + jj_3_7(); + break; + case 7: + jj_3_8(); + break; + case 8: + jj_3_9(); + break; + case 9: + jj_3_10(); + break; + case 10: + jj_3_11(); + break; + case 11: + jj_3_12(); + break; + case 12: + jj_3_13(); + break; } } p = p.next; - } while (p != null); - } catch(LookaheadSuccess ls) { } + }while(p != null); + }catch(LookaheadSuccess ls){} } jj_rescan = false; } - private void jj_save(int index, int xla) { + private void jj_save(int index, int xla){ JJCalls p = jj_2_rtns[index]; - while (p.gen > jj_gen) { - if (p.next == null) { p = p.next = new JJCalls(); break; } + while(p.gen > jj_gen){ + if (p.next == null){ + p = p.next = new JJCalls(); + break; + } p = p.next; } - p.gen = jj_gen + xla - jj_la; p.first = token; p.arg = xla; + p.gen = jj_gen + xla - jj_la; + p.first = token; + p.arg = xla; } static final class JJCalls { diff --git a/src/adql/parser/ADQLParserConstants.java b/src/adql/parser/ADQLParserConstants.java index 15c3b80f33d2ae94a49c9b5bc78789707a6da169..ee79a43e5f66c7bc1c89d64f912ea2295213873d 100644 --- a/src/adql/parser/ADQLParserConstants.java +++ b/src/adql/parser/ADQLParserConstants.java @@ -1,7 +1,6 @@ /* Generated By:JavaCC: Do not edit this line. ADQLParserConstants.java */ package adql.parser; - /** * Token literal values and constants. * Generated by org.javacc.parser.OtherFilesGen#start() @@ -9,311 +8,207 @@ package adql.parser; @SuppressWarnings("all") public interface ADQLParserConstants { - /** End of File. */ - int EOF = 0; - /** RegularExpression Id. */ - int LEFT_PAR = 2; - /** RegularExpression Id. */ - int RIGHT_PAR = 3; - /** RegularExpression Id. */ - int DOT = 4; - /** RegularExpression Id. */ - int COMMA = 5; - /** RegularExpression Id. */ - int EOQ = 6; - /** RegularExpression Id. */ - int CONCAT = 7; - /** RegularExpression Id. */ - int PLUS = 8; - /** RegularExpression Id. */ - int MINUS = 9; - /** RegularExpression Id. */ - int ASTERISK = 10; - /** RegularExpression Id. */ - int DIVIDE = 11; - /** RegularExpression Id. */ - int EQUAL = 12; - /** RegularExpression Id. */ - int NOT_EQUAL = 13; - /** RegularExpression Id. */ - int LESS_THAN = 14; - /** RegularExpression Id. */ - int LESS_EQUAL_THAN = 15; - /** RegularExpression Id. */ - int GREATER_THAN = 16; - /** RegularExpression Id. */ - int GREATER_EQUAL_THAN = 17; - /** RegularExpression Id. */ - int SELECT = 18; - /** RegularExpression Id. */ - int QUANTIFIER = 19; - /** RegularExpression Id. */ - int TOP = 20; - /** RegularExpression Id. */ - int FROM = 21; - /** RegularExpression Id. */ - int AS = 22; - /** RegularExpression Id. */ - int NATURAL = 23; - /** RegularExpression Id. */ - int INNER = 24; - /** RegularExpression Id. */ - int OUTER = 25; - /** RegularExpression Id. */ - int RIGHT = 26; - /** RegularExpression Id. */ - int LEFT = 27; - /** RegularExpression Id. */ - int FULL = 28; - /** RegularExpression Id. */ - int JOIN = 29; - /** RegularExpression Id. */ - int ON = 30; - /** RegularExpression Id. */ - int USING = 31; - /** RegularExpression Id. */ - int WHERE = 32; - /** RegularExpression Id. */ - int AND = 33; - /** RegularExpression Id. */ - int OR = 34; - /** RegularExpression Id. */ - int NOT = 35; - /** RegularExpression Id. */ - int IS = 36; - /** RegularExpression Id. */ - int NULL = 37; - /** RegularExpression Id. */ - int BETWEEN = 38; - /** RegularExpression Id. */ - int LIKE = 39; - /** RegularExpression Id. */ - int IN = 40; - /** RegularExpression Id. */ - int EXISTS = 41; - /** RegularExpression Id. */ - int GROUP_BY = 42; - /** RegularExpression Id. */ - int HAVING = 43; - /** RegularExpression Id. */ - int ORDER_BY = 44; - /** RegularExpression Id. */ - int ASC = 45; - /** RegularExpression Id. */ - int DESC = 46; - /** RegularExpression Id. */ - int AVG = 47; - /** RegularExpression Id. */ - int MAX = 48; - /** RegularExpression Id. */ - int MIN = 49; - /** RegularExpression Id. */ - int SUM = 50; - /** RegularExpression Id. */ - int COUNT = 51; - /** RegularExpression Id. */ - int BOX = 52; - /** RegularExpression Id. */ - int CENTROID = 53; - /** RegularExpression Id. */ - int CIRCLE = 54; - /** RegularExpression Id. */ - int POINT = 55; - /** RegularExpression Id. */ - int POLYGON = 56; - /** RegularExpression Id. */ - int REGION = 57; - /** RegularExpression Id. */ - int CONTAINS = 58; - /** RegularExpression Id. */ - int INTERSECTS = 59; - /** RegularExpression Id. */ - int AREA = 60; - /** RegularExpression Id. */ - int COORD1 = 61; - /** RegularExpression Id. */ - int COORD2 = 62; - /** RegularExpression Id. */ - int COORDSYS = 63; - /** RegularExpression Id. */ - int DISTANCE = 64; - /** RegularExpression Id. */ - int ABS = 65; - /** RegularExpression Id. */ - int CEILING = 66; - /** RegularExpression Id. */ - int DEGREES = 67; - /** RegularExpression Id. */ - int EXP = 68; - /** RegularExpression Id. */ - int FLOOR = 69; - /** RegularExpression Id. */ - int LOG = 70; - /** RegularExpression Id. */ - int LOG10 = 71; - /** RegularExpression Id. */ - int MOD = 72; - /** RegularExpression Id. */ - int PI = 73; - /** RegularExpression Id. */ - int POWER = 74; - /** RegularExpression Id. */ - int RADIANS = 75; - /** RegularExpression Id. */ - int RAND = 76; - /** RegularExpression Id. */ - int ROUND = 77; - /** RegularExpression Id. */ - int SQRT = 78; - /** RegularExpression Id. */ - int TRUNCATE = 79; - /** RegularExpression Id. */ - int ACOS = 80; - /** RegularExpression Id. */ - int ASIN = 81; - /** RegularExpression Id. */ - int ATAN = 82; - /** RegularExpression Id. */ - int ATAN2 = 83; - /** RegularExpression Id. */ - int COS = 84; - /** RegularExpression Id. */ - int COT = 85; - /** RegularExpression Id. */ - int SIN = 86; - /** RegularExpression Id. */ - int TAN = 87; - /** RegularExpression Id. */ - int STRING_LITERAL = 93; - /** RegularExpression Id. */ - int DELIMITED_IDENTIFIER = 96; - /** RegularExpression Id. */ - int REGULAR_IDENTIFIER = 97; - /** RegularExpression Id. */ - int Letter = 98; - /** RegularExpression Id. */ - int SCIENTIFIC_NUMBER = 99; - /** RegularExpression Id. */ - int UNSIGNED_FLOAT = 100; - /** RegularExpression Id. */ - int UNSIGNED_INTEGER = 101; - /** RegularExpression Id. */ - int DIGIT = 102; + /** End of File. */ + int EOF = 0; + /** RegularExpression Id. */ + int LEFT_PAR = 2; + /** RegularExpression Id. */ + int RIGHT_PAR = 3; + /** RegularExpression Id. */ + int DOT = 4; + /** RegularExpression Id. */ + int COMMA = 5; + /** RegularExpression Id. */ + int EOQ = 6; + /** RegularExpression Id. */ + int CONCAT = 7; + /** RegularExpression Id. */ + int PLUS = 8; + /** RegularExpression Id. */ + int MINUS = 9; + /** RegularExpression Id. */ + int ASTERISK = 10; + /** RegularExpression Id. */ + int DIVIDE = 11; + /** RegularExpression Id. */ + int EQUAL = 12; + /** RegularExpression Id. */ + int NOT_EQUAL = 13; + /** RegularExpression Id. */ + int LESS_THAN = 14; + /** RegularExpression Id. */ + int LESS_EQUAL_THAN = 15; + /** RegularExpression Id. */ + int GREATER_THAN = 16; + /** RegularExpression Id. */ + int GREATER_EQUAL_THAN = 17; + /** RegularExpression Id. */ + int SELECT = 18; + /** RegularExpression Id. */ + int QUANTIFIER = 19; + /** RegularExpression Id. */ + int TOP = 20; + /** RegularExpression Id. */ + int FROM = 21; + /** RegularExpression Id. */ + int AS = 22; + /** RegularExpression Id. */ + int NATURAL = 23; + /** RegularExpression Id. */ + int INNER = 24; + /** RegularExpression Id. */ + int OUTER = 25; + /** RegularExpression Id. */ + int RIGHT = 26; + /** RegularExpression Id. */ + int LEFT = 27; + /** RegularExpression Id. */ + int FULL = 28; + /** RegularExpression Id. */ + int JOIN = 29; + /** RegularExpression Id. */ + int ON = 30; + /** RegularExpression Id. */ + int USING = 31; + /** RegularExpression Id. */ + int WHERE = 32; + /** RegularExpression Id. */ + int AND = 33; + /** RegularExpression Id. */ + int OR = 34; + /** RegularExpression Id. */ + int NOT = 35; + /** RegularExpression Id. */ + int IS = 36; + /** RegularExpression Id. */ + int NULL = 37; + /** RegularExpression Id. */ + int BETWEEN = 38; + /** RegularExpression Id. */ + int LIKE = 39; + /** RegularExpression Id. */ + int IN = 40; + /** RegularExpression Id. */ + int EXISTS = 41; + /** RegularExpression Id. */ + int GROUP_BY = 42; + /** RegularExpression Id. */ + int HAVING = 43; + /** RegularExpression Id. */ + int ORDER_BY = 44; + /** RegularExpression Id. */ + int ASC = 45; + /** RegularExpression Id. */ + int DESC = 46; + /** RegularExpression Id. */ + int AVG = 47; + /** RegularExpression Id. */ + int MAX = 48; + /** RegularExpression Id. */ + int MIN = 49; + /** RegularExpression Id. */ + int SUM = 50; + /** RegularExpression Id. */ + int COUNT = 51; + /** RegularExpression Id. */ + int BOX = 52; + /** RegularExpression Id. */ + int CENTROID = 53; + /** RegularExpression Id. */ + int CIRCLE = 54; + /** RegularExpression Id. */ + int POINT = 55; + /** RegularExpression Id. */ + int POLYGON = 56; + /** RegularExpression Id. */ + int REGION = 57; + /** RegularExpression Id. */ + int CONTAINS = 58; + /** RegularExpression Id. */ + int INTERSECTS = 59; + /** RegularExpression Id. */ + int AREA = 60; + /** RegularExpression Id. */ + int COORD1 = 61; + /** RegularExpression Id. */ + int COORD2 = 62; + /** RegularExpression Id. */ + int COORDSYS = 63; + /** RegularExpression Id. */ + int DISTANCE = 64; + /** RegularExpression Id. */ + int ABS = 65; + /** RegularExpression Id. */ + int CEILING = 66; + /** RegularExpression Id. */ + int DEGREES = 67; + /** RegularExpression Id. */ + int EXP = 68; + /** RegularExpression Id. */ + int FLOOR = 69; + /** RegularExpression Id. */ + int LOG = 70; + /** RegularExpression Id. */ + int LOG10 = 71; + /** RegularExpression Id. */ + int MOD = 72; + /** RegularExpression Id. */ + int PI = 73; + /** RegularExpression Id. */ + int POWER = 74; + /** RegularExpression Id. */ + int RADIANS = 75; + /** RegularExpression Id. */ + int RAND = 76; + /** RegularExpression Id. */ + int ROUND = 77; + /** RegularExpression Id. */ + int SQRT = 78; + /** RegularExpression Id. */ + int TRUNCATE = 79; + /** RegularExpression Id. */ + int ACOS = 80; + /** RegularExpression Id. */ + int ASIN = 81; + /** RegularExpression Id. */ + int ATAN = 82; + /** RegularExpression Id. */ + int ATAN2 = 83; + /** RegularExpression Id. */ + int COS = 84; + /** RegularExpression Id. */ + int COT = 85; + /** RegularExpression Id. */ + int SIN = 86; + /** RegularExpression Id. */ + int TAN = 87; + /** RegularExpression Id. */ + int STRING_LITERAL = 93; + /** RegularExpression Id. */ + int DELIMITED_IDENTIFIER = 96; + /** RegularExpression Id. */ + int REGULAR_IDENTIFIER = 97; + /** RegularExpression Id. */ + int Letter = 98; + /** RegularExpression Id. */ + int SCIENTIFIC_NUMBER = 99; + /** RegularExpression Id. */ + int UNSIGNED_FLOAT = 100; + /** RegularExpression Id. */ + int UNSIGNED_INTEGER = 101; + /** RegularExpression Id. */ + int DIGIT = 102; - /** Lexical state. */ - int DEFAULT = 0; - /** Lexical state. */ - int WithinComment = 1; - /** Lexical state. */ - int WithinString = 2; - /** Lexical state. */ - int WithinDelimitedId = 3; + /** Lexical state. */ + int DEFAULT = 0; + /** Lexical state. */ + int WithinComment = 1; + /** Lexical state. */ + int WithinString = 2; + /** Lexical state. */ + int WithinDelimitedId = 3; - /** Literal token values. */ - String[] tokenImage = { - "<EOF>", - "<token of kind 1>", - "\"(\"", - "\")\"", - "\".\"", - "\",\"", - "\";\"", - "\"||\"", - "\"+\"", - "\"-\"", - "\"*\"", - "\"/\"", - "\"=\"", - "<NOT_EQUAL>", - "\"<\"", - "\"<=\"", - "\">\"", - "\">=\"", - "\"SELECT\"", - "<QUANTIFIER>", - "\"TOP\"", - "\"FROM\"", - "\"AS\"", - "\"NATURAL\"", - "\"INNER\"", - "\"OUTER\"", - "\"RIGHT\"", - "\"LEFT\"", - "\"FULL\"", - "\"JOIN\"", - "\"ON\"", - "\"USING\"", - "\"WHERE\"", - "\"AND\"", - "\"OR\"", - "\"NOT\"", - "\"IS\"", - "\"NULL\"", - "\"BETWEEN\"", - "\"LIKE\"", - "\"IN\"", - "\"EXISTS\"", - "\"GROUP BY\"", - "\"HAVING\"", - "\"ORDER BY\"", - "\"ASC\"", - "\"DESC\"", - "\"AVG\"", - "\"MAX\"", - "\"MIN\"", - "\"SUM\"", - "\"COUNT\"", - "\"BOX\"", - "\"CENTROID\"", - "\"CIRCLE\"", - "\"POINT\"", - "\"POLYGON\"", - "\"REGION\"", - "\"CONTAINS\"", - "\"INTERSECTS\"", - "\"AREA\"", - "\"COORD1\"", - "\"COORD2\"", - "\"COORDSYS\"", - "\"DISTANCE\"", - "\"ABS\"", - "\"CEILING\"", - "\"DEGREES\"", - "\"EXP\"", - "\"FLOOR\"", - "\"LOG\"", - "\"LOG10\"", - "\"MOD\"", - "\"PI\"", - "\"POWER\"", - "\"RADIANS\"", - "\"RAND\"", - "\"ROUND\"", - "\"SQRT\"", - "\"TRUNCATE\"", - "\"ACOS\"", - "\"ASIN\"", - "\"ATAN\"", - "\"ATAN2\"", - "\"COS\"", - "\"COT\"", - "\"SIN\"", - "\"TAN\"", - "<token of kind 88>", - "<token of kind 89>", - "<token of kind 90>", - "\"\\\'\"", - "<token of kind 92>", - "\"\\\'\"", - "\"\\\"\"", - "<token of kind 95>", - "\"\\\"\"", - "<REGULAR_IDENTIFIER>", - "<Letter>", - "<SCIENTIFIC_NUMBER>", - "<UNSIGNED_FLOAT>", - "<UNSIGNED_INTEGER>", - "<DIGIT>", - }; + /** Literal token values. */ + String[] tokenImage = {"<EOF>","<token of kind 1>","\"(\"","\")\"","\".\"","\",\"","\";\"","\"||\"","\"+\"","\"-\"","\"*\"","\"/\"","\"=\"","<NOT_EQUAL>","\"<\"","\"<=\"","\">\"","\">=\"","\"SELECT\"","<QUANTIFIER>","\"TOP\"","\"FROM\"","\"AS\"","\"NATURAL\"","\"INNER\"","\"OUTER\"","\"RIGHT\"","\"LEFT\"","\"FULL\"","\"JOIN\"","\"ON\"","\"USING\"","\"WHERE\"","\"AND\"","\"OR\"","\"NOT\"","\"IS\"","\"NULL\"","\"BETWEEN\"","\"LIKE\"","\"IN\"","\"EXISTS\"","\"GROUP BY\"","\"HAVING\"","\"ORDER BY\"","\"ASC\"","\"DESC\"","\"AVG\"","\"MAX\"","\"MIN\"","\"SUM\"","\"COUNT\"","\"BOX\"","\"CENTROID\"","\"CIRCLE\"","\"POINT\"","\"POLYGON\"","\"REGION\"","\"CONTAINS\"","\"INTERSECTS\"","\"AREA\"","\"COORD1\"","\"COORD2\"","\"COORDSYS\"","\"DISTANCE\"","\"ABS\"","\"CEILING\"","\"DEGREES\"","\"EXP\"","\"FLOOR\"","\"LOG\"","\"LOG10\"","\"MOD\"","\"PI\"","\"POWER\"","\"RADIANS\"","\"RAND\"","\"ROUND\"","\"SQRT\"","\"TRUNCATE\"","\"ACOS\"","\"ASIN\"","\"ATAN\"","\"ATAN2\"","\"COS\"","\"COT\"","\"SIN\"","\"TAN\"","<token of kind 88>","<token of kind 89>","<token of kind 90>","\"\\\'\"","<token of kind 92>","\"\\\'\"","\"\\\"\"","<token of kind 95>","\"\\\"\"","<REGULAR_IDENTIFIER>","<Letter>","<SCIENTIFIC_NUMBER>","<UNSIGNED_FLOAT>","<UNSIGNED_INTEGER>","<DIGIT>",}; } diff --git a/src/adql/parser/ADQLParserTokenManager.java b/src/adql/parser/ADQLParserTokenManager.java index 656a51c087c77f70e3497a6193385c9cf7f8b8ab..b6efe77a6f4daba6f9ca60ea4e842673a7d038e1 100644 --- a/src/adql/parser/ADQLParserTokenManager.java +++ b/src/adql/parser/ADQLParserTokenManager.java @@ -1,5 +1,6 @@ /* Generated By:JavaCC: Do not edit this line. ADQLParserTokenManager.java */ package adql.parser; + import java.util.Stack; import java.util.Vector; import java.util.ArrayList; @@ -21,1842 +22,1716 @@ import adql.translator.TranslationException; /** Token Manager. */ @SuppressWarnings("all") -public class ADQLParserTokenManager implements ADQLParserConstants -{ +public class ADQLParserTokenManager implements ADQLParserConstants { - /** Debug output. */ - public java.io.PrintStream debugStream = System.out; - /** Set debug output. */ - public void setDebugStream(java.io.PrintStream ds) { debugStream = ds; } -private final int jjStopStringLiteralDfa_3(int pos, long active0, long active1) -{ - switch (pos) - { - default : - return -1; - } -} -private final int jjStartNfa_3(int pos, long active0, long active1) -{ - return jjMoveNfa_3(jjStopStringLiteralDfa_3(pos, active0, active1), pos + 1); -} -private int jjStopAtPos(int pos, int kind) -{ - jjmatchedKind = kind; - jjmatchedPos = pos; - return pos + 1; -} -private int jjMoveStringLiteralDfa0_3() -{ - switch(curChar) - { - case 34: - return jjStartNfaWithStates_3(0, 96, 1); - default : - return jjMoveNfa_3(0, 0); - } -} -private int jjStartNfaWithStates_3(int pos, int kind, int state) -{ - jjmatchedKind = kind; - jjmatchedPos = pos; - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { return pos + 1; } - return jjMoveNfa_3(state, pos + 1); -} -static final long[] jjbitVec0 = { - 0x0L, 0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL -}; -private int jjMoveNfa_3(int startState, int curPos) -{ - int startsAt = 0; - jjnewStateCnt = 3; - int i = 1; - jjstateSet[0] = startState; - int kind = 0x7fffffff; - for (;;) - { - if (++jjround == 0x7fffffff) - ReInitRounds(); - if (curChar < 64) - { - long l = 1L << curChar; - do - { - switch(jjstateSet[--i]) - { - case 0: - if ((0xfffffffbffffffffL & l) != 0L) - { - if (kind > 95) - kind = 95; - } - else if (curChar == 34) - jjstateSet[jjnewStateCnt++] = 1; - break; - case 1: - if (curChar == 34 && kind > 95) - kind = 95; - break; - case 2: - if (curChar == 34) - jjstateSet[jjnewStateCnt++] = 1; - break; - default : break; - } - } while(i != startsAt); - } - else if (curChar < 128) - { - long l = 1L << (curChar & 077); - do - { - switch(jjstateSet[--i]) - { - case 0: - kind = 95; - break; - default : break; - } - } while(i != startsAt); - } - else - { - int i2 = (curChar & 0xff) >> 6; - long l2 = 1L << (curChar & 077); - do - { - switch(jjstateSet[--i]) - { - case 0: - if ((jjbitVec0[i2] & l2) != 0L && kind > 95) - kind = 95; - break; - default : break; - } - } while(i != startsAt); - } - if (kind != 0x7fffffff) - { - jjmatchedKind = kind; - jjmatchedPos = curPos; - kind = 0x7fffffff; - } - ++curPos; - if ((i = jjnewStateCnt) == (startsAt = 3 - (jjnewStateCnt = startsAt))) - return curPos; - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { return curPos; } - } -} -private final int jjStopStringLiteralDfa_0(int pos, long active0, long active1) -{ - switch (pos) - { - case 0: - if ((active0 & 0xefff1ffdffb40000L) != 0L || (active1 & 0xf0fff4L) != 0L) - { - jjmatchedKind = 97; - return 37; - } - if ((active0 & 0x1000a00200400000L) != 0L || (active1 & 0xf0002L) != 0L) - { - jjmatchedKind = 97; - return 16; - } - if ((active0 & 0x10L) != 0L) - return 38; - if ((active0 & 0x400000000000L) != 0L || (active1 & 0x9L) != 0L) - { - jjmatchedKind = 97; - return 13; - } - if ((active0 & 0xc000L) != 0L) - return 3; - if ((active0 & 0x200L) != 0L) - return 19; - return -1; - case 1: - if ((active0 & 0xf7ffceebbeb40000L) != 0L || (active1 & 0xfdfdfeL) != 0L) - { - if (jjmatchedPos != 1) - { - jjmatchedKind = 97; - jjmatchedPos = 1; - } - return 37; - } - if ((active0 & 0x800311441400000L) != 0L || (active1 & 0x20200L) != 0L) - return 37; - if ((active1 & 0x1L) != 0L) - { - if (jjmatchedPos != 1) - { - jjmatchedKind = 97; - jjmatchedPos = 1; - } - return 12; - } - return -1; - case 2: - if ((active1 & 0x1L) != 0L) - { - if (jjmatchedPos != 2) - { - jjmatchedKind = 97; - jjmatchedPos = 2; - } - return 11; - } - if ((active0 & 0x17a00a00100000L) != 0L || (active1 & 0xf001d2L) != 0L) - return 37; - if ((active0 & 0xffe85ee1bfa40000L) != 0L || (active1 & 0xffc2cL) != 0L) - { - if (jjmatchedPos != 2) - { - jjmatchedKind = 97; - jjmatchedPos = 2; - } - return 37; - } - return -1; - case 3: - if ((active0 & 0xefe81e4187840000L) != 0L || (active1 & 0xac2cL) != 0L) - { - if (jjmatchedPos != 3) - { - jjmatchedKind = 97; - jjmatchedPos = 3; - } - return 37; - } - if ((active0 & 0x100040a038200000L) != 0L || (active1 & 0xf5000L) != 0L) - return 37; - if ((active1 & 0x80L) != 0L) - { - if (jjmatchedPos != 3) - { - jjmatchedKind = 97; - jjmatchedPos = 3; - } - return 21; - } - if ((active1 & 0x1L) != 0L) - { - if (jjmatchedPos != 3) - { - jjmatchedKind = 97; - jjmatchedPos = 3; - } - return 10; - } - return -1; - case 4: - if ((active0 & 0xef601e4000840000L) != 0L || (active1 & 0x880dL) != 0L) - { - jjmatchedKind = 97; - jjmatchedPos = 4; - return 37; - } - if ((active0 & 0x88000187000000L) != 0L || (active1 & 0x2420L) != 0L) - return 37; - if ((active1 & 0x80080L) != 0L) - return 21; - return -1; - case 5: - if ((active0 & 0x2400a0000040000L) != 0L) - return 37; - if ((active0 & 0x6000000000000000L) != 0L) - return 21; - if ((active0 & 0x8d20004000800000L) != 0L || (active1 & 0x880dL) != 0L) - { - jjmatchedKind = 97; - jjmatchedPos = 5; - return 37; - } - if ((active0 & 0x140000000000L) != 0L) - { - if (jjmatchedPos < 4) - { - jjmatchedKind = 97; - jjmatchedPos = 4; - } - return -1; - } - return -1; - case 6: - if ((active0 & 0x8c20000000000000L) != 0L || (active1 & 0x8001L) != 0L) - { - jjmatchedKind = 97; - jjmatchedPos = 6; - return 37; - } - if ((active0 & 0x100004000800000L) != 0L || (active1 & 0x80cL) != 0L) - return 37; - if ((active0 & 0x140000000000L) != 0L) - { - if (jjmatchedPos < 4) - { - jjmatchedKind = 97; - jjmatchedPos = 4; - } - return -1; - } - return -1; - case 7: - if ((active0 & 0x800000000000000L) != 0L) - { - jjmatchedKind = 97; - jjmatchedPos = 7; - return 37; - } - if ((active0 & 0x8420000000000000L) != 0L || (active1 & 0x8001L) != 0L) - return 37; - if ((active0 & 0x140000000000L) != 0L) - { - if (jjmatchedPos < 4) - { - jjmatchedKind = 97; - jjmatchedPos = 4; - } - return -1; - } - return -1; - case 8: - if ((active0 & 0x800000000000000L) != 0L) - { - jjmatchedKind = 97; - jjmatchedPos = 8; - return 37; - } - return -1; - default : - return -1; - } -} -private final int jjStartNfa_0(int pos, long active0, long active1) -{ - return jjMoveNfa_0(jjStopStringLiteralDfa_0(pos, active0, active1), pos + 1); -} -private int jjMoveStringLiteralDfa0_0() -{ - switch(curChar) - { - case 34: - return jjStopAtPos(0, 94); - case 39: - return jjStopAtPos(0, 91); - case 40: - return jjStopAtPos(0, 2); - case 41: - return jjStopAtPos(0, 3); - case 42: - return jjStopAtPos(0, 10); - case 43: - return jjStopAtPos(0, 8); - case 44: - return jjStopAtPos(0, 5); - case 45: - return jjStartNfaWithStates_0(0, 9, 19); - case 46: - return jjStartNfaWithStates_0(0, 4, 38); - case 47: - return jjStopAtPos(0, 11); - case 59: - return jjStopAtPos(0, 6); - case 60: - jjmatchedKind = 14; - return jjMoveStringLiteralDfa1_0(0x8000L, 0x0L); - case 61: - return jjStopAtPos(0, 12); - case 62: - jjmatchedKind = 16; - return jjMoveStringLiteralDfa1_0(0x20000L, 0x0L); - case 65: - case 97: - return jjMoveStringLiteralDfa1_0(0x1000a00200400000L, 0xf0002L); - case 66: - case 98: - return jjMoveStringLiteralDfa1_0(0x10004000000000L, 0x0L); - case 67: - case 99: - return jjMoveStringLiteralDfa1_0(0xe468000000000000L, 0x300004L); - case 68: - case 100: - return jjMoveStringLiteralDfa1_0(0x400000000000L, 0x9L); - case 69: - case 101: - return jjMoveStringLiteralDfa1_0(0x20000000000L, 0x10L); - case 70: - case 102: - return jjMoveStringLiteralDfa1_0(0x10200000L, 0x20L); - case 71: - case 103: - return jjMoveStringLiteralDfa1_0(0x40000000000L, 0x0L); - case 72: - case 104: - return jjMoveStringLiteralDfa1_0(0x80000000000L, 0x0L); - case 73: - case 105: - return jjMoveStringLiteralDfa1_0(0x800011001000000L, 0x0L); - case 74: - case 106: - return jjMoveStringLiteralDfa1_0(0x20000000L, 0x0L); - case 76: - case 108: - return jjMoveStringLiteralDfa1_0(0x8008000000L, 0xc0L); - case 77: - case 109: - return jjMoveStringLiteralDfa1_0(0x3000000000000L, 0x100L); - case 78: - case 110: - return jjMoveStringLiteralDfa1_0(0x2800800000L, 0x0L); - case 79: - case 111: - return jjMoveStringLiteralDfa1_0(0x100442000000L, 0x0L); - case 80: - case 112: - return jjMoveStringLiteralDfa1_0(0x180000000000000L, 0x600L); - case 82: - case 114: - return jjMoveStringLiteralDfa1_0(0x200000004000000L, 0x3800L); - case 83: - case 115: - return jjMoveStringLiteralDfa1_0(0x4000000040000L, 0x404000L); - case 84: - case 116: - return jjMoveStringLiteralDfa1_0(0x100000L, 0x808000L); - case 85: - case 117: - return jjMoveStringLiteralDfa1_0(0x80000000L, 0x0L); - case 87: - case 119: - return jjMoveStringLiteralDfa1_0(0x100000000L, 0x0L); - case 124: - return jjMoveStringLiteralDfa1_0(0x80L, 0x0L); - default : - return jjMoveNfa_0(0, 0); - } -} -private int jjMoveStringLiteralDfa1_0(long active0, long active1) -{ - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { - jjStopStringLiteralDfa_0(0, active0, active1); - return 1; - } - switch(curChar) - { - case 61: - if ((active0 & 0x8000L) != 0L) - return jjStopAtPos(1, 15); - else if ((active0 & 0x20000L) != 0L) - return jjStopAtPos(1, 17); - break; - case 65: - case 97: - return jjMoveStringLiteralDfa2_0(active0, 0x1080000800000L, active1, 0x801800L); - case 66: - case 98: - return jjMoveStringLiteralDfa2_0(active0, 0L, active1, 0x2L); - case 67: - case 99: - return jjMoveStringLiteralDfa2_0(active0, 0L, active1, 0x10000L); - case 69: - case 101: - return jjMoveStringLiteralDfa2_0(active0, 0x220404008040000L, active1, 0xcL); - case 72: - case 104: - return jjMoveStringLiteralDfa2_0(active0, 0x100000000L, active1, 0L); - case 73: - case 105: - if ((active1 & 0x200L) != 0L) - return jjStartNfaWithStates_0(1, 73, 37); - return jjMoveStringLiteralDfa2_0(active0, 0x42008004000000L, active1, 0x400001L); - case 76: - case 108: - return jjMoveStringLiteralDfa2_0(active0, 0L, active1, 0x20L); - case 78: - case 110: - if ((active0 & 0x40000000L) != 0L) - return jjStartNfaWithStates_0(1, 30, 37); - else if ((active0 & 0x10000000000L) != 0L) - { - jjmatchedKind = 40; - jjmatchedPos = 1; - } - return jjMoveStringLiteralDfa2_0(active0, 0x800000201000000L, active1, 0L); - case 79: - case 111: - return jjMoveStringLiteralDfa2_0(active0, 0xe598000820100000L, active1, 0x3025c0L); - case 81: - case 113: - return jjMoveStringLiteralDfa2_0(active0, 0L, active1, 0x4000L); - case 82: - case 114: - if ((active0 & 0x400000000L) != 0L) - { - jjmatchedKind = 34; - jjmatchedPos = 1; - } - return jjMoveStringLiteralDfa2_0(active0, 0x1000140000200000L, active1, 0x8000L); - case 83: - case 115: - if ((active0 & 0x400000L) != 0L) - { - jjmatchedKind = 22; - jjmatchedPos = 1; - } - else if ((active0 & 0x1000000000L) != 0L) - return jjStartNfaWithStates_0(1, 36, 37); - return jjMoveStringLiteralDfa2_0(active0, 0x200080000000L, active1, 0x20000L); - case 84: - case 116: - return jjMoveStringLiteralDfa2_0(active0, 0L, active1, 0xc0000L); - case 85: - case 117: - return jjMoveStringLiteralDfa2_0(active0, 0x4002012000000L, active1, 0L); - case 86: - case 118: - return jjMoveStringLiteralDfa2_0(active0, 0x800000000000L, active1, 0L); - case 88: - case 120: - return jjMoveStringLiteralDfa2_0(active0, 0x20000000000L, active1, 0x10L); - case 124: - if ((active0 & 0x80L) != 0L) - return jjStopAtPos(1, 7); - break; - default : - break; - } - return jjStartNfa_0(0, active0, active1); -} -private int jjMoveStringLiteralDfa2_0(long old0, long active0, long old1, long active1) -{ - if (((active0 &= old0) | (active1 &= old1)) == 0L) - return jjStartNfa_0(0, old0, old1); - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { - jjStopStringLiteralDfa_0(1, active0, active1); - return 2; - } - switch(curChar) - { - case 65: - case 97: - return jjMoveStringLiteralDfa3_0(active0, 0L, active1, 0xc0000L); - case 67: - case 99: - if ((active0 & 0x200000000000L) != 0L) - return jjStartNfaWithStates_0(2, 45, 37); - break; - case 68: - case 100: - if ((active0 & 0x200000000L) != 0L) - return jjStartNfaWithStates_0(2, 33, 37); - else if ((active1 & 0x100L) != 0L) - return jjStartNfaWithStates_0(2, 72, 37); - return jjMoveStringLiteralDfa3_0(active0, 0x100000000000L, active1, 0x800L); - case 69: - case 101: - return jjMoveStringLiteralDfa3_0(active0, 0x1000000100000000L, active1, 0L); - case 70: - case 102: - return jjMoveStringLiteralDfa3_0(active0, 0x8000000L, active1, 0L); - case 71: - case 103: - if ((active0 & 0x800000000000L) != 0L) - return jjStartNfaWithStates_0(2, 47, 37); - else if ((active1 & 0x40L) != 0L) - { - jjmatchedKind = 70; - jjmatchedPos = 2; - } - return jjMoveStringLiteralDfa3_0(active0, 0x200000004000000L, active1, 0x88L); - case 73: - case 105: - return jjMoveStringLiteralDfa3_0(active0, 0x800200a0000000L, active1, 0x20004L); - case 75: - case 107: - return jjMoveStringLiteralDfa3_0(active0, 0x8000000000L, active1, 0L); - case 76: - case 108: - return jjMoveStringLiteralDfa3_0(active0, 0x100002010040000L, active1, 0L); - case 77: - case 109: - if ((active0 & 0x4000000000000L) != 0L) - return jjStartNfaWithStates_0(2, 50, 37); - break; - case 78: - case 110: - if ((active0 & 0x2000000000000L) != 0L) - return jjStartNfaWithStates_0(2, 49, 37); - else if ((active1 & 0x400000L) != 0L) - return jjStartNfaWithStates_0(2, 86, 37); - else if ((active1 & 0x800000L) != 0L) - return jjStartNfaWithStates_0(2, 87, 37); - return jjMoveStringLiteralDfa3_0(active0, 0x420000001000000L, active1, 0x1000L); - case 79: - case 111: - return jjMoveStringLiteralDfa3_0(active0, 0xe000040000200000L, active1, 0x10020L); - case 80: - case 112: - if ((active0 & 0x100000L) != 0L) - return jjStartNfaWithStates_0(2, 20, 37); - else if ((active1 & 0x10L) != 0L) - return jjStartNfaWithStates_0(2, 68, 37); - break; - case 82: - case 114: - return jjMoveStringLiteralDfa3_0(active0, 0x40000000000000L, active1, 0x4000L); - case 83: - case 115: - if ((active1 & 0x2L) != 0L) - return jjStartNfaWithStates_0(2, 65, 37); - else if ((active1 & 0x100000L) != 0L) - return jjStartNfaWithStates_0(2, 84, 37); - return jjMoveStringLiteralDfa3_0(active0, 0x400000000000L, active1, 0x1L); - case 84: - case 116: - if ((active0 & 0x800000000L) != 0L) - return jjStartNfaWithStates_0(2, 35, 37); - else if ((active1 & 0x200000L) != 0L) - return jjStartNfaWithStates_0(2, 85, 37); - return jjMoveStringLiteralDfa3_0(active0, 0x800004002800000L, active1, 0L); - case 85: - case 117: - return jjMoveStringLiteralDfa3_0(active0, 0x8000000000000L, active1, 0xa000L); - case 86: - case 118: - return jjMoveStringLiteralDfa3_0(active0, 0x80000000000L, active1, 0L); - case 87: - case 119: - return jjMoveStringLiteralDfa3_0(active0, 0L, active1, 0x400L); - case 88: - case 120: - if ((active0 & 0x1000000000000L) != 0L) - return jjStartNfaWithStates_0(2, 48, 37); - else if ((active0 & 0x10000000000000L) != 0L) - return jjStartNfaWithStates_0(2, 52, 37); - break; - default : - break; - } - return jjStartNfa_0(1, active0, active1); -} -private int jjMoveStringLiteralDfa3_0(long old0, long active0, long old1, long active1) -{ - if (((active0 &= old0) | (active1 &= old1)) == 0L) - return jjStartNfa_0(1, old0, old1); - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { - jjStopStringLiteralDfa_0(2, active0, active1); - return 3; - } - switch(curChar) - { - case 49: - return jjMoveStringLiteralDfa4_0(active0, 0L, active1, 0x80L); - case 65: - case 97: - if ((active0 & 0x1000000000000000L) != 0L) - return jjStartNfaWithStates_0(3, 60, 37); - break; - case 67: - case 99: - if ((active0 & 0x400000000000L) != 0L) - return jjStartNfaWithStates_0(3, 46, 37); - return jjMoveStringLiteralDfa4_0(active0, 0x40000000000000L, active1, 0L); - case 68: - case 100: - if ((active1 & 0x1000L) != 0L) - return jjStartNfaWithStates_0(3, 76, 37); - break; - case 69: - case 101: - if ((active0 & 0x8000000000L) != 0L) - return jjStartNfaWithStates_0(3, 39, 37); - return jjMoveStringLiteralDfa4_0(active0, 0x800100003040000L, active1, 0x400L); - case 72: - case 104: - return jjMoveStringLiteralDfa4_0(active0, 0x4000000L, active1, 0L); - case 73: - case 105: - return jjMoveStringLiteralDfa4_0(active0, 0x200080000000000L, active1, 0x800L); - case 76: - case 108: - if ((active0 & 0x10000000L) != 0L) - return jjStartNfaWithStates_0(3, 28, 37); - else if ((active0 & 0x2000000000L) != 0L) - return jjStartNfaWithStates_0(3, 37, 37); - return jjMoveStringLiteralDfa4_0(active0, 0L, active1, 0x4L); - case 77: - case 109: - if ((active0 & 0x200000L) != 0L) - return jjStartNfaWithStates_0(3, 21, 37); - break; - case 78: - case 110: - if ((active0 & 0x20000000L) != 0L) - return jjStartNfaWithStates_0(3, 29, 37); - else if ((active1 & 0x20000L) != 0L) - return jjStartNfaWithStates_0(3, 81, 37); - else if ((active1 & 0x40000L) != 0L) - { - jjmatchedKind = 82; - jjmatchedPos = 3; - } - return jjMoveStringLiteralDfa4_0(active0, 0x88000080000000L, active1, 0x8a000L); - case 79: - case 111: - return jjMoveStringLiteralDfa4_0(active0, 0L, active1, 0x20L); - case 82: - case 114: - return jjMoveStringLiteralDfa4_0(active0, 0xe000000100000000L, active1, 0x8L); - case 83: - case 115: - if ((active1 & 0x10000L) != 0L) - return jjStartNfaWithStates_0(3, 80, 37); - return jjMoveStringLiteralDfa4_0(active0, 0x20000000000L, active1, 0L); - case 84: - case 116: - if ((active0 & 0x8000000L) != 0L) - return jjStartNfaWithStates_0(3, 27, 37); - else if ((active1 & 0x4000L) != 0L) - return jjStartNfaWithStates_0(3, 78, 37); - return jjMoveStringLiteralDfa4_0(active0, 0x420000000000000L, active1, 0x1L); - case 85: - case 117: - return jjMoveStringLiteralDfa4_0(active0, 0x40000800000L, active1, 0L); - case 87: - case 119: - return jjMoveStringLiteralDfa4_0(active0, 0x4000000000L, active1, 0L); - case 89: - case 121: - return jjMoveStringLiteralDfa4_0(active0, 0x100000000000000L, active1, 0L); - default : - break; - } - return jjStartNfa_0(2, active0, active1); -} -private int jjMoveStringLiteralDfa4_0(long old0, long active0, long old1, long active1) -{ - if (((active0 &= old0) | (active1 &= old1)) == 0L) - return jjStartNfa_0(2, old0, old1); - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { - jjStopStringLiteralDfa_0(3, active0, active1); - return 4; - } - switch(curChar) - { - case 48: - if ((active1 & 0x80L) != 0L) - return jjStartNfaWithStates_0(4, 71, 21); - break; - case 50: - if ((active1 & 0x80000L) != 0L) - return jjStartNfaWithStates_0(4, 83, 21); - break; - case 65: - case 97: - return jjMoveStringLiteralDfa5_0(active0, 0x400000000000000L, active1, 0x801L); - case 67: - case 99: - return jjMoveStringLiteralDfa5_0(active0, 0x40000L, active1, 0x8000L); - case 68: - case 100: - if ((active1 & 0x2000L) != 0L) - return jjStartNfaWithStates_0(4, 77, 37); - return jjMoveStringLiteralDfa5_0(active0, 0xe000000000000000L, active1, 0L); - case 69: - case 101: - if ((active0 & 0x100000000L) != 0L) - return jjStartNfaWithStates_0(4, 32, 37); - return jjMoveStringLiteralDfa5_0(active0, 0x4000000000L, active1, 0x8L); - case 71: - case 103: - if ((active0 & 0x80000000L) != 0L) - return jjStartNfaWithStates_0(4, 31, 37); - return jjMoveStringLiteralDfa5_0(active0, 0x100000000000000L, active1, 0L); - case 73: - case 105: - return jjMoveStringLiteralDfa5_0(active0, 0L, active1, 0x4L); - case 76: - case 108: - return jjMoveStringLiteralDfa5_0(active0, 0x40000000000000L, active1, 0L); - case 78: - case 110: - return jjMoveStringLiteralDfa5_0(active0, 0x80000000000L, active1, 0L); - case 79: - case 111: - return jjMoveStringLiteralDfa5_0(active0, 0x200000000000000L, active1, 0L); - case 80: - case 112: - return jjMoveStringLiteralDfa5_0(active0, 0x40000000000L, active1, 0L); - case 82: - case 114: - if ((active0 & 0x1000000L) != 0L) - return jjStartNfaWithStates_0(4, 24, 37); - else if ((active0 & 0x2000000L) != 0L) - return jjStartNfaWithStates_0(4, 25, 37); - else if ((active1 & 0x20L) != 0L) - return jjStartNfaWithStates_0(4, 69, 37); - else if ((active1 & 0x400L) != 0L) - return jjStartNfaWithStates_0(4, 74, 37); - return jjMoveStringLiteralDfa5_0(active0, 0x820100000800000L, active1, 0L); - case 84: - case 116: - if ((active0 & 0x4000000L) != 0L) - return jjStartNfaWithStates_0(4, 26, 37); - else if ((active0 & 0x8000000000000L) != 0L) - return jjStartNfaWithStates_0(4, 51, 37); - else if ((active0 & 0x80000000000000L) != 0L) - return jjStartNfaWithStates_0(4, 55, 37); - return jjMoveStringLiteralDfa5_0(active0, 0x20000000000L, active1, 0L); - default : - break; - } - return jjStartNfa_0(3, active0, active1); -} -private int jjMoveStringLiteralDfa5_0(long old0, long active0, long old1, long active1) -{ - if (((active0 &= old0) | (active1 &= old1)) == 0L) - return jjStartNfa_0(3, old0, old1); - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { - jjStopStringLiteralDfa_0(4, active0, active1); - return 5; - } - switch(curChar) - { - case 32: - return jjMoveStringLiteralDfa6_0(active0, 0x140000000000L, active1, 0L); - case 49: - if ((active0 & 0x2000000000000000L) != 0L) - return jjStartNfaWithStates_0(5, 61, 21); - break; - case 50: - if ((active0 & 0x4000000000000000L) != 0L) - return jjStartNfaWithStates_0(5, 62, 21); - break; - case 65: - case 97: - return jjMoveStringLiteralDfa6_0(active0, 0x800000L, active1, 0x8000L); - case 69: - case 101: - if ((active0 & 0x40000000000000L) != 0L) - return jjStartNfaWithStates_0(5, 54, 37); - return jjMoveStringLiteralDfa6_0(active0, 0x4000000000L, active1, 0x8L); - case 71: - case 103: - if ((active0 & 0x80000000000L) != 0L) - return jjStartNfaWithStates_0(5, 43, 37); - break; - case 73: - case 105: - return jjMoveStringLiteralDfa6_0(active0, 0x400000000000000L, active1, 0L); - case 78: - case 110: - if ((active0 & 0x200000000000000L) != 0L) - return jjStartNfaWithStates_0(5, 57, 37); - return jjMoveStringLiteralDfa6_0(active0, 0L, active1, 0x805L); - case 79: - case 111: - return jjMoveStringLiteralDfa6_0(active0, 0x120000000000000L, active1, 0L); - case 83: - case 115: - if ((active0 & 0x20000000000L) != 0L) - return jjStartNfaWithStates_0(5, 41, 37); - return jjMoveStringLiteralDfa6_0(active0, 0x8800000000000000L, active1, 0L); - case 84: - case 116: - if ((active0 & 0x40000L) != 0L) - return jjStartNfaWithStates_0(5, 18, 37); - break; - default : - break; - } - return jjStartNfa_0(4, active0, active1); -} -private int jjMoveStringLiteralDfa6_0(long old0, long active0, long old1, long active1) -{ - if (((active0 &= old0) | (active1 &= old1)) == 0L) - return jjStartNfa_0(4, old0, old1); - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { - jjStopStringLiteralDfa_0(5, active0, active1); - return 6; - } - switch(curChar) - { - case 66: - case 98: - return jjMoveStringLiteralDfa7_0(active0, 0x140000000000L, active1, 0L); - case 67: - case 99: - return jjMoveStringLiteralDfa7_0(active0, 0L, active1, 0x1L); - case 69: - case 101: - return jjMoveStringLiteralDfa7_0(active0, 0x800000000000000L, active1, 0L); - case 71: - case 103: - if ((active1 & 0x4L) != 0L) - return jjStartNfaWithStates_0(6, 66, 37); - break; - case 73: - case 105: - return jjMoveStringLiteralDfa7_0(active0, 0x20000000000000L, active1, 0L); - case 76: - case 108: - if ((active0 & 0x800000L) != 0L) - return jjStartNfaWithStates_0(6, 23, 37); - break; - case 78: - case 110: - if ((active0 & 0x4000000000L) != 0L) - return jjStartNfaWithStates_0(6, 38, 37); - else if ((active0 & 0x100000000000000L) != 0L) - return jjStartNfaWithStates_0(6, 56, 37); - return jjMoveStringLiteralDfa7_0(active0, 0x400000000000000L, active1, 0L); - case 83: - case 115: - if ((active1 & 0x8L) != 0L) - return jjStartNfaWithStates_0(6, 67, 37); - else if ((active1 & 0x800L) != 0L) - return jjStartNfaWithStates_0(6, 75, 37); - break; - case 84: - case 116: - return jjMoveStringLiteralDfa7_0(active0, 0L, active1, 0x8000L); - case 89: - case 121: - return jjMoveStringLiteralDfa7_0(active0, 0x8000000000000000L, active1, 0L); - default : - break; - } - return jjStartNfa_0(5, active0, active1); -} -private int jjMoveStringLiteralDfa7_0(long old0, long active0, long old1, long active1) -{ - if (((active0 &= old0) | (active1 &= old1)) == 0L) - return jjStartNfa_0(5, old0, old1); - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { - jjStopStringLiteralDfa_0(6, active0, active1); - return 7; - } - switch(curChar) - { - case 67: - case 99: - return jjMoveStringLiteralDfa8_0(active0, 0x800000000000000L, active1, 0L); - case 68: - case 100: - if ((active0 & 0x20000000000000L) != 0L) - return jjStartNfaWithStates_0(7, 53, 37); - break; - case 69: - case 101: - if ((active1 & 0x1L) != 0L) - return jjStartNfaWithStates_0(7, 64, 37); - else if ((active1 & 0x8000L) != 0L) - return jjStartNfaWithStates_0(7, 79, 37); - break; - case 83: - case 115: - if ((active0 & 0x400000000000000L) != 0L) - return jjStartNfaWithStates_0(7, 58, 37); - else if ((active0 & 0x8000000000000000L) != 0L) - return jjStartNfaWithStates_0(7, 63, 37); - break; - case 89: - case 121: - if ((active0 & 0x40000000000L) != 0L) - return jjStopAtPos(7, 42); - else if ((active0 & 0x100000000000L) != 0L) - return jjStopAtPos(7, 44); - break; - default : - break; - } - return jjStartNfa_0(6, active0, active1); -} -private int jjMoveStringLiteralDfa8_0(long old0, long active0, long old1, long active1) -{ - if (((active0 &= old0) | (active1 &= old1)) == 0L) - return jjStartNfa_0(6, old0, old1); - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { - jjStopStringLiteralDfa_0(7, active0, 0L); - return 8; - } - switch(curChar) - { - case 84: - case 116: - return jjMoveStringLiteralDfa9_0(active0, 0x800000000000000L); - default : - break; - } - return jjStartNfa_0(7, active0, 0L); -} -private int jjMoveStringLiteralDfa9_0(long old0, long active0) -{ - if (((active0 &= old0)) == 0L) - return jjStartNfa_0(7, old0, 0L); - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { - jjStopStringLiteralDfa_0(8, active0, 0L); - return 9; - } - switch(curChar) - { - case 83: - case 115: - if ((active0 & 0x800000000000000L) != 0L) - return jjStartNfaWithStates_0(9, 59, 37); - break; - default : - break; - } - return jjStartNfa_0(8, active0, 0L); -} -private int jjStartNfaWithStates_0(int pos, int kind, int state) -{ - jjmatchedKind = kind; - jjmatchedPos = pos; - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { return pos + 1; } - return jjMoveNfa_0(state, pos + 1); -} -private int jjMoveNfa_0(int startState, int curPos) -{ - int startsAt = 0; - jjnewStateCnt = 37; - int i = 1; - jjstateSet[0] = startState; - int kind = 0x7fffffff; - for (;;) - { - if (++jjround == 0x7fffffff) - ReInitRounds(); - if (curChar < 64) - { - long l = 1L << curChar; - do - { - switch(jjstateSet[--i]) - { - case 12: - case 21: - if ((0x3ff000000000000L & l) == 0L) - break; - if (kind > 97) - kind = 97; - jjCheckNAdd(21); - break; - case 38: - if ((0x3ff000000000000L & l) != 0L) - { - if (kind > 100) - kind = 100; - jjCheckNAdd(27); - } - if ((0x3ff000000000000L & l) != 0L) - jjCheckNAddTwoStates(23, 24); - break; - case 37: - if ((0x3ff000000000000L & l) == 0L) - break; - if (kind > 97) - kind = 97; - jjCheckNAdd(21); - break; - case 0: - if ((0x3ff000000000000L & l) != 0L) - { - if (kind > 101) - kind = 101; - jjCheckNAddStates(0, 6); - } - else if ((0x100002600L & l) != 0L) - { - if (kind > 1) - kind = 1; - } - else if (curChar == 46) - jjCheckNAddTwoStates(23, 27); - else if (curChar == 45) - jjCheckNAdd(19); - else if (curChar == 33) - jjstateSet[jjnewStateCnt++] = 5; - else if (curChar == 60) - jjstateSet[jjnewStateCnt++] = 3; - if (curChar == 13) - jjstateSet[jjnewStateCnt++] = 1; - break; - case 11: - if ((0x3ff000000000000L & l) == 0L) - break; - if (kind > 97) - kind = 97; - jjCheckNAdd(21); - break; - case 16: - if ((0x3ff000000000000L & l) == 0L) - break; - if (kind > 97) - kind = 97; - jjCheckNAdd(21); - break; - case 13: - if ((0x3ff000000000000L & l) == 0L) - break; - if (kind > 97) - kind = 97; - jjCheckNAdd(21); - break; - case 10: - if ((0x3ff000000000000L & l) == 0L) - break; - if (kind > 97) - kind = 97; - jjCheckNAdd(21); - break; - case 1: - if (curChar == 10 && kind > 1) - kind = 1; - break; - case 2: - if (curChar == 13) - jjstateSet[jjnewStateCnt++] = 1; - break; - case 3: - if (curChar == 62) - kind = 13; - break; - case 4: - if (curChar == 60) - jjstateSet[jjnewStateCnt++] = 3; - break; - case 5: - if (curChar == 61) - kind = 13; - break; - case 6: - if (curChar == 33) - jjstateSet[jjnewStateCnt++] = 5; - break; - case 18: - if (curChar == 45) - jjCheckNAdd(19); - break; - case 19: - if (curChar != 45) - break; - if (kind > 88) - kind = 88; - jjCheckNAdd(19); - break; - case 22: - if (curChar == 46) - jjCheckNAddTwoStates(23, 27); - break; - case 23: - if ((0x3ff000000000000L & l) != 0L) - jjCheckNAddTwoStates(23, 24); - break; - case 25: - if ((0x280000000000L & l) != 0L) - jjCheckNAdd(26); - break; - case 26: - if ((0x3ff000000000000L & l) == 0L) - break; - if (kind > 99) - kind = 99; - jjCheckNAdd(26); - break; - case 27: - if ((0x3ff000000000000L & l) == 0L) - break; - if (kind > 100) - kind = 100; - jjCheckNAdd(27); - break; - case 28: - if ((0x3ff000000000000L & l) == 0L) - break; - if (kind > 101) - kind = 101; - jjCheckNAddStates(0, 6); - break; - case 29: - if ((0x3ff000000000000L & l) != 0L) - jjCheckNAddTwoStates(29, 24); - break; - case 30: - if ((0x3ff000000000000L & l) != 0L) - jjCheckNAddTwoStates(30, 31); - break; - case 31: - if (curChar == 46) - jjCheckNAddTwoStates(32, 24); - break; - case 32: - if ((0x3ff000000000000L & l) != 0L) - jjCheckNAddTwoStates(32, 24); - break; - case 33: - if ((0x3ff000000000000L & l) != 0L) - jjCheckNAddTwoStates(33, 34); - break; - case 34: - if (curChar != 46) - break; - if (kind > 100) - kind = 100; - jjCheckNAdd(35); - break; - case 35: - if ((0x3ff000000000000L & l) == 0L) - break; - if (kind > 100) - kind = 100; - jjCheckNAdd(35); - break; - case 36: - if ((0x3ff000000000000L & l) == 0L) - break; - if (kind > 101) - kind = 101; - jjCheckNAdd(36); - break; - default : break; - } - } while(i != startsAt); - } - else if (curChar < 128) - { - long l = 1L << (curChar & 077); - do - { - switch(jjstateSet[--i]) - { - case 12: - if ((0x7fffffe87fffffeL & l) != 0L) - { - if (kind > 97) - kind = 97; - jjCheckNAdd(21); - } - if ((0x7fffffe07fffffeL & l) != 0L) - { - if (kind > 97) - kind = 97; - jjCheckNAddTwoStates(20, 21); - } - if ((0x8000000080000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 11; - break; - case 37: - if ((0x7fffffe87fffffeL & l) != 0L) - { - if (kind > 97) - kind = 97; - jjCheckNAdd(21); - } - if ((0x7fffffe07fffffeL & l) != 0L) - { - if (kind > 97) - kind = 97; - jjCheckNAddTwoStates(20, 21); - } - break; - case 0: - if ((0x7fffffe07fffffeL & l) != 0L) - { - if (kind > 97) - kind = 97; - jjCheckNAddTwoStates(20, 21); - } - if ((0x200000002L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 16; - else if ((0x1000000010L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 13; - break; - case 11: - if ((0x7fffffe87fffffeL & l) != 0L) - { - if (kind > 97) - kind = 97; - jjCheckNAdd(21); - } - if ((0x7fffffe07fffffeL & l) != 0L) - { - if (kind > 97) - kind = 97; - jjCheckNAddTwoStates(20, 21); - } - if ((0x10000000100000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 10; - break; - case 16: - if ((0x7fffffe87fffffeL & l) != 0L) - { - if (kind > 97) - kind = 97; - jjCheckNAdd(21); - } - if ((0x7fffffe07fffffeL & l) != 0L) - { - if (kind > 97) - kind = 97; - jjCheckNAddTwoStates(20, 21); - } - if ((0x100000001000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 15; - break; - case 13: - if ((0x7fffffe87fffffeL & l) != 0L) - { - if (kind > 97) - kind = 97; - jjCheckNAdd(21); - } - if ((0x7fffffe07fffffeL & l) != 0L) - { - if (kind > 97) - kind = 97; - jjCheckNAddTwoStates(20, 21); - } - if ((0x20000000200L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 12; - break; - case 10: - if ((0x7fffffe87fffffeL & l) != 0L) - { - if (kind > 97) - kind = 97; - jjCheckNAdd(21); - } - if ((0x7fffffe07fffffeL & l) != 0L) - { - if (kind > 97) - kind = 97; - jjCheckNAddTwoStates(20, 21); - } - if ((0x20000000200L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 9; - break; - case 7: - if ((0x10000000100000L & l) != 0L && kind > 19) - kind = 19; - break; - case 8: - if ((0x800000008L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 7; - break; - case 9: - if ((0x400000004000L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 8; - break; - case 14: - if ((0x1000000010L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 13; - break; - case 15: - if ((0x100000001000L & l) != 0L && kind > 19) - kind = 19; - break; - case 17: - if ((0x200000002L & l) != 0L) - jjstateSet[jjnewStateCnt++] = 16; - break; - case 20: - if ((0x7fffffe07fffffeL & l) == 0L) - break; - if (kind > 97) - kind = 97; - jjCheckNAddTwoStates(20, 21); - break; - case 21: - if ((0x7fffffe87fffffeL & l) == 0L) - break; - if (kind > 97) - kind = 97; - jjCheckNAdd(21); - break; - case 24: - if ((0x2000000020L & l) != 0L) - jjAddStates(7, 8); - break; - default : break; - } - } while(i != startsAt); - } - else - { - int i2 = (curChar & 0xff) >> 6; - long l2 = 1L << (curChar & 077); - do - { - switch(jjstateSet[--i]) - { - default : break; - } - } while(i != startsAt); - } - if (kind != 0x7fffffff) - { - jjmatchedKind = kind; - jjmatchedPos = curPos; - kind = 0x7fffffff; - } - ++curPos; - if ((i = jjnewStateCnt) == (startsAt = 37 - (jjnewStateCnt = startsAt))) - return curPos; - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { return curPos; } - } -} -private final int jjStopStringLiteralDfa_2(int pos, long active0, long active1) -{ - switch (pos) - { - default : - return -1; - } -} -private final int jjStartNfa_2(int pos, long active0, long active1) -{ - return jjMoveNfa_2(jjStopStringLiteralDfa_2(pos, active0, active1), pos + 1); -} -private int jjMoveStringLiteralDfa0_2() -{ - switch(curChar) - { - case 39: - return jjStartNfaWithStates_2(0, 93, 1); - default : - return jjMoveNfa_2(0, 0); - } -} -private int jjStartNfaWithStates_2(int pos, int kind, int state) -{ - jjmatchedKind = kind; - jjmatchedPos = pos; - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { return pos + 1; } - return jjMoveNfa_2(state, pos + 1); -} -private int jjMoveNfa_2(int startState, int curPos) -{ - int startsAt = 0; - jjnewStateCnt = 3; - int i = 1; - jjstateSet[0] = startState; - int kind = 0x7fffffff; - for (;;) - { - if (++jjround == 0x7fffffff) - ReInitRounds(); - if (curChar < 64) - { - long l = 1L << curChar; - do - { - switch(jjstateSet[--i]) - { - case 0: - if ((0xffffff7fffffffffL & l) != 0L) - { - if (kind > 92) - kind = 92; - } - else if (curChar == 39) - jjstateSet[jjnewStateCnt++] = 1; - break; - case 1: - if (curChar == 39 && kind > 92) - kind = 92; - break; - case 2: - if (curChar == 39) - jjstateSet[jjnewStateCnt++] = 1; - break; - default : break; - } - } while(i != startsAt); - } - else if (curChar < 128) - { - long l = 1L << (curChar & 077); - do - { - switch(jjstateSet[--i]) - { - case 0: - kind = 92; - break; - default : break; - } - } while(i != startsAt); - } - else - { - int i2 = (curChar & 0xff) >> 6; - long l2 = 1L << (curChar & 077); - do - { - switch(jjstateSet[--i]) - { - case 0: - if ((jjbitVec0[i2] & l2) != 0L && kind > 92) - kind = 92; - break; - default : break; - } - } while(i != startsAt); - } - if (kind != 0x7fffffff) - { - jjmatchedKind = kind; - jjmatchedPos = curPos; - kind = 0x7fffffff; - } - ++curPos; - if ((i = jjnewStateCnt) == (startsAt = 3 - (jjnewStateCnt = startsAt))) - return curPos; - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { return curPos; } - } -} -private int jjMoveStringLiteralDfa0_1() -{ - return jjMoveNfa_1(0, 0); -} -private int jjMoveNfa_1(int startState, int curPos) -{ - int startsAt = 0; - jjnewStateCnt = 3; - int i = 1; - jjstateSet[0] = startState; - int kind = 0x7fffffff; - for (;;) - { - if (++jjround == 0x7fffffff) - ReInitRounds(); - if (curChar < 64) - { - long l = 1L << curChar; - do - { - switch(jjstateSet[--i]) - { - case 0: - if ((0x2400L & l) != 0L) - { - if (kind > 89) - kind = 89; - } - if (curChar == 13) - jjstateSet[jjnewStateCnt++] = 1; - break; - case 1: - if (curChar == 10 && kind > 89) - kind = 89; - break; - case 2: - if (curChar == 13) - jjstateSet[jjnewStateCnt++] = 1; - break; - default : break; - } - } while(i != startsAt); - } - else if (curChar < 128) - { - long l = 1L << (curChar & 077); - do - { - switch(jjstateSet[--i]) - { - default : break; - } - } while(i != startsAt); - } - else - { - int i2 = (curChar & 0xff) >> 6; - long l2 = 1L << (curChar & 077); - do - { - switch(jjstateSet[--i]) - { - default : break; - } - } while(i != startsAt); - } - if (kind != 0x7fffffff) - { - jjmatchedKind = kind; - jjmatchedPos = curPos; - kind = 0x7fffffff; - } - ++curPos; - if ((i = jjnewStateCnt) == (startsAt = 3 - (jjnewStateCnt = startsAt))) - return curPos; - try { curChar = input_stream.readChar(); } - catch(java.io.IOException e) { return curPos; } - } -} -static final int[] jjnextStates = { - 29, 30, 31, 24, 33, 34, 36, 25, 26, -}; + /** Debug output. */ + public java.io.PrintStream debugStream = System.out; -/** Token literal values. */ -public static final String[] jjstrLiteralImages = { -"", null, "\50", "\51", "\56", "\54", "\73", "\174\174", "\53", "\55", "\52", -"\57", "\75", null, "\74", "\74\75", "\76", "\76\75", null, null, null, null, null, -null, null, null, null, null, null, null, null, null, null, null, null, null, null, -null, null, null, null, null, null, null, null, null, null, null, null, null, null, -null, null, null, null, null, null, null, null, null, null, null, null, null, null, -null, null, null, null, null, null, null, null, null, null, null, null, null, null, -null, null, null, null, null, null, null, null, null, null, null, null, null, null, -null, null, null, null, null, null, null, null, null, null, }; + /** Set debug output. */ + public void setDebugStream(java.io.PrintStream ds){ + debugStream = ds; + } -/** Lexer state names. */ -public static final String[] lexStateNames = { - "DEFAULT", - "WithinComment", - "WithinString", - "WithinDelimitedId", -}; + private final int jjStopStringLiteralDfa_3(int pos, long active0, long active1){ + switch(pos){ + default: + return -1; + } + } -/** Lex State array. */ -public static final int[] jjnewLexState = { - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 0, -1, 2, -1, 0, 3, -1, 0, -1, -1, -1, - -1, -1, -1, -}; -static final long[] jjtoToken = { - 0xfffffffffffffffdL, 0x3b20ffffffL, -}; -static final long[] jjtoSkip = { - 0x2L, 0x2000000L, -}; -static final long[] jjtoMore = { - 0x0L, 0xdd000000L, -}; -protected SimpleCharStream input_stream; -private final int[] jjrounds = new int[37]; -private final int[] jjstateSet = new int[74]; -protected char curChar; -/** Constructor. */ -public ADQLParserTokenManager(SimpleCharStream stream){ - if (SimpleCharStream.staticFlag) - throw new Error("ERROR: Cannot use a static CharStream class with a non-static lexical analyzer."); - input_stream = stream; -} + private final int jjStartNfa_3(int pos, long active0, long active1){ + return jjMoveNfa_3(jjStopStringLiteralDfa_3(pos, active0, active1), pos + 1); + } -/** Constructor. */ -public ADQLParserTokenManager(SimpleCharStream stream, int lexState){ - this(stream); - SwitchTo(lexState); -} + private int jjStopAtPos(int pos, int kind){ + jjmatchedKind = kind; + jjmatchedPos = pos; + return pos + 1; + } -/** Reinitialise parser. */ -public void ReInit(SimpleCharStream stream) -{ - jjmatchedPos = jjnewStateCnt = 0; - curLexState = defaultLexState; - input_stream = stream; - ReInitRounds(); -} -private void ReInitRounds() -{ - int i; - jjround = 0x80000001; - for (i = 37; i-- > 0;) - jjrounds[i] = 0x80000000; -} + private int jjMoveStringLiteralDfa0_3(){ + switch(curChar){ + case 34: + return jjStartNfaWithStates_3(0, 96, 1); + default: + return jjMoveNfa_3(0, 0); + } + } -/** Reinitialise parser. */ -public void ReInit(SimpleCharStream stream, int lexState) -{ - ReInit(stream); - SwitchTo(lexState); -} + private int jjStartNfaWithStates_3(int pos, int kind, int state){ + jjmatchedKind = kind; + jjmatchedPos = pos; + try{ + curChar = input_stream.readChar(); + }catch(java.io.IOException e){ + return pos + 1; + } + return jjMoveNfa_3(state, pos + 1); + } -/** Switch to specified lex state. */ -public void SwitchTo(int lexState) -{ - if (lexState >= 4 || lexState < 0) - throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenMgrError.INVALID_LEXICAL_STATE); - else - curLexState = lexState; -} + static final long[] jjbitVec0 = {0x0L,0x0L,0xffffffffffffffffL,0xffffffffffffffffL}; -protected Token jjFillToken() -{ - final Token t; - final String curTokenImage; - final int beginLine; - final int endLine; - final int beginColumn; - final int endColumn; - String im = jjstrLiteralImages[jjmatchedKind]; - curTokenImage = (im == null) ? input_stream.GetImage() : im; - beginLine = input_stream.getBeginLine(); - beginColumn = input_stream.getBeginColumn(); - endLine = input_stream.getEndLine(); - endColumn = input_stream.getEndColumn(); - t = Token.newToken(jjmatchedKind, curTokenImage); + private int jjMoveNfa_3(int startState, int curPos){ + int startsAt = 0; + jjnewStateCnt = 3; + int i = 1; + jjstateSet[0] = startState; + int kind = 0x7fffffff; + for(;;){ + if (++jjround == 0x7fffffff) + ReInitRounds(); + if (curChar < 64){ + long l = 1L << curChar; + do{ + switch(jjstateSet[--i]){ + case 0: + if ((0xfffffffbffffffffL & l) != 0L){ + if (kind > 95) + kind = 95; + }else if (curChar == 34) + jjstateSet[jjnewStateCnt++] = 1; + break; + case 1: + if (curChar == 34 && kind > 95) + kind = 95; + break; + case 2: + if (curChar == 34) + jjstateSet[jjnewStateCnt++] = 1; + break; + default: + break; + } + }while(i != startsAt); + }else if (curChar < 128){ + long l = 1L << (curChar & 077); + do{ + switch(jjstateSet[--i]){ + case 0: + kind = 95; + break; + default: + break; + } + }while(i != startsAt); + }else{ + int i2 = (curChar & 0xff) >> 6; + long l2 = 1L << (curChar & 077); + do{ + switch(jjstateSet[--i]){ + case 0: + if ((jjbitVec0[i2] & l2) != 0L && kind > 95) + kind = 95; + break; + default: + break; + } + }while(i != startsAt); + } + if (kind != 0x7fffffff){ + jjmatchedKind = kind; + jjmatchedPos = curPos; + kind = 0x7fffffff; + } + ++curPos; + if ((i = jjnewStateCnt) == (startsAt = 3 - (jjnewStateCnt = startsAt))) + return curPos; + try{ + curChar = input_stream.readChar(); + }catch(java.io.IOException e){ + return curPos; + } + } + } - t.beginLine = beginLine; - t.endLine = endLine; - t.beginColumn = beginColumn; - t.endColumn = endColumn; + private final int jjStopStringLiteralDfa_0(int pos, long active0, long active1){ + switch(pos){ + case 0: + if ((active0 & 0xefff1ffdffb40000L) != 0L || (active1 & 0xf0fff4L) != 0L){ + jjmatchedKind = 97; + return 37; + } + if ((active0 & 0x1000a00200400000L) != 0L || (active1 & 0xf0002L) != 0L){ + jjmatchedKind = 97; + return 16; + } + if ((active0 & 0x10L) != 0L) + return 38; + if ((active0 & 0x400000000000L) != 0L || (active1 & 0x9L) != 0L){ + jjmatchedKind = 97; + return 13; + } + if ((active0 & 0xc000L) != 0L) + return 3; + if ((active0 & 0x200L) != 0L) + return 19; + return -1; + case 1: + if ((active0 & 0xf7ffceebbeb40000L) != 0L || (active1 & 0xfdfdfeL) != 0L){ + if (jjmatchedPos != 1){ + jjmatchedKind = 97; + jjmatchedPos = 1; + } + return 37; + } + if ((active0 & 0x800311441400000L) != 0L || (active1 & 0x20200L) != 0L) + return 37; + if ((active1 & 0x1L) != 0L){ + if (jjmatchedPos != 1){ + jjmatchedKind = 97; + jjmatchedPos = 1; + } + return 12; + } + return -1; + case 2: + if ((active1 & 0x1L) != 0L){ + if (jjmatchedPos != 2){ + jjmatchedKind = 97; + jjmatchedPos = 2; + } + return 11; + } + if ((active0 & 0x17a00a00100000L) != 0L || (active1 & 0xf001d2L) != 0L) + return 37; + if ((active0 & 0xffe85ee1bfa40000L) != 0L || (active1 & 0xffc2cL) != 0L){ + if (jjmatchedPos != 2){ + jjmatchedKind = 97; + jjmatchedPos = 2; + } + return 37; + } + return -1; + case 3: + if ((active0 & 0xefe81e4187840000L) != 0L || (active1 & 0xac2cL) != 0L){ + if (jjmatchedPos != 3){ + jjmatchedKind = 97; + jjmatchedPos = 3; + } + return 37; + } + if ((active0 & 0x100040a038200000L) != 0L || (active1 & 0xf5000L) != 0L) + return 37; + if ((active1 & 0x80L) != 0L){ + if (jjmatchedPos != 3){ + jjmatchedKind = 97; + jjmatchedPos = 3; + } + return 21; + } + if ((active1 & 0x1L) != 0L){ + if (jjmatchedPos != 3){ + jjmatchedKind = 97; + jjmatchedPos = 3; + } + return 10; + } + return -1; + case 4: + if ((active0 & 0xef601e4000840000L) != 0L || (active1 & 0x880dL) != 0L){ + jjmatchedKind = 97; + jjmatchedPos = 4; + return 37; + } + if ((active0 & 0x88000187000000L) != 0L || (active1 & 0x2420L) != 0L) + return 37; + if ((active1 & 0x80080L) != 0L) + return 21; + return -1; + case 5: + if ((active0 & 0x2400a0000040000L) != 0L) + return 37; + if ((active0 & 0x6000000000000000L) != 0L) + return 21; + if ((active0 & 0x8d20004000800000L) != 0L || (active1 & 0x880dL) != 0L){ + jjmatchedKind = 97; + jjmatchedPos = 5; + return 37; + } + if ((active0 & 0x140000000000L) != 0L){ + if (jjmatchedPos < 4){ + jjmatchedKind = 97; + jjmatchedPos = 4; + } + return -1; + } + return -1; + case 6: + if ((active0 & 0x8c20000000000000L) != 0L || (active1 & 0x8001L) != 0L){ + jjmatchedKind = 97; + jjmatchedPos = 6; + return 37; + } + if ((active0 & 0x100004000800000L) != 0L || (active1 & 0x80cL) != 0L) + return 37; + if ((active0 & 0x140000000000L) != 0L){ + if (jjmatchedPos < 4){ + jjmatchedKind = 97; + jjmatchedPos = 4; + } + return -1; + } + return -1; + case 7: + if ((active0 & 0x800000000000000L) != 0L){ + jjmatchedKind = 97; + jjmatchedPos = 7; + return 37; + } + if ((active0 & 0x8420000000000000L) != 0L || (active1 & 0x8001L) != 0L) + return 37; + if ((active0 & 0x140000000000L) != 0L){ + if (jjmatchedPos < 4){ + jjmatchedKind = 97; + jjmatchedPos = 4; + } + return -1; + } + return -1; + case 8: + if ((active0 & 0x800000000000000L) != 0L){ + jjmatchedKind = 97; + jjmatchedPos = 8; + return 37; + } + return -1; + default: + return -1; + } + } - return t; -} + private final int jjStartNfa_0(int pos, long active0, long active1){ + return jjMoveNfa_0(jjStopStringLiteralDfa_0(pos, active0, active1), pos + 1); + } -int curLexState = 0; -int defaultLexState = 0; -int jjnewStateCnt; -int jjround; -int jjmatchedPos; -int jjmatchedKind; + private int jjMoveStringLiteralDfa0_0(){ + switch(curChar){ + case 34: + return jjStopAtPos(0, 94); + case 39: + return jjStopAtPos(0, 91); + case 40: + return jjStopAtPos(0, 2); + case 41: + return jjStopAtPos(0, 3); + case 42: + return jjStopAtPos(0, 10); + case 43: + return jjStopAtPos(0, 8); + case 44: + return jjStopAtPos(0, 5); + case 45: + return jjStartNfaWithStates_0(0, 9, 19); + case 46: + return jjStartNfaWithStates_0(0, 4, 38); + case 47: + return jjStopAtPos(0, 11); + case 59: + return jjStopAtPos(0, 6); + case 60: + jjmatchedKind = 14; + return jjMoveStringLiteralDfa1_0(0x8000L, 0x0L); + case 61: + return jjStopAtPos(0, 12); + case 62: + jjmatchedKind = 16; + return jjMoveStringLiteralDfa1_0(0x20000L, 0x0L); + case 65: + case 97: + return jjMoveStringLiteralDfa1_0(0x1000a00200400000L, 0xf0002L); + case 66: + case 98: + return jjMoveStringLiteralDfa1_0(0x10004000000000L, 0x0L); + case 67: + case 99: + return jjMoveStringLiteralDfa1_0(0xe468000000000000L, 0x300004L); + case 68: + case 100: + return jjMoveStringLiteralDfa1_0(0x400000000000L, 0x9L); + case 69: + case 101: + return jjMoveStringLiteralDfa1_0(0x20000000000L, 0x10L); + case 70: + case 102: + return jjMoveStringLiteralDfa1_0(0x10200000L, 0x20L); + case 71: + case 103: + return jjMoveStringLiteralDfa1_0(0x40000000000L, 0x0L); + case 72: + case 104: + return jjMoveStringLiteralDfa1_0(0x80000000000L, 0x0L); + case 73: + case 105: + return jjMoveStringLiteralDfa1_0(0x800011001000000L, 0x0L); + case 74: + case 106: + return jjMoveStringLiteralDfa1_0(0x20000000L, 0x0L); + case 76: + case 108: + return jjMoveStringLiteralDfa1_0(0x8008000000L, 0xc0L); + case 77: + case 109: + return jjMoveStringLiteralDfa1_0(0x3000000000000L, 0x100L); + case 78: + case 110: + return jjMoveStringLiteralDfa1_0(0x2800800000L, 0x0L); + case 79: + case 111: + return jjMoveStringLiteralDfa1_0(0x100442000000L, 0x0L); + case 80: + case 112: + return jjMoveStringLiteralDfa1_0(0x180000000000000L, 0x600L); + case 82: + case 114: + return jjMoveStringLiteralDfa1_0(0x200000004000000L, 0x3800L); + case 83: + case 115: + return jjMoveStringLiteralDfa1_0(0x4000000040000L, 0x404000L); + case 84: + case 116: + return jjMoveStringLiteralDfa1_0(0x100000L, 0x808000L); + case 85: + case 117: + return jjMoveStringLiteralDfa1_0(0x80000000L, 0x0L); + case 87: + case 119: + return jjMoveStringLiteralDfa1_0(0x100000000L, 0x0L); + case 124: + return jjMoveStringLiteralDfa1_0(0x80L, 0x0L); + default: + return jjMoveNfa_0(0, 0); + } + } -/** Get the next Token. */ -public Token getNextToken() -{ - Token matchedToken; - int curPos = 0; + private int jjMoveStringLiteralDfa1_0(long active0, long active1){ + try{ + curChar = input_stream.readChar(); + }catch(java.io.IOException e){ + jjStopStringLiteralDfa_0(0, active0, active1); + return 1; + } + switch(curChar){ + case 61: + if ((active0 & 0x8000L) != 0L) + return jjStopAtPos(1, 15); + else if ((active0 & 0x20000L) != 0L) + return jjStopAtPos(1, 17); + break; + case 65: + case 97: + return jjMoveStringLiteralDfa2_0(active0, 0x1080000800000L, active1, 0x801800L); + case 66: + case 98: + return jjMoveStringLiteralDfa2_0(active0, 0L, active1, 0x2L); + case 67: + case 99: + return jjMoveStringLiteralDfa2_0(active0, 0L, active1, 0x10000L); + case 69: + case 101: + return jjMoveStringLiteralDfa2_0(active0, 0x220404008040000L, active1, 0xcL); + case 72: + case 104: + return jjMoveStringLiteralDfa2_0(active0, 0x100000000L, active1, 0L); + case 73: + case 105: + if ((active1 & 0x200L) != 0L) + return jjStartNfaWithStates_0(1, 73, 37); + return jjMoveStringLiteralDfa2_0(active0, 0x42008004000000L, active1, 0x400001L); + case 76: + case 108: + return jjMoveStringLiteralDfa2_0(active0, 0L, active1, 0x20L); + case 78: + case 110: + if ((active0 & 0x40000000L) != 0L) + return jjStartNfaWithStates_0(1, 30, 37); + else if ((active0 & 0x10000000000L) != 0L){ + jjmatchedKind = 40; + jjmatchedPos = 1; + } + return jjMoveStringLiteralDfa2_0(active0, 0x800000201000000L, active1, 0L); + case 79: + case 111: + return jjMoveStringLiteralDfa2_0(active0, 0xe598000820100000L, active1, 0x3025c0L); + case 81: + case 113: + return jjMoveStringLiteralDfa2_0(active0, 0L, active1, 0x4000L); + case 82: + case 114: + if ((active0 & 0x400000000L) != 0L){ + jjmatchedKind = 34; + jjmatchedPos = 1; + } + return jjMoveStringLiteralDfa2_0(active0, 0x1000140000200000L, active1, 0x8000L); + case 83: + case 115: + if ((active0 & 0x400000L) != 0L){ + jjmatchedKind = 22; + jjmatchedPos = 1; + }else if ((active0 & 0x1000000000L) != 0L) + return jjStartNfaWithStates_0(1, 36, 37); + return jjMoveStringLiteralDfa2_0(active0, 0x200080000000L, active1, 0x20000L); + case 84: + case 116: + return jjMoveStringLiteralDfa2_0(active0, 0L, active1, 0xc0000L); + case 85: + case 117: + return jjMoveStringLiteralDfa2_0(active0, 0x4002012000000L, active1, 0L); + case 86: + case 118: + return jjMoveStringLiteralDfa2_0(active0, 0x800000000000L, active1, 0L); + case 88: + case 120: + return jjMoveStringLiteralDfa2_0(active0, 0x20000000000L, active1, 0x10L); + case 124: + if ((active0 & 0x80L) != 0L) + return jjStopAtPos(1, 7); + break; + default: + break; + } + return jjStartNfa_0(0, active0, active1); + } - EOFLoop : - for (;;) - { - try - { - curChar = input_stream.BeginToken(); - } - catch(java.io.IOException e) - { - jjmatchedKind = 0; - matchedToken = jjFillToken(); - return matchedToken; - } + private int jjMoveStringLiteralDfa2_0(long old0, long active0, long old1, long active1){ + if (((active0 &= old0) | (active1 &= old1)) == 0L) + return jjStartNfa_0(0, old0, old1); + try{ + curChar = input_stream.readChar(); + }catch(java.io.IOException e){ + jjStopStringLiteralDfa_0(1, active0, active1); + return 2; + } + switch(curChar){ + case 65: + case 97: + return jjMoveStringLiteralDfa3_0(active0, 0L, active1, 0xc0000L); + case 67: + case 99: + if ((active0 & 0x200000000000L) != 0L) + return jjStartNfaWithStates_0(2, 45, 37); + break; + case 68: + case 100: + if ((active0 & 0x200000000L) != 0L) + return jjStartNfaWithStates_0(2, 33, 37); + else if ((active1 & 0x100L) != 0L) + return jjStartNfaWithStates_0(2, 72, 37); + return jjMoveStringLiteralDfa3_0(active0, 0x100000000000L, active1, 0x800L); + case 69: + case 101: + return jjMoveStringLiteralDfa3_0(active0, 0x1000000100000000L, active1, 0L); + case 70: + case 102: + return jjMoveStringLiteralDfa3_0(active0, 0x8000000L, active1, 0L); + case 71: + case 103: + if ((active0 & 0x800000000000L) != 0L) + return jjStartNfaWithStates_0(2, 47, 37); + else if ((active1 & 0x40L) != 0L){ + jjmatchedKind = 70; + jjmatchedPos = 2; + } + return jjMoveStringLiteralDfa3_0(active0, 0x200000004000000L, active1, 0x88L); + case 73: + case 105: + return jjMoveStringLiteralDfa3_0(active0, 0x800200a0000000L, active1, 0x20004L); + case 75: + case 107: + return jjMoveStringLiteralDfa3_0(active0, 0x8000000000L, active1, 0L); + case 76: + case 108: + return jjMoveStringLiteralDfa3_0(active0, 0x100002010040000L, active1, 0L); + case 77: + case 109: + if ((active0 & 0x4000000000000L) != 0L) + return jjStartNfaWithStates_0(2, 50, 37); + break; + case 78: + case 110: + if ((active0 & 0x2000000000000L) != 0L) + return jjStartNfaWithStates_0(2, 49, 37); + else if ((active1 & 0x400000L) != 0L) + return jjStartNfaWithStates_0(2, 86, 37); + else if ((active1 & 0x800000L) != 0L) + return jjStartNfaWithStates_0(2, 87, 37); + return jjMoveStringLiteralDfa3_0(active0, 0x420000001000000L, active1, 0x1000L); + case 79: + case 111: + return jjMoveStringLiteralDfa3_0(active0, 0xe000040000200000L, active1, 0x10020L); + case 80: + case 112: + if ((active0 & 0x100000L) != 0L) + return jjStartNfaWithStates_0(2, 20, 37); + else if ((active1 & 0x10L) != 0L) + return jjStartNfaWithStates_0(2, 68, 37); + break; + case 82: + case 114: + return jjMoveStringLiteralDfa3_0(active0, 0x40000000000000L, active1, 0x4000L); + case 83: + case 115: + if ((active1 & 0x2L) != 0L) + return jjStartNfaWithStates_0(2, 65, 37); + else if ((active1 & 0x100000L) != 0L) + return jjStartNfaWithStates_0(2, 84, 37); + return jjMoveStringLiteralDfa3_0(active0, 0x400000000000L, active1, 0x1L); + case 84: + case 116: + if ((active0 & 0x800000000L) != 0L) + return jjStartNfaWithStates_0(2, 35, 37); + else if ((active1 & 0x200000L) != 0L) + return jjStartNfaWithStates_0(2, 85, 37); + return jjMoveStringLiteralDfa3_0(active0, 0x800004002800000L, active1, 0L); + case 85: + case 117: + return jjMoveStringLiteralDfa3_0(active0, 0x8000000000000L, active1, 0xa000L); + case 86: + case 118: + return jjMoveStringLiteralDfa3_0(active0, 0x80000000000L, active1, 0L); + case 87: + case 119: + return jjMoveStringLiteralDfa3_0(active0, 0L, active1, 0x400L); + case 88: + case 120: + if ((active0 & 0x1000000000000L) != 0L) + return jjStartNfaWithStates_0(2, 48, 37); + else if ((active0 & 0x10000000000000L) != 0L) + return jjStartNfaWithStates_0(2, 52, 37); + break; + default: + break; + } + return jjStartNfa_0(1, active0, active1); + } - for (;;) - { - switch(curLexState) - { - case 0: - jjmatchedKind = 0x7fffffff; - jjmatchedPos = 0; - curPos = jjMoveStringLiteralDfa0_0(); - break; - case 1: - jjmatchedKind = 0x7fffffff; - jjmatchedPos = 0; - curPos = jjMoveStringLiteralDfa0_1(); - if (jjmatchedPos == 0 && jjmatchedKind > 90) - { - jjmatchedKind = 90; - } - break; - case 2: - jjmatchedKind = 0x7fffffff; - jjmatchedPos = 0; - curPos = jjMoveStringLiteralDfa0_2(); - break; - case 3: - jjmatchedKind = 0x7fffffff; - jjmatchedPos = 0; - curPos = jjMoveStringLiteralDfa0_3(); - break; - } - if (jjmatchedKind != 0x7fffffff) - { - if (jjmatchedPos + 1 < curPos) - input_stream.backup(curPos - jjmatchedPos - 1); - if ((jjtoToken[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L) - { - matchedToken = jjFillToken(); - if (jjnewLexState[jjmatchedKind] != -1) - curLexState = jjnewLexState[jjmatchedKind]; - return matchedToken; - } - else if ((jjtoSkip[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L) - { - if (jjnewLexState[jjmatchedKind] != -1) - curLexState = jjnewLexState[jjmatchedKind]; - continue EOFLoop; - } - if (jjnewLexState[jjmatchedKind] != -1) - curLexState = jjnewLexState[jjmatchedKind]; - curPos = 0; - jjmatchedKind = 0x7fffffff; - try { - curChar = input_stream.readChar(); - continue; - } - catch (java.io.IOException e1) { } - } - int error_line = input_stream.getEndLine(); - int error_column = input_stream.getEndColumn(); - String error_after = null; - boolean EOFSeen = false; - try { input_stream.readChar(); input_stream.backup(1); } - catch (java.io.IOException e1) { - EOFSeen = true; - error_after = curPos <= 1 ? "" : input_stream.GetImage(); - if (curChar == '\n' || curChar == '\r') { - error_line++; - error_column = 0; - } - else - error_column++; - } - if (!EOFSeen) { - input_stream.backup(1); - error_after = curPos <= 1 ? "" : input_stream.GetImage(); - } - throw new TokenMgrError(EOFSeen, curLexState, error_line, error_column, error_after, curChar, TokenMgrError.LEXICAL_ERROR); - } - } -} + private int jjMoveStringLiteralDfa3_0(long old0, long active0, long old1, long active1){ + if (((active0 &= old0) | (active1 &= old1)) == 0L) + return jjStartNfa_0(1, old0, old1); + try{ + curChar = input_stream.readChar(); + }catch(java.io.IOException e){ + jjStopStringLiteralDfa_0(2, active0, active1); + return 3; + } + switch(curChar){ + case 49: + return jjMoveStringLiteralDfa4_0(active0, 0L, active1, 0x80L); + case 65: + case 97: + if ((active0 & 0x1000000000000000L) != 0L) + return jjStartNfaWithStates_0(3, 60, 37); + break; + case 67: + case 99: + if ((active0 & 0x400000000000L) != 0L) + return jjStartNfaWithStates_0(3, 46, 37); + return jjMoveStringLiteralDfa4_0(active0, 0x40000000000000L, active1, 0L); + case 68: + case 100: + if ((active1 & 0x1000L) != 0L) + return jjStartNfaWithStates_0(3, 76, 37); + break; + case 69: + case 101: + if ((active0 & 0x8000000000L) != 0L) + return jjStartNfaWithStates_0(3, 39, 37); + return jjMoveStringLiteralDfa4_0(active0, 0x800100003040000L, active1, 0x400L); + case 72: + case 104: + return jjMoveStringLiteralDfa4_0(active0, 0x4000000L, active1, 0L); + case 73: + case 105: + return jjMoveStringLiteralDfa4_0(active0, 0x200080000000000L, active1, 0x800L); + case 76: + case 108: + if ((active0 & 0x10000000L) != 0L) + return jjStartNfaWithStates_0(3, 28, 37); + else if ((active0 & 0x2000000000L) != 0L) + return jjStartNfaWithStates_0(3, 37, 37); + return jjMoveStringLiteralDfa4_0(active0, 0L, active1, 0x4L); + case 77: + case 109: + if ((active0 & 0x200000L) != 0L) + return jjStartNfaWithStates_0(3, 21, 37); + break; + case 78: + case 110: + if ((active0 & 0x20000000L) != 0L) + return jjStartNfaWithStates_0(3, 29, 37); + else if ((active1 & 0x20000L) != 0L) + return jjStartNfaWithStates_0(3, 81, 37); + else if ((active1 & 0x40000L) != 0L){ + jjmatchedKind = 82; + jjmatchedPos = 3; + } + return jjMoveStringLiteralDfa4_0(active0, 0x88000080000000L, active1, 0x8a000L); + case 79: + case 111: + return jjMoveStringLiteralDfa4_0(active0, 0L, active1, 0x20L); + case 82: + case 114: + return jjMoveStringLiteralDfa4_0(active0, 0xe000000100000000L, active1, 0x8L); + case 83: + case 115: + if ((active1 & 0x10000L) != 0L) + return jjStartNfaWithStates_0(3, 80, 37); + return jjMoveStringLiteralDfa4_0(active0, 0x20000000000L, active1, 0L); + case 84: + case 116: + if ((active0 & 0x8000000L) != 0L) + return jjStartNfaWithStates_0(3, 27, 37); + else if ((active1 & 0x4000L) != 0L) + return jjStartNfaWithStates_0(3, 78, 37); + return jjMoveStringLiteralDfa4_0(active0, 0x420000000000000L, active1, 0x1L); + case 85: + case 117: + return jjMoveStringLiteralDfa4_0(active0, 0x40000800000L, active1, 0L); + case 87: + case 119: + return jjMoveStringLiteralDfa4_0(active0, 0x4000000000L, active1, 0L); + case 89: + case 121: + return jjMoveStringLiteralDfa4_0(active0, 0x100000000000000L, active1, 0L); + default: + break; + } + return jjStartNfa_0(2, active0, active1); + } -private void jjCheckNAdd(int state) -{ - if (jjrounds[state] != jjround) - { - jjstateSet[jjnewStateCnt++] = state; - jjrounds[state] = jjround; - } -} -private void jjAddStates(int start, int end) -{ - do { - jjstateSet[jjnewStateCnt++] = jjnextStates[start]; - } while (start++ != end); -} -private void jjCheckNAddTwoStates(int state1, int state2) -{ - jjCheckNAdd(state1); - jjCheckNAdd(state2); -} + private int jjMoveStringLiteralDfa4_0(long old0, long active0, long old1, long active1){ + if (((active0 &= old0) | (active1 &= old1)) == 0L) + return jjStartNfa_0(2, old0, old1); + try{ + curChar = input_stream.readChar(); + }catch(java.io.IOException e){ + jjStopStringLiteralDfa_0(3, active0, active1); + return 4; + } + switch(curChar){ + case 48: + if ((active1 & 0x80L) != 0L) + return jjStartNfaWithStates_0(4, 71, 21); + break; + case 50: + if ((active1 & 0x80000L) != 0L) + return jjStartNfaWithStates_0(4, 83, 21); + break; + case 65: + case 97: + return jjMoveStringLiteralDfa5_0(active0, 0x400000000000000L, active1, 0x801L); + case 67: + case 99: + return jjMoveStringLiteralDfa5_0(active0, 0x40000L, active1, 0x8000L); + case 68: + case 100: + if ((active1 & 0x2000L) != 0L) + return jjStartNfaWithStates_0(4, 77, 37); + return jjMoveStringLiteralDfa5_0(active0, 0xe000000000000000L, active1, 0L); + case 69: + case 101: + if ((active0 & 0x100000000L) != 0L) + return jjStartNfaWithStates_0(4, 32, 37); + return jjMoveStringLiteralDfa5_0(active0, 0x4000000000L, active1, 0x8L); + case 71: + case 103: + if ((active0 & 0x80000000L) != 0L) + return jjStartNfaWithStates_0(4, 31, 37); + return jjMoveStringLiteralDfa5_0(active0, 0x100000000000000L, active1, 0L); + case 73: + case 105: + return jjMoveStringLiteralDfa5_0(active0, 0L, active1, 0x4L); + case 76: + case 108: + return jjMoveStringLiteralDfa5_0(active0, 0x40000000000000L, active1, 0L); + case 78: + case 110: + return jjMoveStringLiteralDfa5_0(active0, 0x80000000000L, active1, 0L); + case 79: + case 111: + return jjMoveStringLiteralDfa5_0(active0, 0x200000000000000L, active1, 0L); + case 80: + case 112: + return jjMoveStringLiteralDfa5_0(active0, 0x40000000000L, active1, 0L); + case 82: + case 114: + if ((active0 & 0x1000000L) != 0L) + return jjStartNfaWithStates_0(4, 24, 37); + else if ((active0 & 0x2000000L) != 0L) + return jjStartNfaWithStates_0(4, 25, 37); + else if ((active1 & 0x20L) != 0L) + return jjStartNfaWithStates_0(4, 69, 37); + else if ((active1 & 0x400L) != 0L) + return jjStartNfaWithStates_0(4, 74, 37); + return jjMoveStringLiteralDfa5_0(active0, 0x820100000800000L, active1, 0L); + case 84: + case 116: + if ((active0 & 0x4000000L) != 0L) + return jjStartNfaWithStates_0(4, 26, 37); + else if ((active0 & 0x8000000000000L) != 0L) + return jjStartNfaWithStates_0(4, 51, 37); + else if ((active0 & 0x80000000000000L) != 0L) + return jjStartNfaWithStates_0(4, 55, 37); + return jjMoveStringLiteralDfa5_0(active0, 0x20000000000L, active1, 0L); + default: + break; + } + return jjStartNfa_0(3, active0, active1); + } -private void jjCheckNAddStates(int start, int end) -{ - do { - jjCheckNAdd(jjnextStates[start]); - } while (start++ != end); -} + private int jjMoveStringLiteralDfa5_0(long old0, long active0, long old1, long active1){ + if (((active0 &= old0) | (active1 &= old1)) == 0L) + return jjStartNfa_0(3, old0, old1); + try{ + curChar = input_stream.readChar(); + }catch(java.io.IOException e){ + jjStopStringLiteralDfa_0(4, active0, active1); + return 5; + } + switch(curChar){ + case 32: + return jjMoveStringLiteralDfa6_0(active0, 0x140000000000L, active1, 0L); + case 49: + if ((active0 & 0x2000000000000000L) != 0L) + return jjStartNfaWithStates_0(5, 61, 21); + break; + case 50: + if ((active0 & 0x4000000000000000L) != 0L) + return jjStartNfaWithStates_0(5, 62, 21); + break; + case 65: + case 97: + return jjMoveStringLiteralDfa6_0(active0, 0x800000L, active1, 0x8000L); + case 69: + case 101: + if ((active0 & 0x40000000000000L) != 0L) + return jjStartNfaWithStates_0(5, 54, 37); + return jjMoveStringLiteralDfa6_0(active0, 0x4000000000L, active1, 0x8L); + case 71: + case 103: + if ((active0 & 0x80000000000L) != 0L) + return jjStartNfaWithStates_0(5, 43, 37); + break; + case 73: + case 105: + return jjMoveStringLiteralDfa6_0(active0, 0x400000000000000L, active1, 0L); + case 78: + case 110: + if ((active0 & 0x200000000000000L) != 0L) + return jjStartNfaWithStates_0(5, 57, 37); + return jjMoveStringLiteralDfa6_0(active0, 0L, active1, 0x805L); + case 79: + case 111: + return jjMoveStringLiteralDfa6_0(active0, 0x120000000000000L, active1, 0L); + case 83: + case 115: + if ((active0 & 0x20000000000L) != 0L) + return jjStartNfaWithStates_0(5, 41, 37); + return jjMoveStringLiteralDfa6_0(active0, 0x8800000000000000L, active1, 0L); + case 84: + case 116: + if ((active0 & 0x40000L) != 0L) + return jjStartNfaWithStates_0(5, 18, 37); + break; + default: + break; + } + return jjStartNfa_0(4, active0, active1); + } + + private int jjMoveStringLiteralDfa6_0(long old0, long active0, long old1, long active1){ + if (((active0 &= old0) | (active1 &= old1)) == 0L) + return jjStartNfa_0(4, old0, old1); + try{ + curChar = input_stream.readChar(); + }catch(java.io.IOException e){ + jjStopStringLiteralDfa_0(5, active0, active1); + return 6; + } + switch(curChar){ + case 66: + case 98: + return jjMoveStringLiteralDfa7_0(active0, 0x140000000000L, active1, 0L); + case 67: + case 99: + return jjMoveStringLiteralDfa7_0(active0, 0L, active1, 0x1L); + case 69: + case 101: + return jjMoveStringLiteralDfa7_0(active0, 0x800000000000000L, active1, 0L); + case 71: + case 103: + if ((active1 & 0x4L) != 0L) + return jjStartNfaWithStates_0(6, 66, 37); + break; + case 73: + case 105: + return jjMoveStringLiteralDfa7_0(active0, 0x20000000000000L, active1, 0L); + case 76: + case 108: + if ((active0 & 0x800000L) != 0L) + return jjStartNfaWithStates_0(6, 23, 37); + break; + case 78: + case 110: + if ((active0 & 0x4000000000L) != 0L) + return jjStartNfaWithStates_0(6, 38, 37); + else if ((active0 & 0x100000000000000L) != 0L) + return jjStartNfaWithStates_0(6, 56, 37); + return jjMoveStringLiteralDfa7_0(active0, 0x400000000000000L, active1, 0L); + case 83: + case 115: + if ((active1 & 0x8L) != 0L) + return jjStartNfaWithStates_0(6, 67, 37); + else if ((active1 & 0x800L) != 0L) + return jjStartNfaWithStates_0(6, 75, 37); + break; + case 84: + case 116: + return jjMoveStringLiteralDfa7_0(active0, 0L, active1, 0x8000L); + case 89: + case 121: + return jjMoveStringLiteralDfa7_0(active0, 0x8000000000000000L, active1, 0L); + default: + break; + } + return jjStartNfa_0(5, active0, active1); + } + + private int jjMoveStringLiteralDfa7_0(long old0, long active0, long old1, long active1){ + if (((active0 &= old0) | (active1 &= old1)) == 0L) + return jjStartNfa_0(5, old0, old1); + try{ + curChar = input_stream.readChar(); + }catch(java.io.IOException e){ + jjStopStringLiteralDfa_0(6, active0, active1); + return 7; + } + switch(curChar){ + case 67: + case 99: + return jjMoveStringLiteralDfa8_0(active0, 0x800000000000000L, active1, 0L); + case 68: + case 100: + if ((active0 & 0x20000000000000L) != 0L) + return jjStartNfaWithStates_0(7, 53, 37); + break; + case 69: + case 101: + if ((active1 & 0x1L) != 0L) + return jjStartNfaWithStates_0(7, 64, 37); + else if ((active1 & 0x8000L) != 0L) + return jjStartNfaWithStates_0(7, 79, 37); + break; + case 83: + case 115: + if ((active0 & 0x400000000000000L) != 0L) + return jjStartNfaWithStates_0(7, 58, 37); + else if ((active0 & 0x8000000000000000L) != 0L) + return jjStartNfaWithStates_0(7, 63, 37); + break; + case 89: + case 121: + if ((active0 & 0x40000000000L) != 0L) + return jjStopAtPos(7, 42); + else if ((active0 & 0x100000000000L) != 0L) + return jjStopAtPos(7, 44); + break; + default: + break; + } + return jjStartNfa_0(6, active0, active1); + } + + private int jjMoveStringLiteralDfa8_0(long old0, long active0, long old1, long active1){ + if (((active0 &= old0) | (active1 &= old1)) == 0L) + return jjStartNfa_0(6, old0, old1); + try{ + curChar = input_stream.readChar(); + }catch(java.io.IOException e){ + jjStopStringLiteralDfa_0(7, active0, 0L); + return 8; + } + switch(curChar){ + case 84: + case 116: + return jjMoveStringLiteralDfa9_0(active0, 0x800000000000000L); + default: + break; + } + return jjStartNfa_0(7, active0, 0L); + } + + private int jjMoveStringLiteralDfa9_0(long old0, long active0){ + if (((active0 &= old0)) == 0L) + return jjStartNfa_0(7, old0, 0L); + try{ + curChar = input_stream.readChar(); + }catch(java.io.IOException e){ + jjStopStringLiteralDfa_0(8, active0, 0L); + return 9; + } + switch(curChar){ + case 83: + case 115: + if ((active0 & 0x800000000000000L) != 0L) + return jjStartNfaWithStates_0(9, 59, 37); + break; + default: + break; + } + return jjStartNfa_0(8, active0, 0L); + } + + private int jjStartNfaWithStates_0(int pos, int kind, int state){ + jjmatchedKind = kind; + jjmatchedPos = pos; + try{ + curChar = input_stream.readChar(); + }catch(java.io.IOException e){ + return pos + 1; + } + return jjMoveNfa_0(state, pos + 1); + } + + private int jjMoveNfa_0(int startState, int curPos){ + int startsAt = 0; + jjnewStateCnt = 37; + int i = 1; + jjstateSet[0] = startState; + int kind = 0x7fffffff; + for(;;){ + if (++jjround == 0x7fffffff) + ReInitRounds(); + if (curChar < 64){ + long l = 1L << curChar; + do{ + switch(jjstateSet[--i]){ + case 12: + case 21: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 97) + kind = 97; + jjCheckNAdd(21); + break; + case 38: + if ((0x3ff000000000000L & l) != 0L){ + if (kind > 100) + kind = 100; + jjCheckNAdd(27); + } + if ((0x3ff000000000000L & l) != 0L) + jjCheckNAddTwoStates(23, 24); + break; + case 37: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 97) + kind = 97; + jjCheckNAdd(21); + break; + case 0: + if ((0x3ff000000000000L & l) != 0L){ + if (kind > 101) + kind = 101; + jjCheckNAddStates(0, 6); + }else if ((0x100002600L & l) != 0L){ + if (kind > 1) + kind = 1; + }else if (curChar == 46) + jjCheckNAddTwoStates(23, 27); + else if (curChar == 45) + jjCheckNAdd(19); + else if (curChar == 33) + jjstateSet[jjnewStateCnt++] = 5; + else if (curChar == 60) + jjstateSet[jjnewStateCnt++] = 3; + if (curChar == 13) + jjstateSet[jjnewStateCnt++] = 1; + break; + case 11: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 97) + kind = 97; + jjCheckNAdd(21); + break; + case 16: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 97) + kind = 97; + jjCheckNAdd(21); + break; + case 13: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 97) + kind = 97; + jjCheckNAdd(21); + break; + case 10: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 97) + kind = 97; + jjCheckNAdd(21); + break; + case 1: + if (curChar == 10 && kind > 1) + kind = 1; + break; + case 2: + if (curChar == 13) + jjstateSet[jjnewStateCnt++] = 1; + break; + case 3: + if (curChar == 62) + kind = 13; + break; + case 4: + if (curChar == 60) + jjstateSet[jjnewStateCnt++] = 3; + break; + case 5: + if (curChar == 61) + kind = 13; + break; + case 6: + if (curChar == 33) + jjstateSet[jjnewStateCnt++] = 5; + break; + case 18: + if (curChar == 45) + jjCheckNAdd(19); + break; + case 19: + if (curChar != 45) + break; + if (kind > 88) + kind = 88; + jjCheckNAdd(19); + break; + case 22: + if (curChar == 46) + jjCheckNAddTwoStates(23, 27); + break; + case 23: + if ((0x3ff000000000000L & l) != 0L) + jjCheckNAddTwoStates(23, 24); + break; + case 25: + if ((0x280000000000L & l) != 0L) + jjCheckNAdd(26); + break; + case 26: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 99) + kind = 99; + jjCheckNAdd(26); + break; + case 27: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 100) + kind = 100; + jjCheckNAdd(27); + break; + case 28: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 101) + kind = 101; + jjCheckNAddStates(0, 6); + break; + case 29: + if ((0x3ff000000000000L & l) != 0L) + jjCheckNAddTwoStates(29, 24); + break; + case 30: + if ((0x3ff000000000000L & l) != 0L) + jjCheckNAddTwoStates(30, 31); + break; + case 31: + if (curChar == 46) + jjCheckNAddTwoStates(32, 24); + break; + case 32: + if ((0x3ff000000000000L & l) != 0L) + jjCheckNAddTwoStates(32, 24); + break; + case 33: + if ((0x3ff000000000000L & l) != 0L) + jjCheckNAddTwoStates(33, 34); + break; + case 34: + if (curChar != 46) + break; + if (kind > 100) + kind = 100; + jjCheckNAdd(35); + break; + case 35: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 100) + kind = 100; + jjCheckNAdd(35); + break; + case 36: + if ((0x3ff000000000000L & l) == 0L) + break; + if (kind > 101) + kind = 101; + jjCheckNAdd(36); + break; + default: + break; + } + }while(i != startsAt); + }else if (curChar < 128){ + long l = 1L << (curChar & 077); + do{ + switch(jjstateSet[--i]){ + case 12: + if ((0x7fffffe87fffffeL & l) != 0L){ + if (kind > 97) + kind = 97; + jjCheckNAdd(21); + } + if ((0x7fffffe07fffffeL & l) != 0L){ + if (kind > 97) + kind = 97; + jjCheckNAddTwoStates(20, 21); + } + if ((0x8000000080000L & l) != 0L) + jjstateSet[jjnewStateCnt++] = 11; + break; + case 37: + if ((0x7fffffe87fffffeL & l) != 0L){ + if (kind > 97) + kind = 97; + jjCheckNAdd(21); + } + if ((0x7fffffe07fffffeL & l) != 0L){ + if (kind > 97) + kind = 97; + jjCheckNAddTwoStates(20, 21); + } + break; + case 0: + if ((0x7fffffe07fffffeL & l) != 0L){ + if (kind > 97) + kind = 97; + jjCheckNAddTwoStates(20, 21); + } + if ((0x200000002L & l) != 0L) + jjstateSet[jjnewStateCnt++] = 16; + else if ((0x1000000010L & l) != 0L) + jjstateSet[jjnewStateCnt++] = 13; + break; + case 11: + if ((0x7fffffe87fffffeL & l) != 0L){ + if (kind > 97) + kind = 97; + jjCheckNAdd(21); + } + if ((0x7fffffe07fffffeL & l) != 0L){ + if (kind > 97) + kind = 97; + jjCheckNAddTwoStates(20, 21); + } + if ((0x10000000100000L & l) != 0L) + jjstateSet[jjnewStateCnt++] = 10; + break; + case 16: + if ((0x7fffffe87fffffeL & l) != 0L){ + if (kind > 97) + kind = 97; + jjCheckNAdd(21); + } + if ((0x7fffffe07fffffeL & l) != 0L){ + if (kind > 97) + kind = 97; + jjCheckNAddTwoStates(20, 21); + } + if ((0x100000001000L & l) != 0L) + jjstateSet[jjnewStateCnt++] = 15; + break; + case 13: + if ((0x7fffffe87fffffeL & l) != 0L){ + if (kind > 97) + kind = 97; + jjCheckNAdd(21); + } + if ((0x7fffffe07fffffeL & l) != 0L){ + if (kind > 97) + kind = 97; + jjCheckNAddTwoStates(20, 21); + } + if ((0x20000000200L & l) != 0L) + jjstateSet[jjnewStateCnt++] = 12; + break; + case 10: + if ((0x7fffffe87fffffeL & l) != 0L){ + if (kind > 97) + kind = 97; + jjCheckNAdd(21); + } + if ((0x7fffffe07fffffeL & l) != 0L){ + if (kind > 97) + kind = 97; + jjCheckNAddTwoStates(20, 21); + } + if ((0x20000000200L & l) != 0L) + jjstateSet[jjnewStateCnt++] = 9; + break; + case 7: + if ((0x10000000100000L & l) != 0L && kind > 19) + kind = 19; + break; + case 8: + if ((0x800000008L & l) != 0L) + jjstateSet[jjnewStateCnt++] = 7; + break; + case 9: + if ((0x400000004000L & l) != 0L) + jjstateSet[jjnewStateCnt++] = 8; + break; + case 14: + if ((0x1000000010L & l) != 0L) + jjstateSet[jjnewStateCnt++] = 13; + break; + case 15: + if ((0x100000001000L & l) != 0L && kind > 19) + kind = 19; + break; + case 17: + if ((0x200000002L & l) != 0L) + jjstateSet[jjnewStateCnt++] = 16; + break; + case 20: + if ((0x7fffffe07fffffeL & l) == 0L) + break; + if (kind > 97) + kind = 97; + jjCheckNAddTwoStates(20, 21); + break; + case 21: + if ((0x7fffffe87fffffeL & l) == 0L) + break; + if (kind > 97) + kind = 97; + jjCheckNAdd(21); + break; + case 24: + if ((0x2000000020L & l) != 0L) + jjAddStates(7, 8); + break; + default: + break; + } + }while(i != startsAt); + }else{ + int i2 = (curChar & 0xff) >> 6; + long l2 = 1L << (curChar & 077); + do{ + switch(jjstateSet[--i]){ + default: + break; + } + }while(i != startsAt); + } + if (kind != 0x7fffffff){ + jjmatchedKind = kind; + jjmatchedPos = curPos; + kind = 0x7fffffff; + } + ++curPos; + if ((i = jjnewStateCnt) == (startsAt = 37 - (jjnewStateCnt = startsAt))) + return curPos; + try{ + curChar = input_stream.readChar(); + }catch(java.io.IOException e){ + return curPos; + } + } + } + + private final int jjStopStringLiteralDfa_2(int pos, long active0, long active1){ + switch(pos){ + default: + return -1; + } + } + + private final int jjStartNfa_2(int pos, long active0, long active1){ + return jjMoveNfa_2(jjStopStringLiteralDfa_2(pos, active0, active1), pos + 1); + } + + private int jjMoveStringLiteralDfa0_2(){ + switch(curChar){ + case 39: + return jjStartNfaWithStates_2(0, 93, 1); + default: + return jjMoveNfa_2(0, 0); + } + } + + private int jjStartNfaWithStates_2(int pos, int kind, int state){ + jjmatchedKind = kind; + jjmatchedPos = pos; + try{ + curChar = input_stream.readChar(); + }catch(java.io.IOException e){ + return pos + 1; + } + return jjMoveNfa_2(state, pos + 1); + } + + private int jjMoveNfa_2(int startState, int curPos){ + int startsAt = 0; + jjnewStateCnt = 3; + int i = 1; + jjstateSet[0] = startState; + int kind = 0x7fffffff; + for(;;){ + if (++jjround == 0x7fffffff) + ReInitRounds(); + if (curChar < 64){ + long l = 1L << curChar; + do{ + switch(jjstateSet[--i]){ + case 0: + if ((0xffffff7fffffffffL & l) != 0L){ + if (kind > 92) + kind = 92; + }else if (curChar == 39) + jjstateSet[jjnewStateCnt++] = 1; + break; + case 1: + if (curChar == 39 && kind > 92) + kind = 92; + break; + case 2: + if (curChar == 39) + jjstateSet[jjnewStateCnt++] = 1; + break; + default: + break; + } + }while(i != startsAt); + }else if (curChar < 128){ + long l = 1L << (curChar & 077); + do{ + switch(jjstateSet[--i]){ + case 0: + kind = 92; + break; + default: + break; + } + }while(i != startsAt); + }else{ + int i2 = (curChar & 0xff) >> 6; + long l2 = 1L << (curChar & 077); + do{ + switch(jjstateSet[--i]){ + case 0: + if ((jjbitVec0[i2] & l2) != 0L && kind > 92) + kind = 92; + break; + default: + break; + } + }while(i != startsAt); + } + if (kind != 0x7fffffff){ + jjmatchedKind = kind; + jjmatchedPos = curPos; + kind = 0x7fffffff; + } + ++curPos; + if ((i = jjnewStateCnt) == (startsAt = 3 - (jjnewStateCnt = startsAt))) + return curPos; + try{ + curChar = input_stream.readChar(); + }catch(java.io.IOException e){ + return curPos; + } + } + } + + private int jjMoveStringLiteralDfa0_1(){ + return jjMoveNfa_1(0, 0); + } + + private int jjMoveNfa_1(int startState, int curPos){ + int startsAt = 0; + jjnewStateCnt = 3; + int i = 1; + jjstateSet[0] = startState; + int kind = 0x7fffffff; + for(;;){ + if (++jjround == 0x7fffffff) + ReInitRounds(); + if (curChar < 64){ + long l = 1L << curChar; + do{ + switch(jjstateSet[--i]){ + case 0: + if ((0x2400L & l) != 0L){ + if (kind > 89) + kind = 89; + } + if (curChar == 13) + jjstateSet[jjnewStateCnt++] = 1; + break; + case 1: + if (curChar == 10 && kind > 89) + kind = 89; + break; + case 2: + if (curChar == 13) + jjstateSet[jjnewStateCnt++] = 1; + break; + default: + break; + } + }while(i != startsAt); + }else if (curChar < 128){ + long l = 1L << (curChar & 077); + do{ + switch(jjstateSet[--i]){ + default: + break; + } + }while(i != startsAt); + }else{ + int i2 = (curChar & 0xff) >> 6; + long l2 = 1L << (curChar & 077); + do{ + switch(jjstateSet[--i]){ + default: + break; + } + }while(i != startsAt); + } + if (kind != 0x7fffffff){ + jjmatchedKind = kind; + jjmatchedPos = curPos; + kind = 0x7fffffff; + } + ++curPos; + if ((i = jjnewStateCnt) == (startsAt = 3 - (jjnewStateCnt = startsAt))) + return curPos; + try{ + curChar = input_stream.readChar(); + }catch(java.io.IOException e){ + return curPos; + } + } + } + + static final int[] jjnextStates = {29,30,31,24,33,34,36,25,26,}; + + /** Token literal values. */ + public static final String[] jjstrLiteralImages = {"",null,"\50","\51","\56","\54","\73","\174\174","\53","\55","\52","\57","\75",null,"\74","\74\75","\76","\76\75",null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,}; + + /** Lexer state names. */ + public static final String[] lexStateNames = {"DEFAULT","WithinComment","WithinString","WithinDelimitedId",}; + + /** Lex State array. */ + public static final int[] jjnewLexState = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,0,-1,2,-1,0,3,-1,0,-1,-1,-1,-1,-1,-1,}; + static final long[] jjtoToken = {0xfffffffffffffffdL,0x3b20ffffffL,}; + static final long[] jjtoSkip = {0x2L,0x2000000L,}; + static final long[] jjtoMore = {0x0L,0xdd000000L,}; + protected SimpleCharStream input_stream; + private final int[] jjrounds = new int[37]; + private final int[] jjstateSet = new int[74]; + protected char curChar; + + /** Constructor. */ + public ADQLParserTokenManager(SimpleCharStream stream){ + if (SimpleCharStream.staticFlag) + throw new Error("ERROR: Cannot use a static CharStream class with a non-static lexical analyzer."); + input_stream = stream; + } + + /** Constructor. */ + public ADQLParserTokenManager(SimpleCharStream stream, int lexState){ + this(stream); + SwitchTo(lexState); + } + + /** Reinitialise parser. */ + public void ReInit(SimpleCharStream stream){ + jjmatchedPos = jjnewStateCnt = 0; + curLexState = defaultLexState; + input_stream = stream; + ReInitRounds(); + } + + private void ReInitRounds(){ + int i; + jjround = 0x80000001; + for(i = 37; i-- > 0;) + jjrounds[i] = 0x80000000; + } + + /** Reinitialise parser. */ + public void ReInit(SimpleCharStream stream, int lexState){ + ReInit(stream); + SwitchTo(lexState); + } + + /** Switch to specified lex state. */ + public void SwitchTo(int lexState){ + if (lexState >= 4 || lexState < 0) + throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenMgrError.INVALID_LEXICAL_STATE); + else + curLexState = lexState; + } + + protected Token jjFillToken(){ + final Token t; + final String curTokenImage; + final int beginLine; + final int endLine; + final int beginColumn; + final int endColumn; + String im = jjstrLiteralImages[jjmatchedKind]; + curTokenImage = (im == null) ? input_stream.GetImage() : im; + beginLine = input_stream.getBeginLine(); + beginColumn = input_stream.getBeginColumn(); + endLine = input_stream.getEndLine(); + endColumn = input_stream.getEndColumn(); + t = Token.newToken(jjmatchedKind, curTokenImage); + + t.beginLine = beginLine; + t.endLine = endLine; + t.beginColumn = beginColumn; + t.endColumn = endColumn; + + return t; + } + + int curLexState = 0; + int defaultLexState = 0; + int jjnewStateCnt; + int jjround; + int jjmatchedPos; + int jjmatchedKind; + + /** Get the next Token. */ + public Token getNextToken(){ + Token matchedToken; + int curPos = 0; + + EOFLoop: for(;;){ + try{ + curChar = input_stream.BeginToken(); + }catch(java.io.IOException e){ + jjmatchedKind = 0; + matchedToken = jjFillToken(); + return matchedToken; + } + + for(;;){ + switch(curLexState){ + case 0: + jjmatchedKind = 0x7fffffff; + jjmatchedPos = 0; + curPos = jjMoveStringLiteralDfa0_0(); + break; + case 1: + jjmatchedKind = 0x7fffffff; + jjmatchedPos = 0; + curPos = jjMoveStringLiteralDfa0_1(); + if (jjmatchedPos == 0 && jjmatchedKind > 90){ + jjmatchedKind = 90; + } + break; + case 2: + jjmatchedKind = 0x7fffffff; + jjmatchedPos = 0; + curPos = jjMoveStringLiteralDfa0_2(); + break; + case 3: + jjmatchedKind = 0x7fffffff; + jjmatchedPos = 0; + curPos = jjMoveStringLiteralDfa0_3(); + break; + } + if (jjmatchedKind != 0x7fffffff){ + if (jjmatchedPos + 1 < curPos) + input_stream.backup(curPos - jjmatchedPos - 1); + if ((jjtoToken[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L){ + matchedToken = jjFillToken(); + if (jjnewLexState[jjmatchedKind] != -1) + curLexState = jjnewLexState[jjmatchedKind]; + return matchedToken; + }else if ((jjtoSkip[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L){ + if (jjnewLexState[jjmatchedKind] != -1) + curLexState = jjnewLexState[jjmatchedKind]; + continue EOFLoop; + } + if (jjnewLexState[jjmatchedKind] != -1) + curLexState = jjnewLexState[jjmatchedKind]; + curPos = 0; + jjmatchedKind = 0x7fffffff; + try{ + curChar = input_stream.readChar(); + continue; + }catch(java.io.IOException e1){} + } + int error_line = input_stream.getEndLine(); + int error_column = input_stream.getEndColumn(); + String error_after = null; + boolean EOFSeen = false; + try{ + input_stream.readChar(); + input_stream.backup(1); + }catch(java.io.IOException e1){ + EOFSeen = true; + error_after = curPos <= 1 ? "" : input_stream.GetImage(); + if (curChar == '\n' || curChar == '\r'){ + error_line++; + error_column = 0; + }else + error_column++; + } + if (!EOFSeen){ + input_stream.backup(1); + error_after = curPos <= 1 ? "" : input_stream.GetImage(); + } + throw new TokenMgrError(EOFSeen, curLexState, error_line, error_column, error_after, curChar, TokenMgrError.LEXICAL_ERROR); + } + } + } + + private void jjCheckNAdd(int state){ + if (jjrounds[state] != jjround){ + jjstateSet[jjnewStateCnt++] = state; + jjrounds[state] = jjround; + } + } + + private void jjAddStates(int start, int end){ + do{ + jjstateSet[jjnewStateCnt++] = jjnextStates[start]; + }while(start++ != end); + } + + private void jjCheckNAddTwoStates(int state1, int state2){ + jjCheckNAdd(state1); + jjCheckNAdd(state2); + } + + private void jjCheckNAddStates(int start, int end){ + do{ + jjCheckNAdd(jjnextStates[start]); + }while(start++ != end); + } } diff --git a/src/adql/parser/ADQLQueryFactory.java b/src/adql/parser/ADQLQueryFactory.java index 0bf1678985dceeb9c88c4a96567f6c6316ecc38a..daef3dc567acbd9ee71e4b6b6729220e0349fb4e 100644 --- a/src/adql/parser/ADQLQueryFactory.java +++ b/src/adql/parser/ADQLQueryFactory.java @@ -93,25 +93,23 @@ public class ADQLQueryFactory { protected boolean allowUnknownFunctions = false; - public static enum JoinType { - CROSS, - INNER, - OUTER_LEFT, - OUTER_RIGHT, - OUTER_FULL; + public static enum JoinType{ + CROSS, INNER, OUTER_LEFT, OUTER_RIGHT, OUTER_FULL; } - public ADQLQueryFactory(){ ; } + public ADQLQueryFactory(){ + ; + } public ADQLQueryFactory(boolean allowUnknownFunctions){ this.allowUnknownFunctions = allowUnknownFunctions; } - public ADQLQuery createQuery() throws Exception { + public ADQLQuery createQuery() throws Exception{ return new ADQLQuery(); } - public ADQLTable createTable(final IdentifierItems idItems, final IdentifierItem alias) throws Exception { + public ADQLTable createTable(final IdentifierItems idItems, final IdentifierItem alias) throws Exception{ ADQLTable t = new ADQLTable(idItems.getCatalog(), idItems.getSchema(), idItems.getTable()); // Set the table alias: @@ -130,7 +128,7 @@ public class ADQLQueryFactory { return t; } - public ADQLTable createTable(ADQLQuery query, IdentifierItem alias) throws Exception { + public ADQLTable createTable(ADQLQuery query, IdentifierItem alias) throws Exception{ ADQLTable t = new ADQLTable(query); if (alias != null){ @@ -143,50 +141,50 @@ public class ADQLQueryFactory { return t; } - public ADQLJoin createJoin(JoinType type, FromContent leftTable, FromContent rightTable) throws Exception { + public ADQLJoin createJoin(JoinType type, FromContent leftTable, FromContent rightTable) throws Exception{ switch(type){ - case CROSS: - return new CrossJoin(leftTable, rightTable); - case INNER: - return new InnerJoin(leftTable, rightTable); - case OUTER_LEFT: - return new OuterJoin(leftTable, rightTable, OuterType.LEFT); - case OUTER_RIGHT: - return new OuterJoin(leftTable, rightTable, OuterType.RIGHT); - case OUTER_FULL: - return new OuterJoin(leftTable, rightTable, OuterType.FULL); - default: - throw new Exception("Unknown join type: "+type); + case CROSS: + return new CrossJoin(leftTable, rightTable); + case INNER: + return new InnerJoin(leftTable, rightTable); + case OUTER_LEFT: + return new OuterJoin(leftTable, rightTable, OuterType.LEFT); + case OUTER_RIGHT: + return new OuterJoin(leftTable, rightTable, OuterType.RIGHT); + case OUTER_FULL: + return new OuterJoin(leftTable, rightTable, OuterType.FULL); + default: + throw new Exception("Unknown join type: " + type); } } - public ADQLJoin createJoin(JoinType type, FromContent leftTable, FromContent rightTable, ClauseConstraints condition) throws Exception { + public ADQLJoin createJoin(JoinType type, FromContent leftTable, FromContent rightTable, ClauseConstraints condition) throws Exception{ switch(type){ - case CROSS: - throw new Exception("A cross join must have no condition (that's to say: no part ON) !"); - default: - ADQLJoin join = createJoin(type, leftTable, rightTable); - join.setJoinCondition(condition); - return join; + case CROSS: + throw new Exception("A cross join must have no condition (that's to say: no part ON) !"); + default: + ADQLJoin join = createJoin(type, leftTable, rightTable); + join.setJoinCondition(condition); + return join; } } - public ADQLJoin createJoin(JoinType type, FromContent leftTable, FromContent rightTable, Collection<ADQLColumn> lstColumns) throws Exception { + public ADQLJoin createJoin(JoinType type, FromContent leftTable, FromContent rightTable, Collection<ADQLColumn> lstColumns) throws Exception{ switch(type){ - case CROSS: - throw new Exception("A cross join must have no columns list (that's to say: no part USING) !"); - default: - ADQLJoin join = createJoin(type, leftTable, rightTable); - join.setJoinedColumns(lstColumns); - return join; + case CROSS: + throw new Exception("A cross join must have no columns list (that's to say: no part USING) !"); + default: + ADQLJoin join = createJoin(type, leftTable, rightTable); + join.setJoinedColumns(lstColumns); + return join; } } - public SelectItem createSelectItem(ADQLOperand operand, String alias) throws Exception { + public SelectItem createSelectItem(ADQLOperand operand, String alias) throws Exception{ return new SelectItem(operand, alias); } - public ADQLColumn createColumn(final IdentifierItems idItems) throws Exception { + public ADQLColumn createColumn(final IdentifierItems idItems) throws Exception{ ADQLColumn col = new ADQLColumn(idItems.getCatalog(), idItems.getSchema(), idItems.getTable(), idItems.getColumn()); // Set the case sensitivity: @@ -198,7 +196,7 @@ public class ADQLQueryFactory { return col; } - public ADQLColumn createColumn(final IdentifierItem columnName) throws Exception { + public ADQLColumn createColumn(final IdentifierItem columnName) throws Exception{ ADQLColumn col = new ADQLColumn(null, null, null, columnName.identifier); // Set the case sensitivity: @@ -209,67 +207,67 @@ public class ADQLQueryFactory { return col; } - public NumericConstant createNumericConstant(String value) throws Exception { + public NumericConstant createNumericConstant(String value) throws Exception{ return new NumericConstant(value, true); } - public StringConstant createStringConstant(String value) throws Exception { + public StringConstant createStringConstant(String value) throws Exception{ return new StringConstant(value); } - public Operation createOperation(ADQLOperand leftOp, OperationType op, ADQLOperand rightOp) throws Exception { + public Operation createOperation(ADQLOperand leftOp, OperationType op, ADQLOperand rightOp) throws Exception{ return new Operation(leftOp, op, rightOp); } - public NegativeOperand createNegativeOperand(ADQLOperand opToNegativate) throws Exception { + public NegativeOperand createNegativeOperand(ADQLOperand opToNegativate) throws Exception{ return new NegativeOperand(opToNegativate); } - public Concatenation createConcatenation() throws Exception { + public Concatenation createConcatenation() throws Exception{ return new Concatenation(); } - public WrappedOperand createWrappedOperand(ADQLOperand opToWrap) throws Exception { + public WrappedOperand createWrappedOperand(ADQLOperand opToWrap) throws Exception{ return new WrappedOperand(opToWrap); } - public ConstraintsGroup createGroupOfConstraints() throws Exception { + public ConstraintsGroup createGroupOfConstraints() throws Exception{ return new ConstraintsGroup(); } - public NotConstraint createNot(ADQLConstraint constraintToNot) throws Exception { + public NotConstraint createNot(ADQLConstraint constraintToNot) throws Exception{ return new NotConstraint(constraintToNot); } - public Comparison createComparison(ADQLOperand leftOp, ComparisonOperator op, ADQLOperand rightOp) throws Exception { + public Comparison createComparison(ADQLOperand leftOp, ComparisonOperator op, ADQLOperand rightOp) throws Exception{ return new Comparison(leftOp, op, rightOp); } - public Between createBetween(boolean not, ADQLOperand value, ADQLOperand min, ADQLOperand max) throws Exception { + public Between createBetween(boolean not, ADQLOperand value, ADQLOperand min, ADQLOperand max) throws Exception{ return new Between(value, min, max, not); } - public IsNull createIsNull(boolean notNull, ADQLColumn column) throws Exception { + public IsNull createIsNull(boolean notNull, ADQLColumn column) throws Exception{ return new IsNull(column, notNull); } - public Exists createExists(ADQLQuery query) throws Exception { + public Exists createExists(ADQLQuery query) throws Exception{ return new Exists(query); } - public In createIn(ADQLOperand leftOp, ADQLQuery query, boolean notIn) throws Exception { + public In createIn(ADQLOperand leftOp, ADQLQuery query, boolean notIn) throws Exception{ return new In(leftOp, query, notIn); } - public In createIn(ADQLOperand leftOp, ADQLOperand[] valuesList, boolean notIn) throws Exception { + public In createIn(ADQLOperand leftOp, ADQLOperand[] valuesList, boolean notIn) throws Exception{ return new In(leftOp, valuesList, notIn); } - public SQLFunction createSQLFunction(SQLFunctionType type, ADQLOperand op, boolean distinctValues) throws Exception { + public SQLFunction createSQLFunction(SQLFunctionType type, ADQLOperand op, boolean distinctValues) throws Exception{ return new SQLFunction(type, op, distinctValues); } - public MathFunction createMathFunction(MathFunctionType type, ADQLOperand param1, ADQLOperand param2) throws Exception { + public MathFunction createMathFunction(MathFunctionType type, ADQLOperand param1, ADQLOperand param2) throws Exception{ return new MathFunction(type, param1, param2); } @@ -285,109 +283,109 @@ public class ADQLQueryFactory { * @throws Exception An {@link UnsupportedOperationException} by default, otherwise any other type of error may be * thrown if there is a problem while creating the function. */ - public UserDefinedFunction createUserDefinedFunction(String name, ADQLOperand[] params) throws Exception { + public UserDefinedFunction createUserDefinedFunction(String name, ADQLOperand[] params) throws Exception{ if (allowUnknownFunctions) return new DefaultUDF(name, params); else - throw new UnsupportedOperationException("No ADQL function called \""+name+"\" !"); + throw new UnsupportedOperationException("No ADQL function called \"" + name + "\" !"); } - public DistanceFunction createDistance(PointFunction point1, PointFunction point2) throws Exception { + public DistanceFunction createDistance(PointFunction point1, PointFunction point2) throws Exception{ return new DistanceFunction(new GeometryValue<PointFunction>(point1), new GeometryValue<PointFunction>(point2)); } - public DistanceFunction createDistance(GeometryValue<PointFunction> point1, GeometryValue<PointFunction> point2) throws Exception { + public DistanceFunction createDistance(GeometryValue<PointFunction> point1, GeometryValue<PointFunction> point2) throws Exception{ return new DistanceFunction(point1, point2); } - public PointFunction createPoint(ADQLOperand coordSys, ADQLOperand coords, ADQLOperand coords2) throws Exception { + public PointFunction createPoint(ADQLOperand coordSys, ADQLOperand coords, ADQLOperand coords2) throws Exception{ return new PointFunction(coordSys, coords, coords2); } - public BoxFunction createBox(ADQLOperand coordinateSystem, ADQLOperand firstCoord, ADQLOperand secondCoord, ADQLOperand boxWidth, ADQLOperand boxHeight) throws Exception { + public BoxFunction createBox(ADQLOperand coordinateSystem, ADQLOperand firstCoord, ADQLOperand secondCoord, ADQLOperand boxWidth, ADQLOperand boxHeight) throws Exception{ return new BoxFunction(coordinateSystem, firstCoord, secondCoord, boxWidth, boxHeight); } - public CircleFunction createCircle(ADQLOperand coordSys, ADQLOperand coord1, ADQLOperand coord2, ADQLOperand radius) throws Exception { + public CircleFunction createCircle(ADQLOperand coordSys, ADQLOperand coord1, ADQLOperand coord2, ADQLOperand radius) throws Exception{ return new CircleFunction(coordSys, coord1, coord2, radius); } - public CentroidFunction createCentroid(GeometryFunction param) throws Exception { + public CentroidFunction createCentroid(GeometryFunction param) throws Exception{ return new CentroidFunction(new GeometryValue<GeometryFunction>(param)); } - public CentroidFunction createCentroid(GeometryValue<GeometryFunction> param) throws Exception { + public CentroidFunction createCentroid(GeometryValue<GeometryFunction> param) throws Exception{ return new CentroidFunction(param); } - public RegionFunction createRegion(ADQLOperand param) throws Exception { + public RegionFunction createRegion(ADQLOperand param) throws Exception{ return new RegionFunction(param); } - public PolygonFunction createPolygon(ADQLOperand coordSys, Vector<ADQLOperand> coords) throws Exception { + public PolygonFunction createPolygon(ADQLOperand coordSys, Vector<ADQLOperand> coords) throws Exception{ return new PolygonFunction(coordSys, coords); } - public AreaFunction createArea(GeometryFunction param) throws Exception { + public AreaFunction createArea(GeometryFunction param) throws Exception{ return new AreaFunction(new GeometryValue<GeometryFunction>(param)); } - public AreaFunction createArea(GeometryValue<GeometryFunction> param) throws Exception { + public AreaFunction createArea(GeometryValue<GeometryFunction> param) throws Exception{ return new AreaFunction(param); } - public ExtractCoord createCoord1(PointFunction point) throws Exception { + public ExtractCoord createCoord1(PointFunction point) throws Exception{ return new ExtractCoord(1, new GeometryValue<PointFunction>(point)); } - public ExtractCoord createCoord1(ADQLColumn point) throws Exception { + public ExtractCoord createCoord1(ADQLColumn point) throws Exception{ return new ExtractCoord(1, new GeometryValue<PointFunction>(point)); } - public ExtractCoord createCoord2(PointFunction point) throws Exception { + public ExtractCoord createCoord2(PointFunction point) throws Exception{ return new ExtractCoord(2, new GeometryValue<PointFunction>(point)); } - public ExtractCoord createCoord2(ADQLColumn point) throws Exception { + public ExtractCoord createCoord2(ADQLColumn point) throws Exception{ return new ExtractCoord(2, new GeometryValue<PointFunction>(point)); } - public ExtractCoordSys createExtractCoordSys(GeometryFunction param) throws Exception { + public ExtractCoordSys createExtractCoordSys(GeometryFunction param) throws Exception{ return new ExtractCoordSys(new GeometryValue<GeometryFunction>(param)); } - public ExtractCoordSys createExtractCoordSys(ADQLColumn param) throws Exception { + public ExtractCoordSys createExtractCoordSys(ADQLColumn param) throws Exception{ return new ExtractCoordSys(new GeometryValue<GeometryFunction>(param)); } - public ExtractCoordSys createExtractCoordSys(GeometryValue<GeometryFunction> param) throws Exception { + public ExtractCoordSys createExtractCoordSys(GeometryValue<GeometryFunction> param) throws Exception{ return new ExtractCoordSys(new GeometryValue<GeometryFunction>(param)); } - public ContainsFunction createContains(GeometryFunction left, GeometryFunction right) throws Exception { + public ContainsFunction createContains(GeometryFunction left, GeometryFunction right) throws Exception{ return new ContainsFunction(new GeometryValue<GeometryFunction>(left), new GeometryValue<GeometryFunction>(right)); } - public ContainsFunction createContains(GeometryValue<GeometryFunction> left, GeometryValue<GeometryFunction> right) throws Exception { + public ContainsFunction createContains(GeometryValue<GeometryFunction> left, GeometryValue<GeometryFunction> right) throws Exception{ return new ContainsFunction(left, right); } - public IntersectsFunction createIntersects(GeometryFunction left, GeometryFunction right) throws Exception { + public IntersectsFunction createIntersects(GeometryFunction left, GeometryFunction right) throws Exception{ return new IntersectsFunction(new GeometryValue<GeometryFunction>(left), new GeometryValue<GeometryFunction>(right)); } - public IntersectsFunction createIntersects(GeometryValue<GeometryFunction> left, GeometryValue<GeometryFunction> right) throws Exception { + public IntersectsFunction createIntersects(GeometryValue<GeometryFunction> left, GeometryValue<GeometryFunction> right) throws Exception{ return new IntersectsFunction(left, right); } - public ADQLOrder createOrder(final int ind, final boolean desc, final TextPosition position) throws Exception { + public ADQLOrder createOrder(final int ind, final boolean desc, final TextPosition position) throws Exception{ ADQLOrder order = new ADQLOrder(ind, desc); if (order != null) order.setPosition(position); return order; } - public ADQLOrder createOrder(final IdentifierItems idItems, final boolean desc) throws Exception { + public ADQLOrder createOrder(final IdentifierItems idItems, final boolean desc) throws Exception{ ADQLOrder order = new ADQLOrder(idItems.join("."), desc); if (order != null){ order.setPosition(idItems.getPosition()); @@ -396,7 +394,7 @@ public class ADQLQueryFactory { return order; } - public ColumnReference createColRef(final IdentifierItems idItems) throws Exception { + public ColumnReference createColRef(final IdentifierItems idItems) throws Exception{ ColumnReference colRef = new ColumnReference(idItems.join(".")); if (colRef != null){ colRef.setPosition(idItems.getPosition()); @@ -405,7 +403,7 @@ public class ADQLQueryFactory { return colRef; } - public ColumnReference createColRef(final int index, final TextPosition position) throws Exception { + public ColumnReference createColRef(final int index, final TextPosition position) throws Exception{ ColumnReference colRef = new ColumnReference(index); if (colRef != null) colRef.setPosition(position); diff --git a/src/adql/parser/IdentifierItems.java b/src/adql/parser/IdentifierItems.java index 1e9cb0f54bf4f44fc6a3d43822cf027aa42e2740..293921bfd58005b375d91545321c5d33ed04a4ae 100644 --- a/src/adql/parser/IdentifierItems.java +++ b/src/adql/parser/IdentifierItems.java @@ -69,7 +69,6 @@ public class IdentifierItems { } } - /** All identifiers. The position of the different fields change in function of the number of elements. * If count=4: [0]=catalog, [1]=schema, [2]=table, [3]=column. */ private IdentifierItem[] identifiers = new IdentifierItem[4]; @@ -80,7 +79,6 @@ public class IdentifierItems { /** Indicates whether this {@link IdentifierItems} is supposed to represent a table name (true), or a column name (false). */ private boolean tableIdent = false; - /** * Builds an IdentifierItems by specifying it is a table or a column identifier. * @@ -97,7 +95,7 @@ public class IdentifierItems { * * @param item Additional item (may be null). */ - public void append(final IdentifierItem item) { + public void append(final IdentifierItem item){ if (count >= 4) return; identifiers[count++] = item; @@ -108,7 +106,9 @@ public class IdentifierItems { * * @return The number of identifiers. */ - public int size() { return count; } + public int size(){ + return count; + } /** * Gets the whole ind-th identifier/field. @@ -117,7 +117,9 @@ public class IdentifierItems { * * @return The wanted identifier/field. */ - public IdentifierItem get(final int ind) { return (ind < 0 || identifiers[ind] == null) ? null : identifiers[ind]; } + public IdentifierItem get(final int ind){ + return (ind < 0 || identifiers[ind] == null) ? null : identifiers[ind]; + } /** * Gets the value of the ind-th identifier/field. @@ -126,44 +128,74 @@ public class IdentifierItems { * * @return The value of the wanted identifier/field. */ - public String getIdentifier(final int ind) { return (ind < 0 || identifiers[ind] == null) ? null : identifiers[ind].identifier; } - public String getCatalog() { return getIdentifier(tableIdent ? (count-3) : (count-4)); } - public String getSchema() { return getIdentifier(tableIdent ? (count-2) : (count-3)); } - public String getTable() { return getIdentifier(tableIdent ? (count-1) : (count-2)); } - public String getColumn() { return getIdentifier(tableIdent ? -1 : (count-1)); } + public String getIdentifier(final int ind){ + return (ind < 0 || identifiers[ind] == null) ? null : identifiers[ind].identifier; + } + + public String getCatalog(){ + return getIdentifier(tableIdent ? (count - 3) : (count - 4)); + } + + public String getSchema(){ + return getIdentifier(tableIdent ? (count - 2) : (count - 3)); + } + + public String getTable(){ + return getIdentifier(tableIdent ? (count - 1) : (count - 2)); + } + + public String getColumn(){ + return getIdentifier(tableIdent ? -1 : (count - 1)); + } + + public int getBeginLine(){ + return (count == 0 || identifiers[0] == null) ? -1 : identifiers[0].position.beginLine; + } + + public int getEndLine(){ + return (count == 0 || identifiers[count - 1] == null) ? -1 : identifiers[count - 1].position.endLine; + } + + public int getBeginColumn(){ + return (count == 0 || identifiers[0] == null) ? -1 : identifiers[0].position.beginColumn; + } - public int getBeginLine() { return (count == 0 || identifiers[0] == null) ? -1 : identifiers[0].position.beginLine; } - public int getEndLine() { return (count == 0 || identifiers[count-1] == null) ? -1 : identifiers[count-1].position.endLine; } - public int getBeginColumn() { return (count == 0 || identifiers[0] == null) ? -1 : identifiers[0].position.beginColumn; } - public int getEndColumn() { return (count == 0 || identifiers[count-1] == null) ? -1 : identifiers[count-1].position.endColumn; } + public int getEndColumn(){ + return (count == 0 || identifiers[count - 1] == null) ? -1 : identifiers[count - 1].position.endColumn; + } - public TextPosition getPosition() { return new TextPosition(getBeginLine(), getBeginColumn(), getEndLine(), getEndColumn()); } + public TextPosition getPosition(){ + return new TextPosition(getBeginLine(), getBeginColumn(), getEndLine(), getEndColumn()); + } public byte getCaseSensitivity(){ byte sensitivity = IdentifierField.getFullCaseSensitive(false); if (count == 0) return sensitivity; - int ind = count-1; + int ind = count - 1; // COLUMN: if (!tableIdent){ if (identifiers[ind] != null) sensitivity = IdentifierField.COLUMN.setCaseSensitive(sensitivity, identifiers[ind].caseSensitivity); ind--; } - if (ind < 0) return sensitivity; + if (ind < 0) + return sensitivity; // TABLE: if (identifiers[ind] != null) sensitivity = IdentifierField.TABLE.setCaseSensitive(sensitivity, identifiers[ind].caseSensitivity); ind--; - if (ind < 0) return sensitivity; + if (ind < 0) + return sensitivity; // SCHEMA: if (identifiers[ind] != null) sensitivity = IdentifierField.SCHEMA.setCaseSensitive(sensitivity, identifiers[ind].caseSensitivity); ind--; - if (ind < 0) return sensitivity; + if (ind < 0) + return sensitivity; // CATALOG: if (identifiers[ind] != null) @@ -173,9 +205,9 @@ public class IdentifierItems { } public boolean getColumnCaseSensitivity(){ - if (count == 0 || tableIdent || identifiers[count-1] == null) + if (count == 0 || tableIdent || identifiers[count - 1] == null) return false; - return identifiers[count-1].caseSensitivity; + return identifiers[count - 1].caseSensitivity; } /** @@ -193,11 +225,11 @@ public class IdentifierItems { delim = ""; StringBuffer str = new StringBuffer(); - for(int i=0; i<count; i++){ + for(int i = 0; i < count; i++){ if (identifiers[i] != null){ if (str.length() > 0) str.append(delim); - str.append( (identifiers[i]==null) ? "" : identifiers[i].identifier ); + str.append((identifiers[i] == null) ? "" : identifiers[i].identifier); } } return str.toString(); diff --git a/src/adql/parser/ParseException.java b/src/adql/parser/ParseException.java index 50d2dbdd23ed39171169e1e8930ac90be4059738..fb440e49c031045c44c8607c1eaba226260b4665 100644 --- a/src/adql/parser/ParseException.java +++ b/src/adql/parser/ParseException.java @@ -32,11 +32,7 @@ public class ParseException extends Exception { * a new object of this type with the fields "currentToken", * "expectedTokenSequences", and "tokenImage" set. */ - public ParseException(Token currentTokenVal, - int[][] expectedTokenSequencesVal, - String[] tokenImageVal - ) - { + public ParseException(Token currentTokenVal, int[][] expectedTokenSequencesVal, String[] tokenImageVal){ super(initialise(currentTokenVal, expectedTokenSequencesVal, tokenImageVal)); currentToken = currentTokenVal; expectedTokenSequences = expectedTokenSequencesVal; @@ -55,12 +51,12 @@ public class ParseException extends Exception { * these constructors. */ - public ParseException() { + public ParseException(){ super(); } /** Constructor with message. */ - public ParseException(String message) { + public ParseException(String message){ super(message); } @@ -69,7 +65,6 @@ public class ParseException extends Exception { position = errorPosition; } - /** * This is the last token that has been consumed successfully. If * this object has been created due to a parse error, the token @@ -110,16 +105,16 @@ public class ParseException extends Exception { * from the parser) the correct error message * gets displayed. */ - private static String initialise(Token currentToken, int[][] expectedTokenSequences, String[] tokenImage) { + private static String initialise(Token currentToken, int[][] expectedTokenSequences, String[] tokenImage){ int maxSize = 0; // Build the list of expected tokens: StringBuffer expected = new StringBuffer(); - for (int i = 0; i < expectedTokenSequences.length; i++) { - if (maxSize < expectedTokenSequences[i].length) { + for(int i = 0; i < expectedTokenSequences.length; i++){ + if (maxSize < expectedTokenSequences[i].length){ maxSize = expectedTokenSequences[i].length; } - for (int j = 0; j < expectedTokenSequences[i].length; j++) { + for(int j = 0; j < expectedTokenSequences[i].length; j++){ expected.append(tokenImage[expectedTokenSequences[i][j]]); } expected.append(" "); @@ -129,9 +124,10 @@ public class ParseException extends Exception { StringBuffer msg = new StringBuffer(); msg.append(" Encountered \""); Token tok = currentToken.next; - for (int i = 0; i < maxSize; i++) { - if (i != 0) msg.append(' '); - if (tok.kind == 0) { + for(int i = 0; i < maxSize; i++){ + if (i != 0) + msg.append(' '); + if (tok.kind == 0){ msg.append(tokenImage[0]); break; } @@ -141,9 +137,9 @@ public class ParseException extends Exception { msg.append("\"."); // Append the expected tokens list: - if (expectedTokenSequences.length == 1) { + if (expectedTokenSequences.length == 1){ msg.append(" Was expecting: "); - } else { + }else{ msg.append(" Was expecting one of: "); } msg.append(expected); @@ -199,46 +195,45 @@ public class ParseException extends Exception { * when these raw version cannot be used as part of an ASCII * string literal. */ - static String add_escapes(String str) { + static String add_escapes(String str){ StringBuffer retval = new StringBuffer(); char ch; - for (int i = 0; i < str.length(); i++) { - switch (str.charAt(i)) - { - case 0 : - continue; - case '\b': - retval.append("\\b"); - continue; - case '\t': - retval.append("\\t"); - continue; - case '\n': - retval.append("\\n"); - continue; - case '\f': - retval.append("\\f"); - continue; - case '\r': - retval.append("\\r"); - continue; - case '\"': - retval.append("\\\""); - continue; - case '\'': - retval.append("\\\'"); - continue; - case '\\': - retval.append("\\\\"); - continue; - default: - if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) { - String s = "0000" + Integer.toString(ch, 16); - retval.append("\\u" + s.substring(s.length() - 4, s.length())); - } else { - retval.append(ch); - } - continue; + for(int i = 0; i < str.length(); i++){ + switch(str.charAt(i)){ + case 0: + continue; + case '\b': + retval.append("\\b"); + continue; + case '\t': + retval.append("\\t"); + continue; + case '\n': + retval.append("\\n"); + continue; + case '\f': + retval.append("\\f"); + continue; + case '\r': + retval.append("\\r"); + continue; + case '\"': + retval.append("\\\""); + continue; + case '\'': + retval.append("\\\'"); + continue; + case '\\': + retval.append("\\\\"); + continue; + default: + if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e){ + String s = "0000" + Integer.toString(ch, 16); + retval.append("\\u" + s.substring(s.length() - 4, s.length())); + }else{ + retval.append(ch); + } + continue; } } return retval.toString(); diff --git a/src/adql/parser/SimpleCharStream.java b/src/adql/parser/SimpleCharStream.java index 1f6fca798b207268513e6d1062efa7b431a62f1f..75e085ef5a00279df789c1687ce3e4e42b127446 100644 --- a/src/adql/parser/SimpleCharStream.java +++ b/src/adql/parser/SimpleCharStream.java @@ -8,465 +8,399 @@ package adql.parser; */ @SuppressWarnings("all") -public class SimpleCharStream -{ -/** Whether parser is static. */ - public static final boolean staticFlag = false; - int bufsize; - int available; - int tokenBegin; -/** Position in buffer. */ - public int bufpos = -1; - protected int bufline[]; - protected int bufcolumn[]; - - protected int column = 0; - protected int line = 1; - - protected boolean prevCharIsCR = false; - protected boolean prevCharIsLF = false; - - protected java.io.Reader inputStream; - - protected char[] buffer; - protected int maxNextCharInd = 0; - protected int inBuf = 0; - protected int tabSize = 8; - - protected void setTabSize(int i) { tabSize = i; } - protected int getTabSize(int i) { return tabSize; } - - - protected void ExpandBuff(boolean wrapAround) - { - char[] newbuffer = new char[bufsize + 2048]; - int newbufline[] = new int[bufsize + 2048]; - int newbufcolumn[] = new int[bufsize + 2048]; - - try - { - if (wrapAround) - { - System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); - System.arraycopy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos); - buffer = newbuffer; - - System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); - System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos); - bufline = newbufline; - - System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); - System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos); - bufcolumn = newbufcolumn; - - maxNextCharInd = (bufpos += (bufsize - tokenBegin)); - } - else - { - System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); - buffer = newbuffer; - - System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); - bufline = newbufline; - - System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); - bufcolumn = newbufcolumn; - - maxNextCharInd = (bufpos -= tokenBegin); - } - } - catch (Throwable t) - { - throw new Error(t.getMessage()); - } - - - bufsize += 2048; - available = bufsize; - tokenBegin = 0; - } - - protected void FillBuff() throws java.io.IOException - { - if (maxNextCharInd == available) - { - if (available == bufsize) - { - if (tokenBegin > 2048) - { - bufpos = maxNextCharInd = 0; - available = tokenBegin; - } - else if (tokenBegin < 0) - bufpos = maxNextCharInd = 0; - else - ExpandBuff(false); - } - else if (available > tokenBegin) - available = bufsize; - else if ((tokenBegin - available) < 2048) - ExpandBuff(true); - else - available = tokenBegin; - } - - int i; - try { - if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1) - { - inputStream.close(); - throw new java.io.IOException(); - } - else - maxNextCharInd += i; - return; - } - catch(java.io.IOException e) { - --bufpos; - backup(0); - if (tokenBegin == -1) - tokenBegin = bufpos; - throw e; - } - } - -/** Start. */ - public char BeginToken() throws java.io.IOException - { - tokenBegin = -1; - char c = readChar(); - tokenBegin = bufpos; - - return c; - } - - protected void UpdateLineColumn(char c) - { - column++; - - if (prevCharIsLF) - { - prevCharIsLF = false; - line += (column = 1); - } - else if (prevCharIsCR) - { - prevCharIsCR = false; - if (c == '\n') - { - prevCharIsLF = true; - } - else - line += (column = 1); - } - - switch (c) - { - case '\r' : - prevCharIsCR = true; - break; - case '\n' : - prevCharIsLF = true; - break; - case '\t' : - column--; - column += (tabSize - (column % tabSize)); - break; - default : - break; - } - - bufline[bufpos] = line; - bufcolumn[bufpos] = column; - } - -/** Read a character. */ - public char readChar() throws java.io.IOException - { - if (inBuf > 0) - { - --inBuf; - - if (++bufpos == bufsize) - bufpos = 0; - - return buffer[bufpos]; - } - - if (++bufpos >= maxNextCharInd) - FillBuff(); - - char c = buffer[bufpos]; - - UpdateLineColumn(c); - return c; - } - - @Deprecated - /** - * @deprecated - * @see #getEndColumn - */ - - public int getColumn() { - return bufcolumn[bufpos]; - } - - @Deprecated - /** - * @deprecated - * @see #getEndLine - */ - - public int getLine() { - return bufline[bufpos]; - } - - /** Get token end column number. */ - public int getEndColumn() { - return bufcolumn[bufpos]; - } - - /** Get token end line number. */ - public int getEndLine() { - return bufline[bufpos]; - } - - /** Get token beginning column number. */ - public int getBeginColumn() { - return bufcolumn[tokenBegin]; - } - - /** Get token beginning line number. */ - public int getBeginLine() { - return bufline[tokenBegin]; - } - -/** Backup a number of characters. */ - public void backup(int amount) { - - inBuf += amount; - if ((bufpos -= amount) < 0) - bufpos += bufsize; - } - - /** Constructor. */ - public SimpleCharStream(java.io.Reader dstream, int startline, - int startcolumn, int buffersize) - { - inputStream = dstream; - line = startline; - column = startcolumn - 1; - - available = bufsize = buffersize; - buffer = new char[buffersize]; - bufline = new int[buffersize]; - bufcolumn = new int[buffersize]; - } - - /** Constructor. */ - public SimpleCharStream(java.io.Reader dstream, int startline, - int startcolumn) - { - this(dstream, startline, startcolumn, 4096); - } - - /** Constructor. */ - public SimpleCharStream(java.io.Reader dstream) - { - this(dstream, 1, 1, 4096); - } - - /** Reinitialise. */ - public void ReInit(java.io.Reader dstream, int startline, - int startcolumn, int buffersize) - { - inputStream = dstream; - line = startline; - column = startcolumn - 1; - - if (buffer == null || buffersize != buffer.length) - { - available = bufsize = buffersize; - buffer = new char[buffersize]; - bufline = new int[buffersize]; - bufcolumn = new int[buffersize]; - } - prevCharIsLF = prevCharIsCR = false; - tokenBegin = inBuf = maxNextCharInd = 0; - bufpos = -1; - } - - /** Reinitialise. */ - public void ReInit(java.io.Reader dstream, int startline, - int startcolumn) - { - ReInit(dstream, startline, startcolumn, 4096); - } - - /** Reinitialise. */ - public void ReInit(java.io.Reader dstream) - { - ReInit(dstream, 1, 1, 4096); - } - /** Constructor. */ - public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline, - int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException - { - this(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize); - } - - /** Constructor. */ - public SimpleCharStream(java.io.InputStream dstream, int startline, - int startcolumn, int buffersize) - { - this(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize); - } - - /** Constructor. */ - public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline, - int startcolumn) throws java.io.UnsupportedEncodingException - { - this(dstream, encoding, startline, startcolumn, 4096); - } - - /** Constructor. */ - public SimpleCharStream(java.io.InputStream dstream, int startline, - int startcolumn) - { - this(dstream, startline, startcolumn, 4096); - } - - /** Constructor. */ - public SimpleCharStream(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException - { - this(dstream, encoding, 1, 1, 4096); - } - - /** Constructor. */ - public SimpleCharStream(java.io.InputStream dstream) - { - this(dstream, 1, 1, 4096); - } - - /** Reinitialise. */ - public void ReInit(java.io.InputStream dstream, String encoding, int startline, - int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException - { - ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize); - } - - /** Reinitialise. */ - public void ReInit(java.io.InputStream dstream, int startline, - int startcolumn, int buffersize) - { - ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize); - } - - /** Reinitialise. */ - public void ReInit(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException - { - ReInit(dstream, encoding, 1, 1, 4096); - } - - /** Reinitialise. */ - public void ReInit(java.io.InputStream dstream) - { - ReInit(dstream, 1, 1, 4096); - } - /** Reinitialise. */ - public void ReInit(java.io.InputStream dstream, String encoding, int startline, - int startcolumn) throws java.io.UnsupportedEncodingException - { - ReInit(dstream, encoding, startline, startcolumn, 4096); - } - /** Reinitialise. */ - public void ReInit(java.io.InputStream dstream, int startline, - int startcolumn) - { - ReInit(dstream, startline, startcolumn, 4096); - } - /** Get token literal value. */ - public String GetImage() - { - if (bufpos >= tokenBegin) - return new String(buffer, tokenBegin, bufpos - tokenBegin + 1); - else - return new String(buffer, tokenBegin, bufsize - tokenBegin) + - new String(buffer, 0, bufpos + 1); - } - - /** Get the suffix. */ - public char[] GetSuffix(int len) - { - char[] ret = new char[len]; - - if ((bufpos + 1) >= len) - System.arraycopy(buffer, bufpos - len + 1, ret, 0, len); - else - { - System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0, - len - bufpos - 1); - System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1); - } - - return ret; - } - - /** Reset buffer when finished. */ - public void Done() - { - buffer = null; - bufline = null; - bufcolumn = null; - } - - /** - * Method to adjust line and column numbers for the start of a token. - */ - public void adjustBeginLineColumn(int newLine, int newCol) - { - int start = tokenBegin; - int len; - - if (bufpos >= tokenBegin) - { - len = bufpos - tokenBegin + inBuf + 1; - } - else - { - len = bufsize - tokenBegin + bufpos + 1 + inBuf; - } - - int i = 0, j = 0, k = 0; - int nextColDiff = 0, columnDiff = 0; - - while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize]) - { - bufline[j] = newLine; - nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j]; - bufcolumn[j] = newCol + columnDiff; - columnDiff = nextColDiff; - i++; - } - - if (i < len) - { - bufline[j] = newLine++; - bufcolumn[j] = newCol + columnDiff; - - while (i++ < len) - { - if (bufline[j = start % bufsize] != bufline[++start % bufsize]) - bufline[j] = newLine++; - else - bufline[j] = newLine; - } - } - - line = bufline[j]; - column = bufcolumn[j]; - } +public class SimpleCharStream { + /** Whether parser is static. */ + public static final boolean staticFlag = false; + int bufsize; + int available; + int tokenBegin; + /** Position in buffer. */ + public int bufpos = -1; + protected int bufline[]; + protected int bufcolumn[]; + + protected int column = 0; + protected int line = 1; + + protected boolean prevCharIsCR = false; + protected boolean prevCharIsLF = false; + + protected java.io.Reader inputStream; + + protected char[] buffer; + protected int maxNextCharInd = 0; + protected int inBuf = 0; + protected int tabSize = 8; + + protected void setTabSize(int i){ + tabSize = i; + } + + protected int getTabSize(int i){ + return tabSize; + } + + protected void ExpandBuff(boolean wrapAround){ + char[] newbuffer = new char[bufsize + 2048]; + int newbufline[] = new int[bufsize + 2048]; + int newbufcolumn[] = new int[bufsize + 2048]; + + try{ + if (wrapAround){ + System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); + System.arraycopy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos); + buffer = newbuffer; + + System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); + System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos); + bufline = newbufline; + + System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); + System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos); + bufcolumn = newbufcolumn; + + maxNextCharInd = (bufpos += (bufsize - tokenBegin)); + }else{ + System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); + buffer = newbuffer; + + System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); + bufline = newbufline; + + System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); + bufcolumn = newbufcolumn; + + maxNextCharInd = (bufpos -= tokenBegin); + } + }catch(Throwable t){ + throw new Error(t.getMessage()); + } + + bufsize += 2048; + available = bufsize; + tokenBegin = 0; + } + + protected void FillBuff() throws java.io.IOException{ + if (maxNextCharInd == available){ + if (available == bufsize){ + if (tokenBegin > 2048){ + bufpos = maxNextCharInd = 0; + available = tokenBegin; + }else if (tokenBegin < 0) + bufpos = maxNextCharInd = 0; + else + ExpandBuff(false); + }else if (available > tokenBegin) + available = bufsize; + else if ((tokenBegin - available) < 2048) + ExpandBuff(true); + else + available = tokenBegin; + } + + int i; + try{ + if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1){ + inputStream.close(); + throw new java.io.IOException(); + }else + maxNextCharInd += i; + return; + }catch(java.io.IOException e){ + --bufpos; + backup(0); + if (tokenBegin == -1) + tokenBegin = bufpos; + throw e; + } + } + + /** Start. */ + public char BeginToken() throws java.io.IOException{ + tokenBegin = -1; + char c = readChar(); + tokenBegin = bufpos; + + return c; + } + + protected void UpdateLineColumn(char c){ + column++; + + if (prevCharIsLF){ + prevCharIsLF = false; + line += (column = 1); + }else if (prevCharIsCR){ + prevCharIsCR = false; + if (c == '\n'){ + prevCharIsLF = true; + }else + line += (column = 1); + } + + switch(c){ + case '\r': + prevCharIsCR = true; + break; + case '\n': + prevCharIsLF = true; + break; + case '\t': + column--; + column += (tabSize - (column % tabSize)); + break; + default: + break; + } + + bufline[bufpos] = line; + bufcolumn[bufpos] = column; + } + + /** Read a character. */ + public char readChar() throws java.io.IOException{ + if (inBuf > 0){ + --inBuf; + + if (++bufpos == bufsize) + bufpos = 0; + + return buffer[bufpos]; + } + + if (++bufpos >= maxNextCharInd) + FillBuff(); + + char c = buffer[bufpos]; + + UpdateLineColumn(c); + return c; + } + + @Deprecated + /** + * @deprecated + * @see #getEndColumn + */ + public int getColumn(){ + return bufcolumn[bufpos]; + } + + @Deprecated + /** + * @deprecated + * @see #getEndLine + */ + public int getLine(){ + return bufline[bufpos]; + } + + /** Get token end column number. */ + public int getEndColumn(){ + return bufcolumn[bufpos]; + } + + /** Get token end line number. */ + public int getEndLine(){ + return bufline[bufpos]; + } + + /** Get token beginning column number. */ + public int getBeginColumn(){ + return bufcolumn[tokenBegin]; + } + + /** Get token beginning line number. */ + public int getBeginLine(){ + return bufline[tokenBegin]; + } + + /** Backup a number of characters. */ + public void backup(int amount){ + + inBuf += amount; + if ((bufpos -= amount) < 0) + bufpos += bufsize; + } + + /** Constructor. */ + public SimpleCharStream(java.io.Reader dstream, int startline, int startcolumn, int buffersize){ + inputStream = dstream; + line = startline; + column = startcolumn - 1; + + available = bufsize = buffersize; + buffer = new char[buffersize]; + bufline = new int[buffersize]; + bufcolumn = new int[buffersize]; + } + + /** Constructor. */ + public SimpleCharStream(java.io.Reader dstream, int startline, int startcolumn){ + this(dstream, startline, startcolumn, 4096); + } + + /** Constructor. */ + public SimpleCharStream(java.io.Reader dstream){ + this(dstream, 1, 1, 4096); + } + + /** Reinitialise. */ + public void ReInit(java.io.Reader dstream, int startline, int startcolumn, int buffersize){ + inputStream = dstream; + line = startline; + column = startcolumn - 1; + + if (buffer == null || buffersize != buffer.length){ + available = bufsize = buffersize; + buffer = new char[buffersize]; + bufline = new int[buffersize]; + bufcolumn = new int[buffersize]; + } + prevCharIsLF = prevCharIsCR = false; + tokenBegin = inBuf = maxNextCharInd = 0; + bufpos = -1; + } + + /** Reinitialise. */ + public void ReInit(java.io.Reader dstream, int startline, int startcolumn){ + ReInit(dstream, startline, startcolumn, 4096); + } + + /** Reinitialise. */ + public void ReInit(java.io.Reader dstream){ + ReInit(dstream, 1, 1, 4096); + } + + /** Constructor. */ + public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline, int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException{ + this(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize); + } + + /** Constructor. */ + public SimpleCharStream(java.io.InputStream dstream, int startline, int startcolumn, int buffersize){ + this(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize); + } + + /** Constructor. */ + public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline, int startcolumn) throws java.io.UnsupportedEncodingException{ + this(dstream, encoding, startline, startcolumn, 4096); + } + + /** Constructor. */ + public SimpleCharStream(java.io.InputStream dstream, int startline, int startcolumn){ + this(dstream, startline, startcolumn, 4096); + } + + /** Constructor. */ + public SimpleCharStream(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException{ + this(dstream, encoding, 1, 1, 4096); + } + + /** Constructor. */ + public SimpleCharStream(java.io.InputStream dstream){ + this(dstream, 1, 1, 4096); + } + + /** Reinitialise. */ + public void ReInit(java.io.InputStream dstream, String encoding, int startline, int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException{ + ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize); + } + + /** Reinitialise. */ + public void ReInit(java.io.InputStream dstream, int startline, int startcolumn, int buffersize){ + ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize); + } + + /** Reinitialise. */ + public void ReInit(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException{ + ReInit(dstream, encoding, 1, 1, 4096); + } + + /** Reinitialise. */ + public void ReInit(java.io.InputStream dstream){ + ReInit(dstream, 1, 1, 4096); + } + + /** Reinitialise. */ + public void ReInit(java.io.InputStream dstream, String encoding, int startline, int startcolumn) throws java.io.UnsupportedEncodingException{ + ReInit(dstream, encoding, startline, startcolumn, 4096); + } + + /** Reinitialise. */ + public void ReInit(java.io.InputStream dstream, int startline, int startcolumn){ + ReInit(dstream, startline, startcolumn, 4096); + } + + /** Get token literal value. */ + public String GetImage(){ + if (bufpos >= tokenBegin) + return new String(buffer, tokenBegin, bufpos - tokenBegin + 1); + else + return new String(buffer, tokenBegin, bufsize - tokenBegin) + new String(buffer, 0, bufpos + 1); + } + + /** Get the suffix. */ + public char[] GetSuffix(int len){ + char[] ret = new char[len]; + + if ((bufpos + 1) >= len) + System.arraycopy(buffer, bufpos - len + 1, ret, 0, len); + else{ + System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0, len - bufpos - 1); + System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1); + } + + return ret; + } + + /** Reset buffer when finished. */ + public void Done(){ + buffer = null; + bufline = null; + bufcolumn = null; + } + + /** + * Method to adjust line and column numbers for the start of a token. + */ + public void adjustBeginLineColumn(int newLine, int newCol){ + int start = tokenBegin; + int len; + + if (bufpos >= tokenBegin){ + len = bufpos - tokenBegin + inBuf + 1; + }else{ + len = bufsize - tokenBegin + bufpos + 1 + inBuf; + } + + int i = 0, j = 0, k = 0; + int nextColDiff = 0, columnDiff = 0; + + while(i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize]){ + bufline[j] = newLine; + nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j]; + bufcolumn[j] = newCol + columnDiff; + columnDiff = nextColDiff; + i++; + } + + if (i < len){ + bufline[j] = newLine++; + bufcolumn[j] = newCol + columnDiff; + + while(i++ < len){ + if (bufline[j = start % bufsize] != bufline[++start % bufsize]) + bufline[j] = newLine++; + else + bufline[j] = newLine; + } + } + + line = bufline[j]; + column = bufcolumn[j]; + } } /* JavaCC - OriginalChecksum=42af0fefd9dd6e805cbddca0a6f8ad37 (do not edit this line) */ diff --git a/src/adql/parser/Token.java b/src/adql/parser/Token.java index 01453f0d3d10d2605253b8561bc1e8db0ecd22e2..dc75a77f3e4dccb21715ca726f582fd3a2d437d1 100644 --- a/src/adql/parser/Token.java +++ b/src/adql/parser/Token.java @@ -9,124 +9,119 @@ package adql.parser; @SuppressWarnings("all") public class Token implements java.io.Serializable { - /** - * The version identifier for this Serializable class. - * Increment only if the <i>serialized</i> form of the - * class changes. - */ - private static final long serialVersionUID = 1L; - - /** - * An integer that describes the kind of this token. This numbering - * system is determined by JavaCCParser, and a table of these numbers is - * stored in the file ...Constants.java. - */ - public int kind; - - /** The line number of the first character of this Token. */ - public int beginLine; - /** The column number of the first character of this Token. */ - public int beginColumn; - /** The line number of the last character of this Token. */ - public int endLine; - /** The column number of the last character of this Token. */ - public int endColumn; - - /** - * The string image of the token. - */ - public String image; - - /** - * A reference to the next regular (non-special) token from the input - * stream. If this is the last token from the input stream, or if the - * token manager has not read tokens beyond this one, this field is - * set to null. This is true only if this token is also a regular - * token. Otherwise, see below for a description of the contents of - * this field. - */ - public Token next; - - /** - * This field is used to access special tokens that occur prior to this - * token, but after the immediately preceding regular (non-special) token. - * If there are no such special tokens, this field is set to null. - * When there are more than one such special token, this field refers - * to the last of these special tokens, which in turn refers to the next - * previous special token through its specialToken field, and so on - * until the first special token (whose specialToken field is null). - * The next fields of special tokens refer to other special tokens that - * immediately follow it (without an intervening regular token). If there - * is no such token, this field is null. - */ - public Token specialToken; - - /** - * An optional attribute value of the Token. - * Tokens which are not used as syntactic sugar will often contain - * meaningful values that will be used later on by the compiler or - * interpreter. This attribute value is often different from the image. - * Any subclass of Token that actually wants to return a non-null value can - * override this method as appropriate. - */ - public Object getValue() { - return null; - } - - /** - * No-argument constructor - */ - public Token() {} - - /** - * Constructs a new token for the specified Image. - */ - public Token(int kind) - { - this(kind, null); - } - - /** - * Constructs a new token for the specified Image and Kind. - */ - public Token(int kind, String image) - { - this.kind = kind; - this.image = image; - } - - /** - * Returns the image. - */ - public String toString() - { - return image; - } - - /** - * Returns a new Token object, by default. However, if you want, you - * can create and return subclass objects based on the value of ofKind. - * Simply add the cases to the switch for all those special cases. - * For example, if you have a subclass of Token called IDToken that - * you want to create if ofKind is ID, simply add something like : - * - * case MyParserConstants.ID : return new IDToken(ofKind, image); - * - * to the following switch statement. Then you can cast matchedToken - * variable to the appropriate type and use sit in your lexical actions. - */ - public static Token newToken(int ofKind, String image) - { - switch(ofKind) - { - default : return new Token(ofKind, image); - } - } - - public static Token newToken(int ofKind) - { - return newToken(ofKind, null); - } + /** + * The version identifier for this Serializable class. + * Increment only if the <i>serialized</i> form of the + * class changes. + */ + private static final long serialVersionUID = 1L; + + /** + * An integer that describes the kind of this token. This numbering + * system is determined by JavaCCParser, and a table of these numbers is + * stored in the file ...Constants.java. + */ + public int kind; + + /** The line number of the first character of this Token. */ + public int beginLine; + /** The column number of the first character of this Token. */ + public int beginColumn; + /** The line number of the last character of this Token. */ + public int endLine; + /** The column number of the last character of this Token. */ + public int endColumn; + + /** + * The string image of the token. + */ + public String image; + + /** + * A reference to the next regular (non-special) token from the input + * stream. If this is the last token from the input stream, or if the + * token manager has not read tokens beyond this one, this field is + * set to null. This is true only if this token is also a regular + * token. Otherwise, see below for a description of the contents of + * this field. + */ + public Token next; + + /** + * This field is used to access special tokens that occur prior to this + * token, but after the immediately preceding regular (non-special) token. + * If there are no such special tokens, this field is set to null. + * When there are more than one such special token, this field refers + * to the last of these special tokens, which in turn refers to the next + * previous special token through its specialToken field, and so on + * until the first special token (whose specialToken field is null). + * The next fields of special tokens refer to other special tokens that + * immediately follow it (without an intervening regular token). If there + * is no such token, this field is null. + */ + public Token specialToken; + + /** + * An optional attribute value of the Token. + * Tokens which are not used as syntactic sugar will often contain + * meaningful values that will be used later on by the compiler or + * interpreter. This attribute value is often different from the image. + * Any subclass of Token that actually wants to return a non-null value can + * override this method as appropriate. + */ + public Object getValue(){ + return null; + } + + /** + * No-argument constructor + */ + public Token(){} + + /** + * Constructs a new token for the specified Image. + */ + public Token(int kind){ + this(kind, null); + } + + /** + * Constructs a new token for the specified Image and Kind. + */ + public Token(int kind, String image){ + this.kind = kind; + this.image = image; + } + + /** + * Returns the image. + */ + public String toString(){ + return image; + } + + /** + * Returns a new Token object, by default. However, if you want, you + * can create and return subclass objects based on the value of ofKind. + * Simply add the cases to the switch for all those special cases. + * For example, if you have a subclass of Token called IDToken that + * you want to create if ofKind is ID, simply add something like : + * + * case MyParserConstants.ID : return new IDToken(ofKind, image); + * + * to the following switch statement. Then you can cast matchedToken + * variable to the appropriate type and use sit in your lexical actions. + */ + public static Token newToken(int ofKind, String image){ + switch(ofKind){ + default: + return new Token(ofKind, image); + } + } + + public static Token newToken(int ofKind){ + return newToken(ofKind, null); + } } /* JavaCC - OriginalChecksum=d231e694113b489b136cc4eb57fc02f6 (do not edit this line) */ diff --git a/src/adql/parser/TokenMgrError.java b/src/adql/parser/TokenMgrError.java index 152db90ac5100957b182443f11a7c673eca2d0e7..6e875080474475d7cb8e71395dc12a0a47740423 100644 --- a/src/adql/parser/TokenMgrError.java +++ b/src/adql/parser/TokenMgrError.java @@ -11,8 +11,7 @@ package adql.parser; * */ @SuppressWarnings("all") -public class TokenMgrError extends Error -{ +public class TokenMgrError extends Error { /** * The version identifier for this Serializable class. @@ -61,46 +60,45 @@ public class TokenMgrError extends Error * Replaces unprintable characters by their escaped (or unicode escaped) * equivalents in the given string */ - protected static final String addEscapes(String str) { + protected static final String addEscapes(String str){ StringBuffer retval = new StringBuffer(); char ch; - for (int i = 0; i < str.length(); i++) { - switch (str.charAt(i)) - { - case 0 : - continue; - case '\b': - retval.append("\\b"); - continue; - case '\t': - retval.append("\\t"); - continue; - case '\n': - retval.append("\\n"); - continue; - case '\f': - retval.append("\\f"); - continue; - case '\r': - retval.append("\\r"); - continue; - case '\"': - retval.append("\\\""); - continue; - case '\'': - retval.append("\\\'"); - continue; - case '\\': - retval.append("\\\\"); - continue; - default: - if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) { - String s = "0000" + Integer.toString(ch, 16); - retval.append("\\u" + s.substring(s.length() - 4, s.length())); - } else { - retval.append(ch); - } - continue; + for(int i = 0; i < str.length(); i++){ + switch(str.charAt(i)){ + case 0: + continue; + case '\b': + retval.append("\\b"); + continue; + case '\t': + retval.append("\\t"); + continue; + case '\n': + retval.append("\\n"); + continue; + case '\f': + retval.append("\\f"); + continue; + case '\r': + retval.append("\\r"); + continue; + case '\"': + retval.append("\\\""); + continue; + case '\'': + retval.append("\\\'"); + continue; + case '\\': + retval.append("\\\\"); + continue; + default: + if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e){ + String s = "0000" + Integer.toString(ch, 16); + retval.append("\\u" + s.substring(s.length() - 4, s.length())); + }else{ + retval.append(ch); + } + continue; } } return retval.toString(); @@ -118,12 +116,8 @@ public class TokenMgrError extends Error * curchar : the offending character * Note: You can customize the lexical error message by modifying this method. */ - protected static String LexicalError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar) { - return("Lexical error at line " + - errorLine + ", column " + - errorColumn + ". Encountered: " + - (EOFSeen ? "<EOF> " : ("\"" + addEscapes(String.valueOf(curChar)) + "\"") + " (" + (int)curChar + "), ") + - "after : \"" + addEscapes(errorAfter) + "\""); + protected static String LexicalError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar){ + return ("Lexical error at line " + errorLine + ", column " + errorColumn + ". Encountered: " + (EOFSeen ? "<EOF> " : ("\"" + addEscapes(String.valueOf(curChar)) + "\"") + " (" + (int)curChar + "), ") + "after : \"" + addEscapes(errorAfter) + "\""); } /** @@ -135,7 +129,7 @@ public class TokenMgrError extends Error * * from this method for such cases in the release version of your parser. */ - public String getMessage() { + public String getMessage(){ return super.getMessage(); } @@ -162,17 +156,16 @@ public class TokenMgrError extends Error */ /** No arg constructor. */ - public TokenMgrError() { - } + public TokenMgrError(){} /** Constructor with message and reason. */ - public TokenMgrError(String message, int reason) { + public TokenMgrError(String message, int reason){ super(message); errorCode = reason; } /** Full Constructor. */ - public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) { + public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason){ this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason); this.errorLine = errorLine; this.errorColumn = errorColumn; diff --git a/src/adql/query/ADQLList.java b/src/adql/query/ADQLList.java index 12cbd212cbd2bd1b58928baa878ff06c8660f304..25d5933bdc4692b6e6297090ab6c902315fead9c 100644 --- a/src/adql/query/ADQLList.java +++ b/src/adql/query/ADQLList.java @@ -35,7 +35,7 @@ import java.util.Vector; * @see adql.query.operand.Operation * @see adql.query.operand.Concatenation */ -public abstract class ADQLList<T extends ADQLObject> implements ADQLObject, Iterable<T> { +public abstract class ADQLList< T extends ADQLObject > implements ADQLObject, Iterable<T> { /** Label of the list. */ private final String name; @@ -43,13 +43,12 @@ public abstract class ADQLList<T extends ADQLObject> implements ADQLObject, Iter /** List of ADQL items. */ private final Vector<T> list = new Vector<T>(); - /** * Builds an ADQLList with only its name. This name will always prefix the list. * * @param name Prefix/Name of this list. */ - protected ADQLList(String name) { + protected ADQLList(String name){ if (name != null){ name = name.trim(); if (name.length() == 0) @@ -67,7 +66,7 @@ public abstract class ADQLList<T extends ADQLObject> implements ADQLObject, Iter * @throws Exception If there is an error during the copy. */ @SuppressWarnings("unchecked") - protected ADQLList(ADQLList<T> toCopy) throws Exception { + protected ADQLList(ADQLList<T> toCopy) throws Exception{ this(toCopy.getName()); for(T obj : toCopy) add((T)obj.getCopy()); @@ -80,7 +79,7 @@ public abstract class ADQLList<T extends ADQLObject> implements ADQLObject, Iter * @return <i>true</i> if the given item has been successfully added, <i>false</i> otherwise. * @throws NullPointerException If the given item is <i>null</i>. */ - public boolean add(T item) throws NullPointerException { + public boolean add(T item) throws NullPointerException{ if (item == null) throw new NullPointerException("It is impossible to add NULL items to an ADQL clause !"); else @@ -95,7 +94,7 @@ public abstract class ADQLList<T extends ADQLObject> implements ADQLObject, Iter * @throws NullPointerException If the given item is <i>null</i>. * @throws ArrayIndexOutOfBoundsException If the index is out of range (index < 0 || index > size()). */ - public void add(int index, T item) throws NullPointerException, ArrayIndexOutOfBoundsException { + public void add(int index, T item) throws NullPointerException, ArrayIndexOutOfBoundsException{ if (item != null) list.add(index, item); else @@ -111,7 +110,7 @@ public abstract class ADQLList<T extends ADQLObject> implements ADQLObject, Iter * @throws NullPointerException If the given item is <i>null</i>. * @throws ArrayIndexOutOfBoundsException If the index is out of range (index < 0 || index > size()). */ - public T set(int index, T item) throws NullPointerException, ArrayIndexOutOfBoundsException { + public T set(int index, T item) throws NullPointerException, ArrayIndexOutOfBoundsException{ if (item != null) return list.set(index, item); else @@ -125,7 +124,7 @@ public abstract class ADQLList<T extends ADQLObject> implements ADQLObject, Iter * @return The corresponding ADQL item. * @throws ArrayIndexOutOfBoundsException If the index is out of range (index < 0 || index > size()). */ - public T get(int index) throws ArrayIndexOutOfBoundsException { + public T get(int index) throws ArrayIndexOutOfBoundsException{ return list.get(index); } @@ -136,7 +135,7 @@ public abstract class ADQLList<T extends ADQLObject> implements ADQLObject, Iter * @return The removed ADQL item. * @throws ArrayIndexOutOfBoundsException If the index is out of range (index < 0 || index > size()). */ - public T remove(int index) throws ArrayIndexOutOfBoundsException { + public T remove(int index) throws ArrayIndexOutOfBoundsException{ return list.remove(index); } @@ -165,20 +164,20 @@ public abstract class ADQLList<T extends ADQLObject> implements ADQLObject, Iter return list.isEmpty(); } - public String getName() { + public String getName(){ return name; } - public String toADQL() { - String adql = (getName()==null)?"":(getName()+" "); + public String toADQL(){ + String adql = (getName() == null) ? "" : (getName() + " "); - for(int i=0; i<size(); i++) - adql += ((i == 0)?"":(" "+getSeparator(i)+" ")) + get(i).toADQL(); + for(int i = 0; i < size(); i++) + adql += ((i == 0) ? "" : (" " + getSeparator(i) + " ")) + get(i).toADQL(); return adql; } - public Iterator<T> iterator() { + public Iterator<T> iterator(){ return list.iterator(); } @@ -220,16 +219,16 @@ public abstract class ADQLList<T extends ADQLObject> implements ADQLObject, Iter list = (ADQLList<ADQLObject>)lst; } - public boolean hasNext() { - return index+1 < list.size(); + public boolean hasNext(){ + return index + 1 < list.size(); } - public ADQLObject next() { + public ADQLObject next(){ removed = false; return list.get(++index); } - public void replace(ADQLObject replacer) throws UnsupportedOperationException, IllegalStateException { + public void replace(ADQLObject replacer) throws UnsupportedOperationException, IllegalStateException{ if (index <= -1) throw new IllegalStateException("replace(ADQLObject) impossible: next() has not yet been called !"); @@ -242,7 +241,7 @@ public abstract class ADQLList<T extends ADQLObject> implements ADQLObject, Iter list.set(index, replacer); } - public void remove() { + public void remove(){ if (index <= -1) throw new IllegalStateException("remove() impossible: next() has not yet been called !"); diff --git a/src/adql/query/ADQLOrder.java b/src/adql/query/ADQLOrder.java index d3f3000cb46846b5b4dc44e7936643f29ef0d157..718a959c299c10ba460c88c89e4c8a5dddd439c1 100644 --- a/src/adql/query/ADQLOrder.java +++ b/src/adql/query/ADQLOrder.java @@ -30,7 +30,6 @@ public class ADQLOrder extends ColumnReference { /** Gives an indication about how to order the results of a query. (<i>true</i> for DESCending, <i>false</i> for ASCending) */ private boolean descSorting = false; - /** * Builds an order indication with the index of the selected column on which an ASCending ordering will be done. * @@ -40,7 +39,7 @@ public class ADQLOrder extends ColumnReference { * * @see ADQLOrder#ADQLOrder(int, boolean) */ - public ADQLOrder(int colIndex) throws ArrayIndexOutOfBoundsException { + public ADQLOrder(int colIndex) throws ArrayIndexOutOfBoundsException{ this(colIndex, false); } @@ -52,7 +51,7 @@ public class ADQLOrder extends ColumnReference { * * @throws ArrayIndexOutOfBoundsException If the index is less or equal 0. */ - public ADQLOrder(int colIndex, boolean desc) throws ArrayIndexOutOfBoundsException { + public ADQLOrder(int colIndex, boolean desc) throws ArrayIndexOutOfBoundsException{ super(colIndex); descSorting = desc; } @@ -66,7 +65,7 @@ public class ADQLOrder extends ColumnReference { * * @see ADQLOrder#ADQLOrder(String, boolean) */ - public ADQLOrder(String colName) throws NullPointerException { + public ADQLOrder(String colName) throws NullPointerException{ this(colName, false); } @@ -78,7 +77,7 @@ public class ADQLOrder extends ColumnReference { * * @throws NullPointerException If the given name is <i>null</i> or is an empty string. */ - public ADQLOrder(String colName, boolean desc) throws NullPointerException { + public ADQLOrder(String colName, boolean desc) throws NullPointerException{ super(colName); descSorting = desc; } @@ -88,7 +87,7 @@ public class ADQLOrder extends ColumnReference { * * @param toCopy The ORDER BY item to copy. */ - public ADQLOrder(ADQLOrder toCopy) { + public ADQLOrder(ADQLOrder toCopy){ super(toCopy); descSorting = toCopy.descSorting; } @@ -98,7 +97,7 @@ public class ADQLOrder extends ColumnReference { * * @return <i>true</i> DESCending order, <i>false</i> ASCending order. */ - public boolean isDescSorting() { + public boolean isDescSorting(){ return descSorting; } @@ -110,9 +109,9 @@ public class ADQLOrder extends ColumnReference { * * @throws IndexOutOfBoundsException If the given index is less or equal 0. */ - public void setOrder(int colIndex, boolean desc) throws ArrayIndexOutOfBoundsException { + public void setOrder(int colIndex, boolean desc) throws ArrayIndexOutOfBoundsException{ if (colIndex <= 0) - throw new ArrayIndexOutOfBoundsException("Impossible to make a reference to the "+colIndex+"th column: a column index must be greater or equal 1 !"); + throw new ArrayIndexOutOfBoundsException("Impossible to make a reference to the " + colIndex + "th column: a column index must be greater or equal 1 !"); setColumnIndex(colIndex); descSorting = desc; @@ -126,8 +125,8 @@ public class ADQLOrder extends ColumnReference { * * @throws NullPointerException If the given name is <i>null</i> or is an empty string. */ - public void setOrder(String colName, boolean desc) throws NullPointerException { - if (colName == null) + public void setOrder(String colName, boolean desc) throws NullPointerException{ + if (colName == null) throw new NullPointerException("Impossible to make a reference: the given name is null or is an empty string !"); setColumnName(colName); @@ -135,18 +134,18 @@ public class ADQLOrder extends ColumnReference { } @Override - public ADQLObject getCopy() throws Exception { + public ADQLObject getCopy() throws Exception{ return new ADQLOrder(this); } @Override - public String getName() { - return super.getName()+(descSorting?" DESC":" ASC"); + public String getName(){ + return super.getName() + (descSorting ? " DESC" : " ASC"); } @Override public String toADQL(){ - return super.toADQL()+(descSorting?" DESC":" ASC"); + return super.toADQL() + (descSorting ? " DESC" : " ASC"); } } diff --git a/src/adql/query/ADQLQuery.java b/src/adql/query/ADQLQuery.java index fd1d409044f7836fb9a1e2e0bf2bb64da3a0d162..f868009b49c25e03b3ac96e3f9db248f39c84ffc 100644 --- a/src/adql/query/ADQLQuery.java +++ b/src/adql/query/ADQLQuery.java @@ -62,7 +62,6 @@ public class ADQLQuery implements ADQLObject { /** The ADQL clause ORDER BY. */ private ClauseADQL<ADQLOrder> orderBy; - /** * Builds an empty ADQL query. */ @@ -82,7 +81,7 @@ public class ADQLQuery implements ADQLObject { * @throws Exception If there is an error during the copy. */ @SuppressWarnings("unchecked") - public ADQLQuery(ADQLQuery toCopy) throws Exception { + public ADQLQuery(ADQLQuery toCopy) throws Exception{ select = (ClauseSelect)toCopy.select.getCopy(); from = (FromContent)toCopy.from.getCopy(); where = (ClauseConstraints)toCopy.where.getCopy(); @@ -111,7 +110,7 @@ public class ADQLQuery implements ADQLObject { * * @return Its SELECT clause. */ - public final ClauseSelect getSelect() { + public final ClauseSelect getSelect(){ return select; } @@ -122,7 +121,7 @@ public class ADQLQuery implements ADQLObject { * * @throws NullPointerException If the given SELECT clause is <i>null</i>. */ - public void setSelect(ClauseSelect newSelect) throws NullPointerException { + public void setSelect(ClauseSelect newSelect) throws NullPointerException{ if (newSelect == null) throw new NullPointerException("Impossible to replace the SELECT clause of a query by NULL !"); else @@ -134,7 +133,7 @@ public class ADQLQuery implements ADQLObject { * * @return Its FROM clause. */ - public final FromContent getFrom() { + public final FromContent getFrom(){ return from; } @@ -145,7 +144,7 @@ public class ADQLQuery implements ADQLObject { * * @throws NullPointerException If the given FROM clause is <i>null</i>. */ - public void setFrom(FromContent newFrom) throws NullPointerException { + public void setFrom(FromContent newFrom) throws NullPointerException{ if (newFrom == null) throw new NullPointerException("Impossible to replace the FROM clause of a query by NULL !"); else @@ -157,7 +156,7 @@ public class ADQLQuery implements ADQLObject { * * @return Its WHERE clause. */ - public final ClauseConstraints getWhere() { + public final ClauseConstraints getWhere(){ return where; } @@ -168,7 +167,7 @@ public class ADQLQuery implements ADQLObject { * * @throws NullPointerException If the given WHERE clause is <i>null</i>. */ - public void setWhere(ClauseConstraints newWhere) throws NullPointerException { + public void setWhere(ClauseConstraints newWhere) throws NullPointerException{ if (newWhere == null) where.clear(); else @@ -180,7 +179,7 @@ public class ADQLQuery implements ADQLObject { * * @return Its GROUP BY clause. */ - public final ClauseADQL<ColumnReference> getGroupBy() { + public final ClauseADQL<ColumnReference> getGroupBy(){ return groupBy; } @@ -190,7 +189,7 @@ public class ADQLQuery implements ADQLObject { * @param newGroupBy The new GROUP BY clause. * @throws NullPointerException If the given GROUP BY clause is <i>null</i>. */ - public void setGroupBy(ClauseADQL<ColumnReference> newGroupBy) throws NullPointerException { + public void setGroupBy(ClauseADQL<ColumnReference> newGroupBy) throws NullPointerException{ if (newGroupBy == null) groupBy.clear(); else @@ -202,7 +201,7 @@ public class ADQLQuery implements ADQLObject { * * @return Its HAVING clause. */ - public final ClauseConstraints getHaving() { + public final ClauseConstraints getHaving(){ return having; } @@ -212,7 +211,7 @@ public class ADQLQuery implements ADQLObject { * @param newHaving The new HAVING clause. * @throws NullPointerException If the given HAVING clause is <i>null</i>. */ - public void setHaving(ClauseConstraints newHaving) throws NullPointerException { + public void setHaving(ClauseConstraints newHaving) throws NullPointerException{ if (newHaving == null) having.clear(); else @@ -224,7 +223,7 @@ public class ADQLQuery implements ADQLObject { * * @return Its ORDER BY clause. */ - public final ClauseADQL<ADQLOrder> getOrderBy() { + public final ClauseADQL<ADQLOrder> getOrderBy(){ return orderBy; } @@ -234,18 +233,18 @@ public class ADQLQuery implements ADQLObject { * @param newOrderBy The new ORDER BY clause. * @throws NullPointerException If the given ORDER BY clause is <i>null</i>. */ - public void setOrderBy(ClauseADQL<ADQLOrder> newOrderBy) throws NullPointerException { + public void setOrderBy(ClauseADQL<ADQLOrder> newOrderBy) throws NullPointerException{ if (newOrderBy == null) orderBy.clear(); else orderBy = newOrderBy; } - public ADQLObject getCopy() throws Exception { + public ADQLObject getCopy() throws Exception{ return new ADQLQuery(this); } - public String getName() { + public String getName(){ return "{ADQL query}"; } @@ -298,32 +297,44 @@ public class ADQLQuery implements ADQLObject { } public ADQLIterator adqlIterator(){ - return new ADQLIterator() { + return new ADQLIterator(){ private int index = -1; private ClauseADQL<?> currentClause = null; - public ADQLObject next() { + public ADQLObject next(){ index++; switch(index){ - case 0: currentClause = select; break; - case 1: currentClause = null; return from; - case 2: currentClause = where; break; - case 3: currentClause = groupBy; break; - case 4: currentClause = having; break; - case 5: currentClause = orderBy; break; - default: - throw new NoSuchElementException(); + case 0: + currentClause = select; + break; + case 1: + currentClause = null; + return from; + case 2: + currentClause = where; + break; + case 3: + currentClause = groupBy; + break; + case 4: + currentClause = having; + break; + case 5: + currentClause = orderBy; + break; + default: + throw new NoSuchElementException(); } return currentClause; } - public boolean hasNext() { - return index+1 < 6; + public boolean hasNext(){ + return index + 1 < 6; } @SuppressWarnings("unchecked") - public void replace(ADQLObject replacer) throws UnsupportedOperationException, IllegalStateException { + public void replace(ADQLObject replacer) throws UnsupportedOperationException, IllegalStateException{ if (index <= -1) throw new IllegalStateException("replace(ADQLObject) impossible: next() has not yet been called !"); @@ -331,59 +342,59 @@ public class ADQLQuery implements ADQLObject { remove(); else{ switch(index){ - case 0: - if (replacer instanceof ClauseSelect) - select = (ClauseSelect)replacer; - else - throw new UnsupportedOperationException("Impossible to replace a ClauseSelect ("+select.toADQL()+") by a "+replacer.getClass().getName()+" ("+replacer.toADQL()+") !"); - break; - case 1: - if (replacer instanceof FromContent) - from = (FromContent)replacer; - else - throw new UnsupportedOperationException("Impossible to replace a FromContent ("+from.toADQL()+") by a "+replacer.getClass().getName()+" ("+replacer.toADQL()+") !"); - break; - case 2: - if (replacer instanceof ClauseConstraints) - where = (ClauseConstraints)replacer; - else - throw new UnsupportedOperationException("Impossible to replace a ClauseConstraints ("+where.toADQL()+") by a "+replacer.getClass().getName()+" ("+replacer.toADQL()+") !"); - break; - case 3: - if (replacer instanceof ClauseADQL) - groupBy = (ClauseADQL<ColumnReference>)replacer; - else - throw new UnsupportedOperationException("Impossible to replace a ClauseADQL ("+groupBy.toADQL()+") by a "+replacer.getClass().getName()+" ("+replacer.toADQL()+") !"); - break; - case 4: - if (replacer instanceof ClauseConstraints) - having = (ClauseConstraints)replacer; - else - throw new UnsupportedOperationException("Impossible to replace a ClauseConstraints ("+having.toADQL()+") by a "+replacer.getClass().getName()+" ("+replacer.toADQL()+") !"); - break; - case 5: - if (replacer instanceof ClauseADQL) - orderBy = (ClauseADQL<ADQLOrder>)replacer; - else - throw new UnsupportedOperationException("Impossible to replace a ClauseADQL ("+orderBy.toADQL()+") by a "+replacer.getClass().getName()+" ("+replacer.toADQL()+") !"); - break; + case 0: + if (replacer instanceof ClauseSelect) + select = (ClauseSelect)replacer; + else + throw new UnsupportedOperationException("Impossible to replace a ClauseSelect (" + select.toADQL() + ") by a " + replacer.getClass().getName() + " (" + replacer.toADQL() + ") !"); + break; + case 1: + if (replacer instanceof FromContent) + from = (FromContent)replacer; + else + throw new UnsupportedOperationException("Impossible to replace a FromContent (" + from.toADQL() + ") by a " + replacer.getClass().getName() + " (" + replacer.toADQL() + ") !"); + break; + case 2: + if (replacer instanceof ClauseConstraints) + where = (ClauseConstraints)replacer; + else + throw new UnsupportedOperationException("Impossible to replace a ClauseConstraints (" + where.toADQL() + ") by a " + replacer.getClass().getName() + " (" + replacer.toADQL() + ") !"); + break; + case 3: + if (replacer instanceof ClauseADQL) + groupBy = (ClauseADQL<ColumnReference>)replacer; + else + throw new UnsupportedOperationException("Impossible to replace a ClauseADQL (" + groupBy.toADQL() + ") by a " + replacer.getClass().getName() + " (" + replacer.toADQL() + ") !"); + break; + case 4: + if (replacer instanceof ClauseConstraints) + having = (ClauseConstraints)replacer; + else + throw new UnsupportedOperationException("Impossible to replace a ClauseConstraints (" + having.toADQL() + ") by a " + replacer.getClass().getName() + " (" + replacer.toADQL() + ") !"); + break; + case 5: + if (replacer instanceof ClauseADQL) + orderBy = (ClauseADQL<ADQLOrder>)replacer; + else + throw new UnsupportedOperationException("Impossible to replace a ClauseADQL (" + orderBy.toADQL() + ") by a " + replacer.getClass().getName() + " (" + replacer.toADQL() + ") !"); + break; } } } - public void remove() { + public void remove(){ if (index <= -1) throw new IllegalStateException("remove() impossible: next() has not yet been called !"); if (index == 0 || index == 1) - throw new UnsupportedOperationException("Impossible to remove a "+((index==0)?"SELECT":"FROM")+" clause from a query !"); + throw new UnsupportedOperationException("Impossible to remove a " + ((index == 0) ? "SELECT" : "FROM") + " clause from a query !"); else currentClause.clear(); } }; } - public String toADQL() { + public String toADQL(){ StringBuffer adql = new StringBuffer(select.toADQL()); adql.append("\nFROM ").append(from.toADQL()); diff --git a/src/adql/query/ClauseADQL.java b/src/adql/query/ClauseADQL.java index da158520b3cfb46f671ac70b62cef26903227e9a..1c3c90ad663d8bb67b656c558f4843a938db241d 100644 --- a/src/adql/query/ClauseADQL.java +++ b/src/adql/query/ClauseADQL.java @@ -25,12 +25,12 @@ package adql.query; * @author Grégory Mantelet (CDS) * @version 11/2010 */ -public class ClauseADQL<T extends ADQLObject> extends ADQLList<T> { +public class ClauseADQL< T extends ADQLObject > extends ADQLList<T> { /** * Builds an anonymous ClauseADQL. */ - public ClauseADQL() { + public ClauseADQL(){ super((String)null); } @@ -39,7 +39,7 @@ public class ClauseADQL<T extends ADQLObject> extends ADQLList<T> { * * @param name List label. */ - public ClauseADQL(String name) { + public ClauseADQL(String name){ super(name); } @@ -49,13 +49,13 @@ public class ClauseADQL<T extends ADQLObject> extends ADQLList<T> { * @param toCopy The ClauseADQL to copy. * @throws Exception If there is an unexpected error during the copy. */ - public ClauseADQL(ADQLList<T> toCopy) throws Exception { + public ClauseADQL(ADQLList<T> toCopy) throws Exception{ super(toCopy); } @SuppressWarnings("unchecked") @Override - public ADQLObject getCopy() throws Exception { + public ADQLObject getCopy() throws Exception{ return new ClauseADQL(this); } @@ -65,7 +65,7 @@ public class ClauseADQL<T extends ADQLObject> extends ADQLList<T> { * @see adql.query.ADQLList#getPossibleSeparators() */ @Override - public String[] getPossibleSeparators() { + public String[] getPossibleSeparators(){ return new String[]{","}; } @@ -75,9 +75,9 @@ public class ClauseADQL<T extends ADQLObject> extends ADQLList<T> { * @see adql.query.ADQLList#getSeparator(int) */ @Override - public String getSeparator(int index) throws ArrayIndexOutOfBoundsException { + public String getSeparator(int index) throws ArrayIndexOutOfBoundsException{ if (index <= 0 || index > size()) - throw new ArrayIndexOutOfBoundsException("Impossible to get the separator between the item "+(index-1)+" and "+index+" !"); + throw new ArrayIndexOutOfBoundsException("Impossible to get the separator between the item " + (index - 1) + " and " + index + " !"); else return ","; } diff --git a/src/adql/query/ClauseConstraints.java b/src/adql/query/ClauseConstraints.java index b991a16c01967750d9b819d953819c98406303e3..d4e305fe7794c96c254934f49196502919a89c54 100644 --- a/src/adql/query/ClauseConstraints.java +++ b/src/adql/query/ClauseConstraints.java @@ -59,7 +59,6 @@ public class ClauseConstraints extends ClauseADQL<ADQLConstraint> { * vSeparators.get(i) gives the separator between get(i-1) and get(i)). */ private Vector<String> vSeparators = new Vector<String>(); - /** * <p>Builds a constraints list with only its name (which will prefix the whole list).</p> * @@ -67,7 +66,7 @@ public class ClauseConstraints extends ClauseADQL<ADQLConstraint> { * * @param name The name/prefix of the list. */ - public ClauseConstraints(String name) { + public ClauseConstraints(String name){ super(name); defaultSeparator = OR; } @@ -83,7 +82,7 @@ public class ClauseConstraints extends ClauseADQL<ADQLConstraint> { * * @see ClauseConstraints#checkSeparator(String) */ - public ClauseConstraints(String name, String logicalSep) { + public ClauseConstraints(String name, String logicalSep){ super(name); defaultSeparator = checkSeparator(logicalSep); } @@ -96,7 +95,7 @@ public class ClauseConstraints extends ClauseADQL<ADQLConstraint> { * * @see ClauseConstraints#checkSeparator(String) */ - public ClauseConstraints(ClauseConstraints toCopy) throws Exception { + public ClauseConstraints(ClauseConstraints toCopy) throws Exception{ super(toCopy); defaultSeparator = checkSeparator(toCopy.defaultSeparator); } @@ -129,7 +128,7 @@ public class ClauseConstraints extends ClauseADQL<ADQLConstraint> { * @see ClauseConstraints#add(String, ADQLConstraint) */ @Override - public boolean add(ADQLConstraint constraint) throws NullPointerException { + public boolean add(ADQLConstraint constraint) throws NullPointerException{ return add(defaultSeparator, constraint); } @@ -138,7 +137,7 @@ public class ClauseConstraints extends ClauseADQL<ADQLConstraint> { * @see ClauseConstraints#add(int, String, ADQLConstraint) */ @Override - public void add(int index, ADQLConstraint constraint) throws NullPointerException, ArrayIndexOutOfBoundsException { + public void add(int index, ADQLConstraint constraint) throws NullPointerException, ArrayIndexOutOfBoundsException{ add(index, defaultSeparator, constraint); } @@ -154,7 +153,7 @@ public class ClauseConstraints extends ClauseADQL<ADQLConstraint> { * @see ADQLList#add(ADQLObject) * @see ClauseConstraints#checkSeparator(String) */ - public boolean add(String logicalSep, ADQLConstraint constraint) throws NullPointerException { + public boolean add(String logicalSep, ADQLConstraint constraint) throws NullPointerException{ boolean added = super.add(constraint); if (added && size() > 1) vSeparators.add(checkSeparator(logicalSep)); @@ -174,10 +173,10 @@ public class ClauseConstraints extends ClauseADQL<ADQLConstraint> { * @see ADQLList#add(int, ADQLObject) * @see ClauseConstraints#checkSeparator(String) */ - public void add(int index, String logicalSep, ADQLConstraint constraint) throws NullPointerException, ArrayIndexOutOfBoundsException { + public void add(int index, String logicalSep, ADQLConstraint constraint) throws NullPointerException, ArrayIndexOutOfBoundsException{ super.add(index, constraint); if (index > 0) - vSeparators.add(index-1, checkSeparator(logicalSep)); + vSeparators.add(index - 1, checkSeparator(logicalSep)); } /** @@ -185,7 +184,7 @@ public class ClauseConstraints extends ClauseADQL<ADQLConstraint> { * @see ClauseConstraints#set(int, String, ADQLConstraint) */ @Override - public ADQLConstraint set(int index, ADQLConstraint constraint) throws NullPointerException, ArrayIndexOutOfBoundsException { + public ADQLConstraint set(int index, ADQLConstraint constraint) throws NullPointerException, ArrayIndexOutOfBoundsException{ return set(index, null, constraint); } @@ -202,32 +201,32 @@ public class ClauseConstraints extends ClauseADQL<ADQLConstraint> { * * @see ADQLList#set(int, ADQLObject) */ - public ADQLConstraint set(int index, String logicalSep, ADQLConstraint constraint) throws NullPointerException, ArrayIndexOutOfBoundsException { + public ADQLConstraint set(int index, String logicalSep, ADQLConstraint constraint) throws NullPointerException, ArrayIndexOutOfBoundsException{ ADQLConstraint replaced = super.set(index, constraint); if (replaced != null && logicalSep != null && index > 0) - vSeparators.set(index-1, logicalSep); + vSeparators.set(index - 1, logicalSep); return replaced; } @Override - public void clear() { + public void clear(){ super.clear(); vSeparators.clear(); } @Override - public ADQLConstraint remove(int index) throws ArrayIndexOutOfBoundsException { + public ADQLConstraint remove(int index) throws ArrayIndexOutOfBoundsException{ ADQLConstraint removed = super.remove(index); if (removed != null) if (index > 0) - vSeparators.remove(index-1); + vSeparators.remove(index - 1); else if (index == 0) vSeparators.remove(index); return removed; } @Override - public ADQLObject getCopy() throws Exception { + public ADQLObject getCopy() throws Exception{ return new ClauseConstraints(this); } @@ -237,16 +236,16 @@ public class ClauseConstraints extends ClauseADQL<ADQLConstraint> { * @see adql.query.ADQLList#getPossibleSeparators() */ @Override - public String[] getPossibleSeparators() { - return new String[]{AND, OR}; + public String[] getPossibleSeparators(){ + return new String[]{AND,OR}; } @Override - public String getSeparator(int index) throws ArrayIndexOutOfBoundsException { + public String getSeparator(int index) throws ArrayIndexOutOfBoundsException{ if (index <= 0 || index > size()) - throw new ArrayIndexOutOfBoundsException("Impossible to get the logical separator between the item "+(index-1)+" and "+index+" !"); + throw new ArrayIndexOutOfBoundsException("Impossible to get the logical separator between the item " + (index - 1) + " and " + index + " !"); else - return vSeparators.get(index-1); + return vSeparators.get(index - 1); } } diff --git a/src/adql/query/ClauseSelect.java b/src/adql/query/ClauseSelect.java index 60634bf374f0652cb3b990752d623d37d31e0535..0f63247cea675a0485e877c6cee61b9853092053 100644 --- a/src/adql/query/ClauseSelect.java +++ b/src/adql/query/ClauseSelect.java @@ -41,11 +41,10 @@ public class ClauseSelect extends ClauseADQL<SelectItem> { /** The maximum number of returned rows. */ private int limit = -1; - /** * Builds an empty SELECT clause. */ - public ClauseSelect() { + public ClauseSelect(){ this(false, -1); } @@ -54,7 +53,7 @@ public class ClauseSelect extends ClauseADQL<SelectItem> { * * @param distinctColumns <i>true</i> means unique rows (= SELECT DISTINCT), <i>false</i> otherwise (= SELECT or = SELECT ALL). */ - public ClauseSelect(boolean distinctColumns) { + public ClauseSelect(boolean distinctColumns){ this(distinctColumns, -1); } @@ -63,7 +62,7 @@ public class ClauseSelect extends ClauseADQL<SelectItem> { * * @param limit Maximum number of returned rows (= SELECT TOP limit). */ - public ClauseSelect(int limit) { + public ClauseSelect(int limit){ this(false, limit); } @@ -73,7 +72,7 @@ public class ClauseSelect extends ClauseADQL<SelectItem> { * @param distinctColumns <i>true</i> means unique rows (= SELECT DISTINCT), <i>false</i> otherwise (= SELECT or = SELECT ALL). * @param limit Maximum number of returned rows (= SELECT TOP limit). */ - public ClauseSelect(boolean distinctColumns, int limit) { + public ClauseSelect(boolean distinctColumns, int limit){ super("SELECT"); distinct = distinctColumns; this.limit = limit; @@ -85,7 +84,7 @@ public class ClauseSelect extends ClauseADQL<SelectItem> { * @param toCopy The SELECT clause to copy. * @throws Exception If there is an error during the copy. */ - public ClauseSelect(ClauseSelect toCopy) throws Exception { + public ClauseSelect(ClauseSelect toCopy) throws Exception{ super(toCopy); distinct = toCopy.distinct; limit = toCopy.limit; @@ -155,7 +154,7 @@ public class ClauseSelect extends ClauseADQL<SelectItem> { * * @see SelectItem */ - public boolean add(ADQLOperand operand) throws NullPointerException { + public boolean add(ADQLOperand operand) throws NullPointerException{ if (operand == null) throw new NullPointerException("It is impossible to add NULL items to a SELECT clause !"); return add(new SelectItem(operand)); @@ -174,7 +173,7 @@ public class ClauseSelect extends ClauseADQL<SelectItem> { * * @see SelectItem */ - public void add(int index, ADQLOperand operand) throws NullPointerException, ArrayIndexOutOfBoundsException { + public void add(int index, ADQLOperand operand) throws NullPointerException, ArrayIndexOutOfBoundsException{ if (operand == null) throw new NullPointerException("It is impossible to add NULL items to a SELECT clause !"); add(index, new SelectItem(operand)); @@ -192,7 +191,7 @@ public class ClauseSelect extends ClauseADQL<SelectItem> { * @throws NullPointerException If the given item is <i>null</i>. * @throws ArrayIndexOutOfBoundsException If the index is out of range (index < 0 || index > size()). */ - public ADQLOperand set(int index, ADQLOperand operand) throws NullPointerException, ArrayIndexOutOfBoundsException { + public ADQLOperand set(int index, ADQLOperand operand) throws NullPointerException, ArrayIndexOutOfBoundsException{ if (operand == null) throw new NullPointerException("It is impossible to replace a SELECT item by a NULL item into a SELECT clause !"); SelectItem item = set(index, new SelectItem(operand)); @@ -206,7 +205,7 @@ public class ClauseSelect extends ClauseADQL<SelectItem> { * @return The corresponding operand. * @throws ArrayIndexOutOfBoundsException If the index is out of range (index < 0 || index > size()). */ - public ADQLOperand searchByIndex(int index) throws ArrayIndexOutOfBoundsException { + public ADQLOperand searchByIndex(int index) throws ArrayIndexOutOfBoundsException{ return get(index).getOperand(); } @@ -247,7 +246,7 @@ public class ClauseSelect extends ClauseADQL<SelectItem> { if (item.getAlias().equalsIgnoreCase(alias)) founds.add(item); } - } else { + }else{ if (item.isCaseSensitive()){ if (item.getAlias().equals(alias)) founds.add(item); @@ -262,21 +261,21 @@ public class ClauseSelect extends ClauseADQL<SelectItem> { } @Override - public ADQLObject getCopy() throws Exception { + public ADQLObject getCopy() throws Exception{ return new ClauseSelect(this); } @Override - public String toADQL() { + public String toADQL(){ String adql = null; - for(int i=0; i<size(); i++){ + for(int i = 0; i < size(); i++){ if (i == 0){ - adql = getName()+(distinct?" DISTINCT":"")+(hasLimit()?(" TOP "+limit):""); + adql = getName() + (distinct ? " DISTINCT" : "") + (hasLimit() ? (" TOP " + limit) : ""); }else - adql += " "+getSeparator(i); + adql += " " + getSeparator(i); - adql += " "+get(i).toADQL(); + adql += " " + get(i).toADQL(); } return adql; diff --git a/src/adql/query/ColumnReference.java b/src/adql/query/ColumnReference.java index 13ec3cf41fb10537c12b7fff82a69186737e0e05..3390e7a716bf975da31c15624fc55fa123d7ff65 100644 --- a/src/adql/query/ColumnReference.java +++ b/src/adql/query/ColumnReference.java @@ -51,7 +51,6 @@ public class ColumnReference implements ADQLObject { /** Indicates whether the column name/alias is case sensitive. */ private boolean caseSensitive = false; - /** * Builds a column reference with an index of a selected column. * @@ -59,9 +58,9 @@ public class ColumnReference implements ADQLObject { * * @throws ArrayIndexOutOfBoundsException If the given index is less or equal 0. */ - public ColumnReference(int index) throws ArrayIndexOutOfBoundsException { + public ColumnReference(int index) throws ArrayIndexOutOfBoundsException{ if (index <= 0) - throw new IndexOutOfBoundsException("Impossible to make a reference to the "+index+"th column: a column index must be greater or equal 1 !"); + throw new IndexOutOfBoundsException("Impossible to make a reference to the " + index + "th column: a column index must be greater or equal 1 !"); columnIndex = index; columnName = null; @@ -74,7 +73,7 @@ public class ColumnReference implements ADQLObject { * * @throws NullPointerException If the given name is <i>null</i> or is an empty string. */ - public ColumnReference(String colName) throws NullPointerException { + public ColumnReference(String colName) throws NullPointerException{ if (!setColumnName(colName)) throw new NullPointerException("Impossible to make a reference: the given column name is null or is an empty string !"); } @@ -84,7 +83,7 @@ public class ColumnReference implements ADQLObject { * * @param toCopy The column reference to copy. */ - public ColumnReference(ColumnReference toCopy) { + public ColumnReference(ColumnReference toCopy){ columnName = toCopy.columnName; caseSensitive = toCopy.caseSensitive; columnIndex = toCopy.columnIndex; @@ -104,7 +103,7 @@ public class ColumnReference implements ADQLObject { * * @param pos Position of this {@link ColumnReference}. */ - public void setPosition(final TextPosition pos) { + public void setPosition(final TextPosition pos){ position = pos; } @@ -113,7 +112,7 @@ public class ColumnReference implements ADQLObject { * * @return The index of the referenced column or <i>-1</i> if this column reference has been made with a column name/alias. */ - public final int getColumnIndex() { + public final int getColumnIndex(){ return columnIndex; } @@ -146,7 +145,7 @@ public class ColumnReference implements ADQLObject { * * @return The referenced column's name/alias or <i>null</i> if this column reference has been made with a column index. */ - public final String getColumnName() { + public final String getColumnName(){ return columnName; } @@ -162,9 +161,9 @@ public class ColumnReference implements ADQLObject { StringBuffer n = new StringBuffer(name); n.trimToSize(); - if (n.length() > 1 && n.charAt(0) == '\"' && n.charAt(name.length()-1) == '\"'){ + if (n.length() > 1 && n.charAt(0) == '\"' && n.charAt(name.length() - 1) == '\"'){ n.deleteCharAt(0); - n.deleteCharAt(n.length()-1); + n.deleteCharAt(n.length() - 1); n.trimToSize(); if (n.length() > 0) caseSensitive = true; @@ -201,7 +200,7 @@ public class ColumnReference implements ADQLObject { * * @return The corresponding {@link DBColumn} if {@link #getColumnName()} is a column name (not an alias), <i>null</i> otherwise. */ - public final DBColumn getDBLink() { + public final DBColumn getDBLink(){ return dbLink; } @@ -212,7 +211,7 @@ public class ColumnReference implements ADQLObject { * * @param dbLink Its corresponding {@link DBColumn} if {@link #getColumnName()} is a column name (not an alias), <i>null</i> otherwise. */ - public final void setDBLink(DBColumn dbLink) { + public final void setDBLink(DBColumn dbLink){ this.dbLink = dbLink; } @@ -221,7 +220,7 @@ public class ColumnReference implements ADQLObject { * * @return Its source table if {@link #getColumnName()} is a column name (not an alias), otherwise <i>null</i>. */ - public final ADQLTable getAdqlTable() { + public final ADQLTable getAdqlTable(){ return adqlTable; } @@ -232,16 +231,16 @@ public class ColumnReference implements ADQLObject { * * @param adqlTable Its source table if {@link #getColumnName()} is a column name (not an alias), <i>null</i> otherwise. */ - public final void setAdqlTable(ADQLTable adqlTable) { + public final void setAdqlTable(ADQLTable adqlTable){ this.adqlTable = adqlTable; } - public ADQLObject getCopy() throws Exception { + public ADQLObject getCopy() throws Exception{ return new ColumnReference(this); } - public String getName() { - return isIndex()?(columnIndex+""):columnName; + public String getName(){ + return isIndex() ? (columnIndex + "") : columnName; } public final ADQLIterator adqlIterator(){ @@ -249,7 +248,7 @@ public class ColumnReference implements ADQLObject { } public String toADQL(){ - return isIndex()?(""+columnIndex):(isCaseSensitive()?("\""+columnName+"\""):columnName); + return isIndex() ? ("" + columnIndex) : (isCaseSensitive() ? ("\"" + columnName + "\"") : columnName); } } diff --git a/src/adql/query/IdentifierField.java b/src/adql/query/IdentifierField.java index b487a8455149014ae67b0de421cf298f51cf9efa..8abb5ad09032c3ac06cb4bd017114fc7f82bd340 100644 --- a/src/adql/query/IdentifierField.java +++ b/src/adql/query/IdentifierField.java @@ -75,12 +75,8 @@ import adql.query.operand.ADQLColumn; * @see ADQLTable * @see ADQLColumn */ -public enum IdentifierField { - COLUMN(0), - TABLE(1), - SCHEMA(2), - CATALOG(3), - ALIAS(4); +public enum IdentifierField{ + COLUMN(0), TABLE(1), SCHEMA(2), CATALOG(3), ALIAS(4); private final byte nbShift; diff --git a/src/adql/query/NullADQLIterator.java b/src/adql/query/NullADQLIterator.java index f088bbc5c2cc7344230fbdb98d6876e03be93390..1363d2a826d75e84bc17d7218babcedca6ad41f2 100644 --- a/src/adql/query/NullADQLIterator.java +++ b/src/adql/query/NullADQLIterator.java @@ -29,12 +29,20 @@ import java.util.NoSuchElementException; */ public class NullADQLIterator implements ADQLIterator { - public boolean hasNext() { return false; } + public boolean hasNext(){ + return false; + } - public ADQLObject next() { throw new NoSuchElementException(); } + public ADQLObject next(){ + throw new NoSuchElementException(); + } - public void remove() { throw new UnsupportedOperationException(); } + public void remove(){ + throw new UnsupportedOperationException(); + } - public void replace(ADQLObject replacer) throws UnsupportedOperationException, IllegalStateException { throw new UnsupportedOperationException(); } + public void replace(ADQLObject replacer) throws UnsupportedOperationException, IllegalStateException{ + throw new UnsupportedOperationException(); + } } diff --git a/src/adql/query/SelectAllColumns.java b/src/adql/query/SelectAllColumns.java index 2170b3d50cd2e9d3a31c72f04e993240e3571544..b94159f7cbab1ec762e944c221661cc3aafcffe3 100644 --- a/src/adql/query/SelectAllColumns.java +++ b/src/adql/query/SelectAllColumns.java @@ -38,13 +38,12 @@ public final class SelectAllColumns extends SelectItem { /** The table whose all columns must be selected. */ private ADQLTable adqlTable = null; - /** * Builds a {@link SelectItem} which selects all columns available in the given ADQL query. * * @param query The query whose all available columns must be selected. */ - public SelectAllColumns(final ADQLQuery query) { + public SelectAllColumns(final ADQLQuery query){ super(null, null); this.query = query; } @@ -54,7 +53,7 @@ public final class SelectAllColumns extends SelectItem { * * @param table The table whose all available columns must be selected. */ - public SelectAllColumns(final ADQLTable table) { + public SelectAllColumns(final ADQLTable table){ super(null, null); adqlTable = table; } @@ -65,7 +64,7 @@ public final class SelectAllColumns extends SelectItem { * @param toCopy The {@link SelectAllColumns} to copy. * @throws Exception If there is an error during the copy. */ - public SelectAllColumns(SelectAllColumns toCopy) throws Exception { + public SelectAllColumns(SelectAllColumns toCopy) throws Exception{ super(toCopy); } @@ -106,7 +105,7 @@ public final class SelectAllColumns extends SelectItem { * * @param table An {@link ADQLTable} (MUST NOT BE NULL). */ - public final void setAdqlTable(final ADQLTable table) { + public final void setAdqlTable(final ADQLTable table){ if (table == null){ adqlTable = table; query = null; @@ -114,63 +113,61 @@ public final class SelectAllColumns extends SelectItem { } @Override - public final ADQLObject getCopy() throws Exception { + public final ADQLObject getCopy() throws Exception{ return new SelectAllColumns(this); } @Override - public final String getName() { + public final String getName(){ return "*"; } @Override public final ADQLIterator adqlIterator(){ - return new ADQLIterator() { + return new ADQLIterator(){ private boolean tableGot = (adqlTable == null); - public ADQLObject next() throws NoSuchElementException { + public ADQLObject next() throws NoSuchElementException{ if (tableGot) throw new NoSuchElementException(); tableGot = true; return adqlTable; } - public boolean hasNext() { + public boolean hasNext(){ return !tableGot; } - public void replace(ADQLObject replacer) throws UnsupportedOperationException, IllegalStateException { + public void replace(ADQLObject replacer) throws UnsupportedOperationException, IllegalStateException{ if (replacer == null) remove(); else if (!tableGot) throw new IllegalStateException("replace(ADQLObject) impossible: next() has not yet been called !"); else if (!(replacer instanceof ADQLTable)) - throw new IllegalStateException("Impossible to replace an ADQLTable by a "+replacer.getClass().getName()+" !"); + throw new IllegalStateException("Impossible to replace an ADQLTable by a " + replacer.getClass().getName() + " !"); else adqlTable = (ADQLTable)replacer; } - public void remove() { + public void remove(){ if (!tableGot) throw new IllegalStateException("remove() impossible: next() has not yet been called !"); else - throw new UnsupportedOperationException("Impossible to remove the only operand ("+adqlTable.toADQL()+") from a SelectItem ("+toADQL()+") !"); + throw new UnsupportedOperationException("Impossible to remove the only operand (" + adqlTable.toADQL() + ") from a SelectItem (" + toADQL() + ") !"); } }; } @Override - public final String toADQL() { - if (adqlTable != null) { + public final String toADQL(){ + if (adqlTable != null){ if (adqlTable.hasAlias()) - return (adqlTable.isCaseSensitive(IdentifierField.ALIAS) ? ("\""+adqlTable.getAlias()+"\"") : adqlTable.getAlias())+".*"; + return (adqlTable.isCaseSensitive(IdentifierField.ALIAS) ? ("\"" + adqlTable.getAlias() + "\"") : adqlTable.getAlias()) + ".*"; else - return adqlTable.getFullTableName()+".*"; + return adqlTable.getFullTableName() + ".*"; }else return "*"; } - - } diff --git a/src/adql/query/SelectItem.java b/src/adql/query/SelectItem.java index 43737638919e18bb9c65151fc0cf779a567416a9..595e762482a24502ce2db1bd7eb89d86e120b6eb 100644 --- a/src/adql/query/SelectItem.java +++ b/src/adql/query/SelectItem.java @@ -44,7 +44,6 @@ public class SelectItem implements ADQLObject { /** Indicates whether the alias is case sensitive (if yes, the alias is written between double-quotes). */ private boolean caseSensitive = false; - /** * Builds a SELECT item just with an operand. * @@ -71,7 +70,7 @@ public class SelectItem implements ADQLObject { * @param toCopy The SELECT item to copy. * @throws Exception If there is an error during the copy. */ - public SelectItem(SelectItem toCopy) throws Exception { + public SelectItem(SelectItem toCopy) throws Exception{ if (toCopy.getOperand() != null) operand = (ADQLOperand)toCopy.getOperand().getCopy(); else @@ -122,9 +121,9 @@ public class SelectItem implements ADQLObject { if (a.length() == 0){ alias = null; return; - }else if (a.length() > 1 && a.charAt(0) == '\"' && a.charAt(a.length()-1) == '\"'){ + }else if (a.length() > 1 && a.charAt(0) == '\"' && a.charAt(a.length() - 1) == '\"'){ a.deleteCharAt(0); - a.deleteCharAt(a.length()-1); + a.deleteCharAt(a.length() - 1); a.trimToSize(); if (a.length() == 0){ alias = null; @@ -154,51 +153,51 @@ public class SelectItem implements ADQLObject { caseSensitive = sensitive; } - public ADQLObject getCopy() throws Exception { + public ADQLObject getCopy() throws Exception{ return new SelectItem(this); } - public String getName() { - return hasAlias()?alias:operand.getName(); + public String getName(){ + return hasAlias() ? alias : operand.getName(); } public ADQLIterator adqlIterator(){ - return new ADQLIterator() { + return new ADQLIterator(){ private boolean operandGot = (operand == null); - public ADQLObject next() throws NoSuchElementException { + public ADQLObject next() throws NoSuchElementException{ if (operandGot) throw new NoSuchElementException(); operandGot = true; return operand; } - public boolean hasNext() { + public boolean hasNext(){ return !operandGot; } - public void replace(ADQLObject replacer) throws UnsupportedOperationException, IllegalStateException { + public void replace(ADQLObject replacer) throws UnsupportedOperationException, IllegalStateException{ if (replacer == null) remove(); else if (!operandGot) throw new IllegalStateException("replace(ADQLObject) impossible: next() has not yet been called !"); else if (!(replacer instanceof ADQLOperand)) - throw new IllegalStateException("Impossible to replace an ADQLOperand by a "+replacer.getClass().getName()+" !"); + throw new IllegalStateException("Impossible to replace an ADQLOperand by a " + replacer.getClass().getName() + " !"); else operand = (ADQLOperand)replacer; } - public void remove() { + public void remove(){ if (!operandGot) throw new IllegalStateException("remove() impossible: next() has not yet been called !"); else - throw new UnsupportedOperationException("Impossible to remove the only operand ("+operand.toADQL()+") from a SelectItem ("+toADQL()+") !"); + throw new UnsupportedOperationException("Impossible to remove the only operand (" + operand.toADQL() + ") from a SelectItem (" + toADQL() + ") !"); } }; } - public String toADQL() { + public String toADQL(){ StringBuffer adql = new StringBuffer(operand.toADQL()); if (hasAlias()){ adql.append(" AS "); diff --git a/src/adql/query/TextPosition.java b/src/adql/query/TextPosition.java index 42b05653e2096e1ce038922a5ae05c84b1a18383..e7d086aa64e47dc19cf36207904307e7f0debcaa 100644 --- a/src/adql/query/TextPosition.java +++ b/src/adql/query/TextPosition.java @@ -50,8 +50,8 @@ public class TextPosition { * @param column Begin column. */ public TextPosition(final int line, final int column){ - beginLine = (line<0)?-1:line; - beginColumn = (column<0)?-1:column; + beginLine = (line < 0) ? -1 : line; + beginColumn = (column < 0) ? -1 : column; endLine = endColumn = -1; } @@ -64,10 +64,10 @@ public class TextPosition { * @param endColumn End column. */ public TextPosition(final int beginLine, final int beginColumn, final int endLine, final int endColumn){ - this.beginLine = (beginLine<0)?-1:beginLine; - this.beginColumn = (beginColumn<0)?-1:beginColumn; - this.endLine = (endLine<0)?-1:endLine; - this.endColumn = (endColumn<0)?-1:endColumn; + this.beginLine = (beginLine < 0) ? -1 : beginLine; + this.beginColumn = (beginColumn < 0) ? -1 : beginColumn; + this.endLine = (endLine < 0) ? -1 : endLine; + this.endColumn = (endColumn < 0) ? -1 : endColumn; } /** @@ -76,7 +76,7 @@ public class TextPosition { * @param token The position will be the one of this token. */ public TextPosition(final Token token){ - this(token.beginLine, token.beginColumn, token.endLine, (token.endColumn<0)?-1:(token.endColumn+1)); + this(token.beginLine, token.beginColumn, token.endLine, (token.endColumn < 0) ? -1 : (token.endColumn + 1)); } /** @@ -86,7 +86,7 @@ public class TextPosition { * @param endToken End position. */ public TextPosition(final Token beginToken, final Token endToken){ - this(beginToken.beginLine, beginToken.beginColumn, endToken.endLine, (endToken.endColumn<0)?-1:(endToken.endColumn+1)); + this(beginToken.beginLine, beginToken.beginColumn, endToken.endLine, (endToken.endColumn < 0) ? -1 : (endToken.endColumn + 1)); } @Override @@ -94,9 +94,9 @@ public class TextPosition { if (beginLine == -1 && beginColumn == -1) return "[l.? c.?]"; else if (endLine == -1 && endColumn == -1) - return "[l."+beginLine+" c."+beginColumn+"]"; + return "[l." + beginLine + " c." + beginColumn + "]"; else - return "[l."+beginLine+" c."+beginColumn+" - l."+endLine+" c."+endColumn+"]"; + return "[l." + beginLine + " c." + beginColumn + " - l." + endLine + " c." + endColumn + "]"; } } diff --git a/src/adql/query/constraint/Between.java b/src/adql/query/constraint/Between.java index c624240a209b70e50246dfb38db436b670d1725b..28cecbd4ba60221013da2eefd92c275cd4cd3da1 100644 --- a/src/adql/query/constraint/Between.java +++ b/src/adql/query/constraint/Between.java @@ -49,7 +49,6 @@ public class Between implements ADQLConstraint { /** Indicates which predicate must be used: BETWEEN (<i>false</i>) or NOT BETWEEN (<i>true</i>). */ private boolean notBetween = false; - /** * Builds a BETWEEN constraints. * @@ -58,7 +57,7 @@ public class Between implements ADQLConstraint { * @param max The operand which represents the maximum value. * @throws NullPointerException If one of the given parameters is <i>null</i>. */ - public Between(ADQLOperand operand, ADQLOperand min, ADQLOperand max) throws NullPointerException { + public Between(ADQLOperand operand, ADQLOperand min, ADQLOperand max) throws NullPointerException{ this(operand, min, max, false); } @@ -71,7 +70,7 @@ public class Between implements ADQLConstraint { * @param notBetween <i>true</i> if the predicate NOT BETWEEN must be used or <i>false</i> for BETWEEN. * @throws NullPointerException If one of the given parameters is <i>null</i>. */ - public Between(ADQLOperand operand, ADQLOperand min, ADQLOperand max, boolean notBetween) throws NullPointerException { + public Between(ADQLOperand operand, ADQLOperand min, ADQLOperand max, boolean notBetween) throws NullPointerException{ setLeftOperand(operand); setMinOperand(min); setMaxOperand(max); @@ -84,7 +83,7 @@ public class Between implements ADQLConstraint { * @param toCopy The BETWEEN constraint to copy. * @throws Exception If there is an error during the copy. */ - public Between(Between toCopy) throws Exception { + public Between(Between toCopy) throws Exception{ setLeftOperand((ADQLOperand)toCopy.leftOperand.getCopy()); setMinOperand((ADQLOperand)toCopy.minOperand.getCopy()); setMaxOperand((ADQLOperand)toCopy.maxOperand.getCopy()); @@ -95,7 +94,7 @@ public class Between implements ADQLConstraint { * * @return Its left operand. */ - public final ADQLOperand getLeftOperand() { + public final ADQLOperand getLeftOperand(){ return leftOperand; } @@ -105,7 +104,7 @@ public class Between implements ADQLConstraint { * @param leftOperand Its new left operand. * @throws NullPointerException If the given operand is <i>null</i>. */ - public void setLeftOperand(ADQLOperand leftOperand) throws NullPointerException { + public void setLeftOperand(ADQLOperand leftOperand) throws NullPointerException{ this.leftOperand = leftOperand; } @@ -114,7 +113,7 @@ public class Between implements ADQLConstraint { * * @return Its minimum value. */ - public final ADQLOperand getMinOperand() { + public final ADQLOperand getMinOperand(){ return minOperand; } @@ -124,7 +123,7 @@ public class Between implements ADQLConstraint { * @param minOperand Its new minimum value. * @throws NullPointerException If the given operand is <i>null</i>. */ - public void setMinOperand(ADQLOperand minOperand) throws NullPointerException { + public void setMinOperand(ADQLOperand minOperand) throws NullPointerException{ this.minOperand = minOperand; } @@ -133,7 +132,7 @@ public class Between implements ADQLConstraint { * * @return Its maximum value. */ - public final ADQLOperand getMaxOperand() { + public final ADQLOperand getMaxOperand(){ return maxOperand; } @@ -143,7 +142,7 @@ public class Between implements ADQLConstraint { * @param maxOperand Its new maximum value. * @throws NullPointerException If the given operand is <i>null</i>. */ - public void setMaxOperand(ADQLOperand maxOperand) throws NullPointerException { + public void setMaxOperand(ADQLOperand maxOperand) throws NullPointerException{ this.maxOperand = maxOperand; } @@ -165,34 +164,37 @@ public class Between implements ADQLConstraint { this.notBetween = notBetween; } - public ADQLObject getCopy() throws Exception { + public ADQLObject getCopy() throws Exception{ return new Between(this); } - public String getName() { - return (isNotBetween()?"NOT ":"")+"BETWEEN"; + public String getName(){ + return (isNotBetween() ? "NOT " : "") + "BETWEEN"; } public ADQLIterator adqlIterator(){ - return new ADQLIterator() { + return new ADQLIterator(){ private int index = -1; - public ADQLObject next() { + public ADQLObject next(){ switch(++index){ - case 0: return leftOperand; - case 1: return minOperand; - case 2: return maxOperand; - default: - throw new NoSuchElementException(); + case 0: + return leftOperand; + case 1: + return minOperand; + case 2: + return maxOperand; + default: + throw new NoSuchElementException(); } } - public boolean hasNext() { - return index+1 < 3; + public boolean hasNext(){ + return index + 1 < 3; } - public void replace(ADQLObject replacer) throws UnsupportedOperationException, IllegalStateException { + public void replace(ADQLObject replacer) throws UnsupportedOperationException, IllegalStateException{ if (index <= -1) throw new IllegalStateException("replace(ADQLObject) impossible: next() has not yet been called !"); @@ -200,15 +202,21 @@ public class Between implements ADQLConstraint { remove(); else if (replacer instanceof ADQLOperand){ switch(index){ - case 0: leftOperand = (ADQLOperand)replacer; break; - case 1: minOperand = (ADQLOperand)replacer; break; - case 2: maxOperand = (ADQLOperand)replacer; break; + case 0: + leftOperand = (ADQLOperand)replacer; + break; + case 1: + minOperand = (ADQLOperand)replacer; + break; + case 2: + maxOperand = (ADQLOperand)replacer; + break; } }else - throw new UnsupportedOperationException("Impossible to replace an ADQLOperand by a "+replacer.getClass().getName()+" ("+replacer.toADQL()+") !"); + throw new UnsupportedOperationException("Impossible to replace an ADQLOperand by a " + replacer.getClass().getName() + " (" + replacer.toADQL() + ") !"); } - public void remove() { + public void remove(){ if (index <= -1) throw new IllegalStateException("remove() impossible: next() has not yet been called !"); else @@ -217,8 +225,8 @@ public class Between implements ADQLConstraint { }; } - public String toADQL() { - return leftOperand.toADQL()+" "+getName()+" "+minOperand.toADQL()+" AND "+maxOperand.toADQL(); + public String toADQL(){ + return leftOperand.toADQL() + " " + getName() + " " + minOperand.toADQL() + " AND " + maxOperand.toADQL(); } } diff --git a/src/adql/query/constraint/Comparison.java b/src/adql/query/constraint/Comparison.java index 1414b1ec02f7968c67a642fb29d92bfc84c69c97..8aeab2e2e1e1444d31003bcb9e2339307cf22907 100644 --- a/src/adql/query/constraint/Comparison.java +++ b/src/adql/query/constraint/Comparison.java @@ -44,7 +44,6 @@ public class Comparison implements ADQLConstraint { /** The right part of the comparison. */ private ADQLOperand rightOperand; - /** * Creates a comparison between two operands. * @@ -58,7 +57,7 @@ public class Comparison implements ADQLConstraint { * @see Comparison#setLeftOperand(ADQLOperand) * @see Comparison#setRightOperand(ADQLOperand) */ - public Comparison(ADQLOperand left, ComparisonOperator comp, ADQLOperand right) throws NullPointerException, UnsupportedOperationException { + public Comparison(ADQLOperand left, ComparisonOperator comp, ADQLOperand right) throws NullPointerException, UnsupportedOperationException{ setLeftOperand(left); setRightOperand(right); setOperation(comp); @@ -70,7 +69,7 @@ public class Comparison implements ADQLConstraint { * @param toCopy The comparison to copy. * @throws Exception If there is an error during the copy. */ - public Comparison(Comparison toCopy) throws Exception { + public Comparison(Comparison toCopy) throws Exception{ leftOperand = (ADQLOperand)toCopy.leftOperand.getCopy(); compOperator = toCopy.compOperator; rightOperand = (ADQLOperand)toCopy.rightOperand.getCopy(); @@ -81,7 +80,7 @@ public class Comparison implements ADQLConstraint { * * @return The left operand. */ - public final ADQLOperand getLeftOperand() { + public final ADQLOperand getLeftOperand(){ return leftOperand; } @@ -92,13 +91,13 @@ public class Comparison implements ADQLConstraint { * @throws NullPointerException If the given operand is <i>null</i>. * @throws UnsupportedOperationException If the type of the given operand is incompatible with the right operand and/or with the comparison operator. */ - public void setLeftOperand(ADQLOperand newLeftOperand) throws NullPointerException, UnsupportedOperationException { + public void setLeftOperand(ADQLOperand newLeftOperand) throws NullPointerException, UnsupportedOperationException{ if (newLeftOperand == null) - throw new NullPointerException("Impossible to update the left operand of the comparison ("+toADQL()+") with a NULL operand !"); + throw new NullPointerException("Impossible to update the left operand of the comparison (" + toADQL() + ") with a NULL operand !"); if (rightOperand != null && newLeftOperand.isNumeric() != rightOperand.isNumeric() && newLeftOperand.isString() != rightOperand.isString()) - throw new UnsupportedOperationException("Impossible to update the left operand of the comparison ("+toADQL()+") with \""+newLeftOperand.toADQL()+"\" because its type is not compatible with the type of the right operand !"); + throw new UnsupportedOperationException("Impossible to update the left operand of the comparison (" + toADQL() + ") with \"" + newLeftOperand.toADQL() + "\" because its type is not compatible with the type of the right operand !"); if (compOperator != null && newLeftOperand.isNumeric() && (compOperator == ComparisonOperator.LIKE || compOperator == ComparisonOperator.NOTLIKE)) - throw new UnsupportedOperationException("Impossible to update the left operand of the comparison ("+toADQL()+") with \""+newLeftOperand.toADQL()+"\" because the comparison operator "+compOperator.toADQL()+" is not applicable on numeric operands !"); + throw new UnsupportedOperationException("Impossible to update the left operand of the comparison (" + toADQL() + ") with \"" + newLeftOperand.toADQL() + "\" because the comparison operator " + compOperator.toADQL() + " is not applicable on numeric operands !"); leftOperand = newLeftOperand; } @@ -108,7 +107,7 @@ public class Comparison implements ADQLConstraint { * * @return The comparison operator. */ - public ComparisonOperator getOperator() { + public ComparisonOperator getOperator(){ return compOperator; } @@ -119,12 +118,11 @@ public class Comparison implements ADQLConstraint { * @throws NullPointerException If the given type is <i>null</i>. * @throws UnsupportedOperationException If the given type is incompatible with the two operands. */ - public void setOperation(ComparisonOperator newOperation) throws NullPointerException, UnsupportedOperationException { + public void setOperation(ComparisonOperator newOperation) throws NullPointerException, UnsupportedOperationException{ if (newOperation == null) - throw new NullPointerException("Impossible to update the comparison operator ("+compOperator.toADQL()+") with a NULL operand !"); - if ((!leftOperand.isString() || !rightOperand.isString()) - && (newOperation == ComparisonOperator.LIKE || newOperation == ComparisonOperator.NOTLIKE)) - throw new UnsupportedOperationException("Impossible to update the comparison operator"+((compOperator!=null)?(" ("+compOperator.toADQL()+")"):"")+" by "+newOperation.toADQL()+" because the two operands (\""+leftOperand.toADQL()+"\" & \""+rightOperand.toADQL()+"\") are not all Strings !"); + throw new NullPointerException("Impossible to update the comparison operator (" + compOperator.toADQL() + ") with a NULL operand !"); + if ((!leftOperand.isString() || !rightOperand.isString()) && (newOperation == ComparisonOperator.LIKE || newOperation == ComparisonOperator.NOTLIKE)) + throw new UnsupportedOperationException("Impossible to update the comparison operator" + ((compOperator != null) ? (" (" + compOperator.toADQL() + ")") : "") + " by " + newOperation.toADQL() + " because the two operands (\"" + leftOperand.toADQL() + "\" & \"" + rightOperand.toADQL() + "\") are not all Strings !"); compOperator = newOperation; } @@ -134,7 +132,7 @@ public class Comparison implements ADQLConstraint { * * @return The right operand. */ - public ADQLOperand getRightOperand() { + public ADQLOperand getRightOperand(){ return rightOperand; } @@ -145,31 +143,31 @@ public class Comparison implements ADQLConstraint { * @throws NullPointerException If the given operand is <i>null</i>. * @throws UnsupportedOperationException If the type of the given operand is incompatible with the left operand and/or with the comparison operator. */ - public void setRightOperand(ADQLOperand newRightOperand) throws NullPointerException, UnsupportedOperationException { + public void setRightOperand(ADQLOperand newRightOperand) throws NullPointerException, UnsupportedOperationException{ if (newRightOperand == null) - throw new NullPointerException("Impossible to update the right operand of the comparison ("+toADQL()+") with a NULL operand !"); + throw new NullPointerException("Impossible to update the right operand of the comparison (" + toADQL() + ") with a NULL operand !"); if (leftOperand != null && newRightOperand.isNumeric() != leftOperand.isNumeric() && newRightOperand.isString() != leftOperand.isString()) - throw new UnsupportedOperationException("Impossible to update the right operand of the comparison ("+toADQL()+") with \""+newRightOperand.toADQL()+"\" because its type is not compatible with the type of the left operand !"); + throw new UnsupportedOperationException("Impossible to update the right operand of the comparison (" + toADQL() + ") with \"" + newRightOperand.toADQL() + "\" because its type is not compatible with the type of the left operand !"); if (compOperator != null && newRightOperand.isNumeric() && (compOperator == ComparisonOperator.LIKE || compOperator == ComparisonOperator.NOTLIKE)) - throw new UnsupportedOperationException("Impossible to update the right operand of the comparison ("+toADQL()+") with \""+newRightOperand.toADQL()+"\" because the comparison operator "+compOperator.toADQL()+" is not applicable on numeric operands !"); + throw new UnsupportedOperationException("Impossible to update the right operand of the comparison (" + toADQL() + ") with \"" + newRightOperand.toADQL() + "\" because the comparison operator " + compOperator.toADQL() + " is not applicable on numeric operands !"); rightOperand = newRightOperand; } - public ADQLObject getCopy() throws Exception { + public ADQLObject getCopy() throws Exception{ return new Comparison(this); } - public String getName() { + public String getName(){ return compOperator.toADQL(); } public ADQLIterator adqlIterator(){ - return new ADQLIterator() { + return new ADQLIterator(){ private int index = -1; - public ADQLObject next() { + public ADQLObject next(){ index++; if (index == 0) return leftOperand; @@ -179,11 +177,11 @@ public class Comparison implements ADQLConstraint { throw new NoSuchElementException(); } - public boolean hasNext() { - return index+1 < 2; + public boolean hasNext(){ + return index + 1 < 2; } - public void replace(ADQLObject replacer) throws UnsupportedOperationException, IllegalStateException { + public void replace(ADQLObject replacer) throws UnsupportedOperationException, IllegalStateException{ if (index <= -1) throw new IllegalStateException("replace(ADQLObject) impossible: next() has not yet been called !"); @@ -195,10 +193,10 @@ public class Comparison implements ADQLConstraint { else if (index == 1) rightOperand = (ADQLOperand)replacer; }else - throw new UnsupportedOperationException("Impossible to replace an ADQLOperand by a "+replacer.getClass().getName()+" in a comparison !"); + throw new UnsupportedOperationException("Impossible to replace an ADQLOperand by a " + replacer.getClass().getName() + " in a comparison !"); } - public void remove() { + public void remove(){ if (index <= -1) throw new IllegalStateException("remove() impossible: next() has not yet been called !"); else @@ -207,8 +205,8 @@ public class Comparison implements ADQLConstraint { }; } - public String toADQL() { - return ((leftOperand == null)?"NULL":leftOperand.toADQL())+" "+((compOperator == null)?"NULL":compOperator.toADQL())+" "+((rightOperand == null)?"NULL":rightOperand.toADQL()); + public String toADQL(){ + return ((leftOperand == null) ? "NULL" : leftOperand.toADQL()) + " " + ((compOperator == null) ? "NULL" : compOperator.toADQL()) + " " + ((rightOperand == null) ? "NULL" : rightOperand.toADQL()); } } \ No newline at end of file diff --git a/src/adql/query/constraint/ComparisonOperator.java b/src/adql/query/constraint/ComparisonOperator.java index 154f3c59591ef90762aeb026d3ec73caece12a92..ac255dc3c427e814c3988fb8bf0d8eef80904b9c 100644 --- a/src/adql/query/constraint/ComparisonOperator.java +++ b/src/adql/query/constraint/ComparisonOperator.java @@ -27,17 +27,10 @@ package adql.query.constraint; * * @see Comparison */ -public enum ComparisonOperator { - EQUAL, - NOT_EQUAL, - LESS_THAN, - LESS_OR_EQUAL, - GREATER_THAN, - GREATER_OR_EQUAL, - LIKE, - NOTLIKE; +public enum ComparisonOperator{ + EQUAL, NOT_EQUAL, LESS_THAN, LESS_OR_EQUAL, GREATER_THAN, GREATER_OR_EQUAL, LIKE, NOTLIKE; - public static ComparisonOperator getOperator(String str) throws UnsupportedOperationException { + public static ComparisonOperator getOperator(String str) throws UnsupportedOperationException{ if (str.equalsIgnoreCase("=")) return EQUAL; else if (str.equalsIgnoreCase("!=") || str.equalsIgnoreCase("<>")) @@ -55,29 +48,29 @@ public enum ComparisonOperator { else if (str.equalsIgnoreCase("NOT LIKE")) return NOTLIKE; else - throw new UnsupportedOperationException("Comparison operator unknown: \""+str+"\" !"); + throw new UnsupportedOperationException("Comparison operator unknown: \"" + str + "\" !"); } public String toADQL(){ switch(this){ - case EQUAL: - return "="; - case NOT_EQUAL: - return "!="; - case LESS_THAN: - return "<"; - case LESS_OR_EQUAL: - return "<="; - case GREATER_THAN: - return ">"; - case GREATER_OR_EQUAL: - return ">="; - case LIKE: - return "LIKE"; - case NOTLIKE: - return "NOT LIKE"; - default: - return "???"; + case EQUAL: + return "="; + case NOT_EQUAL: + return "!="; + case LESS_THAN: + return "<"; + case LESS_OR_EQUAL: + return "<="; + case GREATER_THAN: + return ">"; + case GREATER_OR_EQUAL: + return ">="; + case LIKE: + return "LIKE"; + case NOTLIKE: + return "NOT LIKE"; + default: + return "???"; } } diff --git a/src/adql/query/constraint/ConstraintsGroup.java b/src/adql/query/constraint/ConstraintsGroup.java index 024d30ddfc241e4d8ec29b4241b49c96c429fb2d..e7c8b26498d4d747391fcac1aa035262e94818f8 100644 --- a/src/adql/query/constraint/ConstraintsGroup.java +++ b/src/adql/query/constraint/ConstraintsGroup.java @@ -30,7 +30,7 @@ import adql.query.ClauseConstraints; * * @see ClauseConstraints */ -public class ConstraintsGroup extends ClauseConstraints implements ADQLConstraint { +public class ConstraintsGroup extends ClauseConstraints implements ADQLConstraint { public ConstraintsGroup(){ super((String)null); @@ -41,15 +41,13 @@ public class ConstraintsGroup extends ClauseConstraints implements ADQLConstrain } @Override - public ADQLObject getCopy() throws Exception { + public ADQLObject getCopy() throws Exception{ return new ConstraintsGroup(this); } @Override - public String toADQL() { - return "("+super.toADQL()+")"; + public String toADQL(){ + return "(" + super.toADQL() + ")"; } - - } \ No newline at end of file diff --git a/src/adql/query/constraint/Exists.java b/src/adql/query/constraint/Exists.java index 24ec2febba2283ce01ea743336d98c978e79980c..363588ff01bd554ab862411ce7abb0c4e0129a20 100644 --- a/src/adql/query/constraint/Exists.java +++ b/src/adql/query/constraint/Exists.java @@ -38,7 +38,6 @@ public class Exists implements ADQLConstraint { /** The sub-query. */ private ADQLQuery subQuery; - /** * Builds an Exists constraint instance. * @@ -54,7 +53,7 @@ public class Exists implements ADQLConstraint { * @param toCopy The Exists constraint to copy. * @throws Exception If there is an error during the copy. */ - public Exists(Exists toCopy) throws Exception { + public Exists(Exists toCopy) throws Exception{ subQuery = (ADQLQuery)toCopy.subQuery.getCopy(); } @@ -73,38 +72,38 @@ public class Exists implements ADQLConstraint { * @param query Its new sub-query. * @throws NullPointerException If the given query is <i>null</i>. */ - public void setSubQuery(ADQLQuery query) throws NullPointerException { + public void setSubQuery(ADQLQuery query) throws NullPointerException{ if (query == null) throw new NullPointerException("Impossible to build an EXISTS constraint with a sub-query NULL !"); else subQuery = query; } - public ADQLObject getCopy() throws Exception { + public ADQLObject getCopy() throws Exception{ return new Exists(this); } - public String getName() { + public String getName(){ return "EXISTS"; } public ADQLIterator adqlIterator(){ - return new ADQLIterator() { + return new ADQLIterator(){ private boolean subQueryGot = (subQuery == null); - public ADQLObject next() { + public ADQLObject next(){ if (subQueryGot) throw new NoSuchElementException(); subQueryGot = true; return subQuery; } - public boolean hasNext() { + public boolean hasNext(){ return !subQueryGot; } - public void replace(ADQLObject replacer) throws UnsupportedOperationException, IllegalStateException { + public void replace(ADQLObject replacer) throws UnsupportedOperationException, IllegalStateException{ if (!subQueryGot) throw new IllegalStateException("replace(ADQLObject) impossible: next() has not yet been called !"); @@ -113,10 +112,10 @@ public class Exists implements ADQLConstraint { else if (replacer instanceof ADQLQuery) subQuery = (ADQLQuery)replacer; else - throw new UnsupportedOperationException("Impossible to replace an ADQLQuery by a "+replacer.getClass().getName()+" ("+replacer.toADQL()+") !"); + throw new UnsupportedOperationException("Impossible to replace an ADQLQuery by a " + replacer.getClass().getName() + " (" + replacer.toADQL() + ") !"); } - public void remove() { + public void remove(){ if (!subQueryGot) throw new IllegalStateException("remove() impossible: next() has not yet been called !"); else @@ -125,8 +124,8 @@ public class Exists implements ADQLConstraint { }; } - public String toADQL() { - return getName()+"("+subQuery.toADQL()+")"; + public String toADQL(){ + return getName() + "(" + subQuery.toADQL() + ")"; } } \ No newline at end of file diff --git a/src/adql/query/constraint/In.java b/src/adql/query/constraint/In.java index 3aae7ac1252ddc96ddd3ad59befff91db135993b..2ea7ffa10727f19d2530130f0cda0a0a442415b2 100644 --- a/src/adql/query/constraint/In.java +++ b/src/adql/query/constraint/In.java @@ -52,7 +52,6 @@ public class In implements ADQLConstraint { /** IN or NOT IN ? */ private boolean notIn = false; - /** * Builds an IN constraint with a sub-query. * @@ -60,7 +59,7 @@ public class In implements ADQLConstraint { * @param query A sub-query. * @throws NullPointerException If the given operand and/or the given sub-query is <i>null</i>. */ - public In(ADQLOperand op, ADQLQuery query) throws NullPointerException { + public In(ADQLOperand op, ADQLQuery query) throws NullPointerException{ this(op, query, false); } @@ -72,7 +71,7 @@ public class In implements ADQLConstraint { * @param notIn <i>true</i> for NOT IN, <i>false</i> for IN. * @throws NullPointerException If the given operand and/or the given sub-query is <i>null</i>. */ - public In(ADQLOperand op, ADQLQuery query, boolean notIn) throws NullPointerException { + public In(ADQLOperand op, ADQLQuery query, boolean notIn) throws NullPointerException{ setOperand(op); setSubQuery(query); setNotIn(notIn); @@ -85,7 +84,7 @@ public class In implements ADQLConstraint { * @param valuesList The values list. * @throws NullPointerException If the given operand is <i>null</i> and/or the given list is <i>null</i> or empty. */ - public In(ADQLOperand op, ADQLOperand[] valuesList) throws NullPointerException { + public In(ADQLOperand op, ADQLOperand[] valuesList) throws NullPointerException{ this(op, valuesList, false); } @@ -97,7 +96,7 @@ public class In implements ADQLConstraint { * @param notIn <i>true</i> for NOT IN, <i>false</i> for IN. * @throws NullPointerException If the given operand is <i>null</i> and/or the given list is <i>null</i> or empty. */ - public In(ADQLOperand op, ADQLOperand[] valuesList, boolean notIn) throws NullPointerException { + public In(ADQLOperand op, ADQLOperand[] valuesList, boolean notIn) throws NullPointerException{ setOperand(op); setValuesList(valuesList); setNotIn(notIn); @@ -110,7 +109,7 @@ public class In implements ADQLConstraint { * @param valuesList The values list. * @throws NullPointerException If the given operand is <i>null</i> and/or the given list is <i>null</i> or empty. */ - public In(ADQLOperand op, ADQLList<ADQLOperand> valuesList) throws NullPointerException { + public In(ADQLOperand op, ADQLList<ADQLOperand> valuesList) throws NullPointerException{ this(op, valuesList, false); } @@ -122,7 +121,7 @@ public class In implements ADQLConstraint { * @param notIn <i>true</i> for NOT IN, <i>false</i> for IN. * @throws NullPointerException If the given operand is <i>null</i> and/or the given list is <i>null</i> or empty. */ - public In(ADQLOperand op, ADQLList<ADQLOperand> valuesList, boolean notIn) throws NullPointerException { + public In(ADQLOperand op, ADQLList<ADQLOperand> valuesList, boolean notIn) throws NullPointerException{ setOperand(op); setValuesList(valuesList); setNotIn(notIn); @@ -135,7 +134,7 @@ public class In implements ADQLConstraint { * @throws Exception If there is an error during the copy. */ @SuppressWarnings("unchecked") - public In(In toCopy) throws Exception { + public In(In toCopy) throws Exception{ leftOp = (ADQLOperand)toCopy.leftOp.getCopy(); if (toCopy.hasSubQuery()) setSubQuery((ADQLQuery)toCopy.subQuery.getCopy()); @@ -159,7 +158,7 @@ public class In implements ADQLConstraint { * @param newLeftOp Its new left operand. * @throws NullPointerException If the given operand is <i>null</i>. */ - public void setOperand(ADQLOperand newLeftOp) throws NullPointerException { + public void setOperand(ADQLOperand newLeftOp) throws NullPointerException{ if (newLeftOp == null) throw new NullPointerException("Impossible to set a left operand NULL in an IN constraint !"); else @@ -190,7 +189,7 @@ public class In implements ADQLConstraint { * @param newSubQuery Its new sub-query. * @throws NullPointerException If the given sub-query is <i>null</i>. */ - public void setSubQuery(ADQLQuery newSubQuery) throws NullPointerException { + public void setSubQuery(ADQLQuery newSubQuery) throws NullPointerException{ if (newSubQuery == null) throw new NullPointerException("Impossible to set a sub-query NULL in an IN constraint !"); else{ @@ -214,13 +213,13 @@ public class In implements ADQLConstraint { * @param valuesList Its new values list. * @throws NullPointerException If the given list is <i>null</i>. */ - public void setValuesList(ADQLOperand[] valuesList) throws NullPointerException { + public void setValuesList(ADQLOperand[] valuesList) throws NullPointerException{ if (valuesList == null) throw new NullPointerException("Impossible to set a values list NULL in an IN constraint !"); else if (valuesList.length > 0){ subQuery = null; list = new ClauseADQL<ADQLOperand>(); - for(int i=0; i<valuesList.length; i++) + for(int i = 0; i < valuesList.length; i++) list.add(valuesList[i]); } } @@ -231,7 +230,7 @@ public class In implements ADQLConstraint { * @param valuesList Its new values list. * @throws NullPointerException If the given list is <i>null</i>. */ - public void setValuesList(ADQLList<ADQLOperand> valuesList) throws NullPointerException { + public void setValuesList(ADQLList<ADQLOperand> valuesList) throws NullPointerException{ if (valuesList == null) throw new NullPointerException("Impossible to set a values list NULL in an IN constraint !"); else{ @@ -258,35 +257,35 @@ public class In implements ADQLConstraint { this.notIn = notIn; } - public ADQLObject getCopy() throws Exception { + public ADQLObject getCopy() throws Exception{ return new In(this); } - public String getName() { - return notIn?"NOT IN":"IN"; + public String getName(){ + return notIn ? "NOT IN" : "IN"; } public ADQLIterator adqlIterator(){ - return new ADQLIterator() { + return new ADQLIterator(){ private int index = -1; - public ADQLObject next() { + public ADQLObject next(){ index++; if (index == 0) return leftOp; else if (index == 1) - return hasSubQuery()?subQuery:list; + return hasSubQuery() ? subQuery : list; else throw new NoSuchElementException(); } - public boolean hasNext() { - return index+1 < 2; + public boolean hasNext(){ + return index + 1 < 2; } @SuppressWarnings("unchecked") - public void replace(ADQLObject replacer) throws UnsupportedOperationException, IllegalStateException { + public void replace(ADQLObject replacer) throws UnsupportedOperationException, IllegalStateException{ if (index <= -1) throw new IllegalStateException("replace(ADQLObject) impossible: next() has not yet been called !"); @@ -297,31 +296,31 @@ public class In implements ADQLConstraint { if (replacer instanceof ADQLOperand) leftOp = (ADQLOperand)replacer; else - throw new UnsupportedOperationException("Impossible to replace an ADQLOperand by a "+replacer.getClass().getName()+" ("+replacer.toADQL()+") !"); + throw new UnsupportedOperationException("Impossible to replace an ADQLOperand by a " + replacer.getClass().getName() + " (" + replacer.toADQL() + ") !"); }else if (index == 1){ if (hasSubQuery() && replacer instanceof ADQLQuery) subQuery = (ADQLQuery)replacer; else if (!hasSubQuery() && replacer instanceof ADQLList) list = (ADQLList<ADQLOperand>)replacer; else - throw new UnsupportedOperationException("Impossible to replace an "+(hasSubQuery()?"ADQLQuery":"ADQLList<ADQLOperand>")+" by a "+replacer.getClass().getName()+" ("+replacer.toADQL()+") !"); + throw new UnsupportedOperationException("Impossible to replace an " + (hasSubQuery() ? "ADQLQuery" : "ADQLList<ADQLOperand>") + " by a " + replacer.getClass().getName() + " (" + replacer.toADQL() + ") !"); } } - public void remove() { + public void remove(){ if (index <= -1) throw new IllegalStateException("remove() impossible: next() has not yet been called !"); if (index == 0) throw new UnsupportedOperationException("Impossible to remove the left operand of the IN constraint !"); else if (index == 1) - throw new UnsupportedOperationException("Impossible to remove the "+(hasSubQuery()?"sub-query":"values list")+" of the IN constraint !"); + throw new UnsupportedOperationException("Impossible to remove the " + (hasSubQuery() ? "sub-query" : "values list") + " of the IN constraint !"); } }; } public String toADQL(){ - return leftOp.toADQL()+" "+getName()+" ("+(hasSubQuery()?subQuery.toADQL():list.toADQL())+")"; + return leftOp.toADQL() + " " + getName() + " (" + (hasSubQuery() ? subQuery.toADQL() : list.toADQL()) + ")"; } } \ No newline at end of file diff --git a/src/adql/query/constraint/IsNull.java b/src/adql/query/constraint/IsNull.java index a442d397bf23af561942cac02cf6c254aa5e92b7..666654df3b61b0afa29ec7e1417fe246866aa525 100644 --- a/src/adql/query/constraint/IsNull.java +++ b/src/adql/query/constraint/IsNull.java @@ -39,14 +39,13 @@ public class IsNull implements ADQLConstraint { /** Indicates whether the predicate IS NOT NULL must be used rather than IS NULL. */ private boolean isNotNull = false; - /** * Builds a comparison between the given column and NULL. * * @param column The column whose the value must be compared to NULL. * @throws NullPointerException If the given column is <i>null</i>. */ - public IsNull(ADQLColumn column) throws NullPointerException { + public IsNull(ADQLColumn column) throws NullPointerException{ this(column, false); } @@ -57,7 +56,7 @@ public class IsNull implements ADQLConstraint { * @param isNot <i>true</i> means IS NOT NULL, <i>false</i> means IS NULL. * @throws NullPointerException If the given column is <i>null</i>. */ - public IsNull(ADQLColumn column, boolean isNot) throws NullPointerException { + public IsNull(ADQLColumn column, boolean isNot) throws NullPointerException{ setColumn(column); isNotNull = isNot; } @@ -68,7 +67,7 @@ public class IsNull implements ADQLConstraint { * @param toCopy The IsNull to copy. * @throws Exception If there is an error during the copy. */ - public IsNull(IsNull toCopy) throws Exception { + public IsNull(IsNull toCopy) throws Exception{ column = (ADQLColumn)toCopy.column.getCopy(); isNotNull = toCopy.isNotNull; } @@ -88,7 +87,7 @@ public class IsNull implements ADQLConstraint { * @param column The new column to compare to <i>NULL</i>. * @throws NullPointerException If the given column is <i>null</i>. */ - public final void setColumn(ADQLColumn column) throws NullPointerException { + public final void setColumn(ADQLColumn column) throws NullPointerException{ if (column == null) throw new NullPointerException("Impossible to compare nothing to NULL: no column has been given to build a IsNull constraint !"); else @@ -113,31 +112,31 @@ public class IsNull implements ADQLConstraint { isNotNull = notNull; } - public ADQLObject getCopy() throws Exception { + public ADQLObject getCopy() throws Exception{ return new IsNull(this); } - public String getName() { - return "IS"+(isNotNull?" NOT ":" ")+"NULL"; + public String getName(){ + return "IS" + (isNotNull ? " NOT " : " ") + "NULL"; } public ADQLIterator adqlIterator(){ - return new ADQLIterator() { + return new ADQLIterator(){ private boolean columnGot = (column == null); - public ADQLObject next() { + public ADQLObject next(){ if (columnGot) throw new NoSuchElementException(); columnGot = true; return column; } - public boolean hasNext() { + public boolean hasNext(){ return !columnGot; } - public void replace(ADQLObject replacer) throws UnsupportedOperationException, IllegalStateException { + public void replace(ADQLObject replacer) throws UnsupportedOperationException, IllegalStateException{ if (!columnGot) throw new IllegalStateException("replace(ADQLObject) impossible: next() has not yet been called !"); @@ -146,20 +145,20 @@ public class IsNull implements ADQLConstraint { else if (replacer instanceof ADQLColumn) column = (ADQLColumn)replacer; else - throw new UnsupportedOperationException("Impossible to replace a column ("+column.toADQL()+") by a "+replacer.getClass().getName()+" ("+replacer.toADQL()+") in a IsNull constraint ("+toADQL()+") !"); + throw new UnsupportedOperationException("Impossible to replace a column (" + column.toADQL() + ") by a " + replacer.getClass().getName() + " (" + replacer.toADQL() + ") in a IsNull constraint (" + toADQL() + ") !"); } - public void remove() { + public void remove(){ if (!columnGot) throw new IllegalStateException("remove() impossible: next() has not yet been called !"); else - throw new UnsupportedOperationException("Impossible to remove the only column ("+column.toADQL()+") of a constraint IsNull ("+toADQL()+") !"); + throw new UnsupportedOperationException("Impossible to remove the only column (" + column.toADQL() + ") of a constraint IsNull (" + toADQL() + ") !"); } }; } - public String toADQL() { - return column.toADQL()+" "+getName(); + public String toADQL(){ + return column.toADQL() + " " + getName(); } } diff --git a/src/adql/query/constraint/NotConstraint.java b/src/adql/query/constraint/NotConstraint.java index ce228b4963c70c0630678ff0fccfcdb12a7b2641..77caae147ec5d6b278eede5f4f7d34b9d7f1ed31 100644 --- a/src/adql/query/constraint/NotConstraint.java +++ b/src/adql/query/constraint/NotConstraint.java @@ -41,7 +41,7 @@ public class NotConstraint implements ADQLConstraint { * * @throws NullPointerException If the given constraint is <i>null</i>. */ - public NotConstraint(ADQLConstraint constraint) throws NullPointerException { + public NotConstraint(ADQLConstraint constraint) throws NullPointerException{ if (constraint == null) throw new NullPointerException("Impossible to apply the logical operator NOT on a NULL constraint !"); this.constraint = constraint; @@ -56,31 +56,31 @@ public class NotConstraint implements ADQLConstraint { return constraint; } - public ADQLObject getCopy() throws Exception { + public ADQLObject getCopy() throws Exception{ return new NotConstraint((ADQLConstraint)constraint.getCopy()); } - public String getName() { - return "NOT "+constraint.getName(); + public String getName(){ + return "NOT " + constraint.getName(); } public ADQLIterator adqlIterator(){ - return new ADQLIterator() { + return new ADQLIterator(){ private boolean constraintGot = (constraint == null); - public ADQLObject next() { + public ADQLObject next(){ if (constraintGot) throw new NoSuchElementException(); constraintGot = true; return constraint; } - public boolean hasNext() { + public boolean hasNext(){ return !constraintGot; } - public void replace(ADQLObject replacer) throws UnsupportedOperationException, IllegalStateException { + public void replace(ADQLObject replacer) throws UnsupportedOperationException, IllegalStateException{ if (!constraintGot) throw new IllegalStateException("replace(ADQLObject) impossible: next() has not yet been called !"); @@ -89,10 +89,10 @@ public class NotConstraint implements ADQLConstraint { else if (replacer instanceof ADQLConstraint) constraint = (ADQLConstraint)replacer; else - throw new UnsupportedOperationException("Impossible to replace an ADQLConstraint by a "+replacer.getClass().getName()+" !"); + throw new UnsupportedOperationException("Impossible to replace an ADQLConstraint by a " + replacer.getClass().getName() + " !"); } - public void remove() { + public void remove(){ if (!constraintGot) throw new IllegalStateException("remove() impossible: next() has not yet been called !"); else @@ -101,8 +101,8 @@ public class NotConstraint implements ADQLConstraint { }; } - public String toADQL() { - return "NOT "+constraint.toADQL(); + public String toADQL(){ + return "NOT " + constraint.toADQL(); } } diff --git a/src/adql/query/from/ADQLJoin.java b/src/adql/query/from/ADQLJoin.java index f598dd4beeefb5cf05ffd5603512a83a5b74ffd4..3f4736233eeac52a03e334fe0c6dea8f02ec30bb 100644 --- a/src/adql/query/from/ADQLJoin.java +++ b/src/adql/query/from/ADQLJoin.java @@ -54,7 +54,6 @@ public abstract class ADQLJoin implements ADQLObject, FromContent { /** List of columns on which the join must be done. */ protected ArrayList<ADQLColumn> lstColumns = null; - /* ************ */ /* CONSTRUCTORS */ /* ************ */ @@ -77,7 +76,7 @@ public abstract class ADQLJoin implements ADQLObject, FromContent { * * @throws Exception If there is an error during the copy. */ - public ADQLJoin(ADQLJoin toCopy) throws Exception { + public ADQLJoin(ADQLJoin toCopy) throws Exception{ leftTable = (FromContent)(toCopy.leftTable.getCopy()); rightTable = (FromContent)(toCopy.rightTable.getCopy()); natural = toCopy.natural; @@ -89,7 +88,6 @@ public abstract class ADQLJoin implements ADQLObject, FromContent { } } - /* ***************** */ /* GETTERS & SETTERS */ /* ***************** */ @@ -98,7 +96,7 @@ public abstract class ADQLJoin implements ADQLObject, FromContent { * * @return <i>true</i> means this join is natural, <i>false</i> else. */ - public final boolean isNatural() { + public final boolean isNatural(){ return natural; } @@ -107,7 +105,7 @@ public abstract class ADQLJoin implements ADQLObject, FromContent { * * @param natural <i>true</i> means this join must be natural, <i>false</i> else. */ - public void setNatural(boolean natural) { + public void setNatural(boolean natural){ this.natural = natural; if (natural){ condition = null; @@ -120,7 +118,7 @@ public abstract class ADQLJoin implements ADQLObject, FromContent { * * @return The left part of the join. */ - public final FromContent getLeftTable() { + public final FromContent getLeftTable(){ return leftTable; } @@ -129,7 +127,7 @@ public abstract class ADQLJoin implements ADQLObject, FromContent { * * @param table The left part of the join. */ - public void setLeftTable(FromContent table) { + public void setLeftTable(FromContent table){ leftTable = table; } @@ -147,7 +145,7 @@ public abstract class ADQLJoin implements ADQLObject, FromContent { * * @param table The right part of the join. */ - public void setRightTable(FromContent table) { + public void setRightTable(FromContent table){ rightTable = table; } @@ -156,7 +154,7 @@ public abstract class ADQLJoin implements ADQLObject, FromContent { * * @return The join condition. */ - public final ClauseConstraints getJoinCondition() { + public final ClauseConstraints getJoinCondition(){ return condition; } @@ -165,7 +163,7 @@ public abstract class ADQLJoin implements ADQLObject, FromContent { * * @param cond The join condition (condition following ON). */ - public void setJoinCondition(ClauseConstraints cond) { + public void setJoinCondition(ClauseConstraints cond){ condition = cond; if (condition != null){ natural = false; @@ -180,10 +178,18 @@ public abstract class ADQLJoin implements ADQLObject, FromContent { */ public final Iterator<ADQLColumn> getJoinedColumns(){ if (lstColumns == null){ - return new Iterator<ADQLColumn>() { - public boolean hasNext() { return false; } - public ADQLColumn next() { return null; } - public void remove() { ; } + return new Iterator<ADQLColumn>(){ + public boolean hasNext(){ + return false; + } + + public ADQLColumn next(){ + return null; + } + + public void remove(){ + ; + } }; }else return lstColumns.iterator(); @@ -216,23 +222,22 @@ public abstract class ADQLJoin implements ADQLObject, FromContent { } } - /* ***************** */ /* INHERITED METHODS */ /* ***************** */ - public String getName() { + public String getName(){ return getJoinType(); } public ADQLIterator adqlIterator(){ - return new ADQLIterator() { + return new ADQLIterator(){ private int index = -1; - private final int nbItems = 2+((condition==null)?0:1)+((lstColumns==null)?0:lstColumns.size()); - private final int offset = 2+((condition==null)?0:1); + private final int nbItems = 2 + ((condition == null) ? 0 : 1) + ((lstColumns == null) ? 0 : lstColumns.size()); + private final int offset = 2 + ((condition == null) ? 0 : 1); private Iterator<ADQLColumn> itCol = null; - public ADQLObject next() { + public ADQLObject next(){ index++; if (index == 0) @@ -242,17 +247,18 @@ public abstract class ADQLJoin implements ADQLObject, FromContent { else if (index == 2 && condition != null) return condition; else if (lstColumns != null && !lstColumns.isEmpty()){ - if (itCol == null) itCol = lstColumns.iterator(); + if (itCol == null) + itCol = lstColumns.iterator(); return itCol.next(); }else throw new NoSuchElementException(); } - public boolean hasNext() { - return (itCol != null && itCol.hasNext()) || index+1 < nbItems; + public boolean hasNext(){ + return (itCol != null && itCol.hasNext()) || index + 1 < nbItems; } - public void replace(ADQLObject replacer) throws UnsupportedOperationException, IllegalStateException { + public void replace(ADQLObject replacer) throws UnsupportedOperationException, IllegalStateException{ if (index <= -1) throw new IllegalStateException("replace(ADQLObject) impossible: next() has not yet been called !"); @@ -262,35 +268,35 @@ public abstract class ADQLJoin implements ADQLObject, FromContent { if (replacer instanceof FromContent) leftTable = (FromContent)replacer; else - throw new UnsupportedOperationException("Impossible to replace the left \"table\" of the join ("+leftTable.toADQL()+") by a "+replacer.getClass().getName()+" ("+replacer.toADQL()+") ! The replacer must be a FromContent instance."); + throw new UnsupportedOperationException("Impossible to replace the left \"table\" of the join (" + leftTable.toADQL() + ") by a " + replacer.getClass().getName() + " (" + replacer.toADQL() + ") ! The replacer must be a FromContent instance."); }else if (index == 1){ if (replacer instanceof FromContent) rightTable = (FromContent)replacer; else - throw new UnsupportedOperationException("Impossible to replace the right \"table\" of the join ("+rightTable.toADQL()+") by a "+replacer.getClass().getName()+" ("+replacer.toADQL()+") ! The replacer must be a FromContent instance."); + throw new UnsupportedOperationException("Impossible to replace the right \"table\" of the join (" + rightTable.toADQL() + ") by a " + replacer.getClass().getName() + " (" + replacer.toADQL() + ") ! The replacer must be a FromContent instance."); }else if (index == 2 && itCol == null){ if (replacer instanceof ClauseConstraints) condition = (ClauseConstraints)replacer; else - throw new UnsupportedOperationException("Impossible to replace an ADQLConstraint ("+condition+") by a "+replacer.getClass().getName()+" ("+replacer.toADQL()+") !"); + throw new UnsupportedOperationException("Impossible to replace an ADQLConstraint (" + condition + ") by a " + replacer.getClass().getName() + " (" + replacer.toADQL() + ") !"); }else if (itCol != null){ if (replacer instanceof ADQLColumn) - lstColumns.set(index-offset, (ADQLColumn)replacer); + lstColumns.set(index - offset, (ADQLColumn)replacer); else - throw new UnsupportedOperationException("Impossible to replace an ADQLColumn by a "+replacer.getClass().getName()+" ("+replacer.toADQL()+") !"); + throw new UnsupportedOperationException("Impossible to replace an ADQLColumn by a " + replacer.getClass().getName() + " (" + replacer.toADQL() + ") !"); } } - public void remove() { + public void remove(){ if (index <= -1) throw new IllegalStateException("remove() impossible: next() has not yet been called !"); else if (index == 0) - throw new UnsupportedOperationException("Impossible to remove the left \"table\" of the join ("+leftTable.toADQL()+") !"); + throw new UnsupportedOperationException("Impossible to remove the left \"table\" of the join (" + leftTable.toADQL() + ") !"); else if (index == 1) - throw new UnsupportedOperationException("Impossible to remove the right \"table\" of the join ("+rightTable.toADQL()+") !"); + throw new UnsupportedOperationException("Impossible to remove the right \"table\" of the join (" + rightTable.toADQL() + ") !"); else if (index == 2 && itCol == null) - throw new UnsupportedOperationException("Impossible to remove a condition ("+condition.toADQL()+") from a join ("+toADQL()+") !"); + throw new UnsupportedOperationException("Impossible to remove a condition (" + condition.toADQL() + ") from a join (" + toADQL() + ") !"); else if (itCol != null){ itCol.remove(); index--; @@ -302,14 +308,14 @@ public abstract class ADQLJoin implements ADQLObject, FromContent { public String toADQL(){ StringBuffer adql = new StringBuffer(leftTable.toADQL()); - adql.append(natural?" NATURAL ":" ").append(getJoinType()).append(' ').append(rightTable.toADQL()); + adql.append(natural ? " NATURAL " : " ").append(getJoinType()).append(' ').append(rightTable.toADQL()); if (condition != null) adql.append(" ON ").append(condition.toADQL()); - else if (lstColumns != null) { + else if (lstColumns != null){ String cols = null; for(ADQLColumn item : lstColumns){ - cols = (cols==null)?("\""+item.toADQL()+"\""):(cols+", \""+item.toADQL()+"\""); + cols = (cols == null) ? ("\"" + item.toADQL() + "\"") : (cols + ", \"" + item.toADQL() + "\""); } adql.append(" USING (").append(cols).append(')'); } @@ -355,7 +361,6 @@ public abstract class ADQLJoin implements ADQLObject, FromContent { return tables; } - /* **************** */ /* ABSTRACT METHODS */ /* **************** */ diff --git a/src/adql/query/from/ADQLTable.java b/src/adql/query/from/ADQLTable.java index dfce3a81b8949b5dc6578c4e802738a0f5b19b88..9acd436324b4ba4bf228457f2a875c5fdc888ce1 100644 --- a/src/adql/query/from/ADQLTable.java +++ b/src/adql/query/from/ADQLTable.java @@ -66,7 +66,6 @@ public class ADQLTable implements ADQLObject, FromContent { /** Position in the original ADQL query string. */ private TextPosition position = null; - /** * Builds a reference to a table with its name (simple or full ({catalog}.{schema}.{table})). * @@ -118,11 +117,11 @@ public class ADQLTable implements ADQLObject, FromContent { * * @throws Exception If there is an error during the copy. */ - public ADQLTable(ADQLTable toCopy) throws Exception { + public ADQLTable(ADQLTable toCopy) throws Exception{ catalog = toCopy.catalog; schema = toCopy.schema; table = toCopy.table; - subQuery = (toCopy.subQuery == null)?null:(ADQLQuery)toCopy.subQuery.getCopy(); + subQuery = (toCopy.subQuery == null) ? null : (ADQLQuery)toCopy.subQuery.getCopy(); alias = toCopy.alias; caseSensitivity = toCopy.caseSensitivity; position = toCopy.position; @@ -147,9 +146,9 @@ public class ADQLTable implements ADQLObject, FromContent { if (n.length() == 0) return null; else{ - if (n.length() > 1 && n.charAt(0) == '\"' && n.charAt(n.length()-1) == '\"'){ + if (n.length() > 1 && n.charAt(0) == '\"' && n.charAt(n.length() - 1) == '\"'){ n.deleteCharAt(0); - n.deleteCharAt(n.length()-1); + n.deleteCharAt(n.length() - 1); n.trimToSize(); if (n.length() == 0) return null; @@ -174,7 +173,7 @@ public class ADQLTable implements ADQLObject, FromContent { * * @param pos Position of this {@link ADQLTable}. */ - public final void setPosition(final TextPosition pos) { + public final void setPosition(final TextPosition pos){ position = pos; } @@ -183,7 +182,7 @@ public class ADQLTable implements ADQLObject, FromContent { * * @return Catalog name. */ - public final String getCatalogName() { + public final String getCatalogName(){ return catalog; } @@ -192,7 +191,7 @@ public class ADQLTable implements ADQLObject, FromContent { * * @param catalog The new name of its catalog. */ - public final void setCatalogName(String catalog) { + public final void setCatalogName(String catalog){ final String temp = normalizeName(catalog, IdentifierField.CATALOG); if ((this.catalog == null && temp != null) || (this.catalog != null && !this.catalog.equalsIgnoreCase(temp))) dbLink = null; @@ -204,7 +203,7 @@ public class ADQLTable implements ADQLObject, FromContent { * * @return Schema name. */ - public final String getSchemaName() { + public final String getSchemaName(){ return schema; } @@ -213,7 +212,7 @@ public class ADQLTable implements ADQLObject, FromContent { * * @param schema The new name of its schema. */ - public final void setSchemaName(String schema) { + public final void setSchemaName(String schema){ final String temp = normalizeName(schema, IdentifierField.SCHEMA); if ((this.schema == null && temp != null) || (this.schema != null && !this.schema.equalsIgnoreCase(temp))) dbLink = null; @@ -269,7 +268,7 @@ public class ADQLTable implements ADQLObject, FromContent { * * @param newTableName The new name of the table. */ - public void setTableName(String newTableName) { + public void setTableName(String newTableName){ final String temp = normalizeName(newTableName, IdentifierField.TABLE); if ((this.table == null && temp != null) || (this.table != null && !this.table.equalsIgnoreCase(temp))) dbLink = null; @@ -284,14 +283,14 @@ public class ADQLTable implements ADQLObject, FromContent { * @param tableRef The complete table reference ({catalog}.{schema}.{table}). */ public final void setTable(String tableRef){ - String[] parts = (tableRef == null)?null:tableRef.split("\\."); + String[] parts = (tableRef == null) ? null : tableRef.split("\\."); if (parts != null && parts.length > 3) return; else{ - int i = (parts==null)?-1:(parts.length-1); - setTableName((i<0)?null:parts[i--]); - setSchemaName((i<0)?null:parts[i--]); - setCatalogName((i<0)?null:parts[i]); + int i = (parts == null) ? -1 : (parts.length - 1); + setTableName((i < 0) ? null : parts[i--]); + setSchemaName((i < 0) ? null : parts[i--]); + setCatalogName((i < 0) ? null : parts[i]); if (table != null) subQuery = null; } @@ -360,7 +359,7 @@ public class ADQLTable implements ADQLObject, FromContent { * * @return Table label. */ - public final String getAlias() { + public final String getAlias(){ return alias; } @@ -378,7 +377,7 @@ public class ADQLTable implements ADQLObject, FromContent { * * @param alias Label to put on this table. */ - public void setAlias(String alias) { + public void setAlias(String alias){ this.alias = normalizeName(alias, IdentifierField.ALIAS); } @@ -460,7 +459,7 @@ public class ADQLTable implements ADQLObject, FromContent { * * @return The corresponding {@link DBTable}. */ - public final DBTable getDBLink() { + public final DBTable getDBLink(){ return dbLink; } @@ -472,7 +471,7 @@ public class ADQLTable implements ADQLObject, FromContent { * * @param dbLink Its corresponding {@link DBTable}. */ - public final void setDBLink(DBTable dbLink) { + public final void setDBLink(DBTable dbLink){ if (!isSubQuery()) this.dbLink = dbLink; } @@ -501,7 +500,7 @@ public class ADQLTable implements ADQLObject, FromContent { if (!caseSensitive){ if (getAlias().equalsIgnoreCase(alias)) tables.add(this); - } else { + }else{ if (IdentifierField.ALIAS.isCaseSensitive(caseSensitivity)){ if (getAlias().equals(alias)) tables.add(this); @@ -515,20 +514,20 @@ public class ADQLTable implements ADQLObject, FromContent { return tables; } - public ADQLObject getCopy() throws Exception { + public ADQLObject getCopy() throws Exception{ return new ADQLTable(this); } - public String getName() { - return hasAlias()?alias:(isSubQuery()?"{subquery}":getTableName()); + public String getName(){ + return hasAlias() ? alias : (isSubQuery() ? "{subquery}" : getTableName()); } public ADQLIterator adqlIterator(){ - return new ADQLIterator() { + return new ADQLIterator(){ private boolean subQueryGot = !isSubQuery(); - public ADQLObject next() { + public ADQLObject next(){ if (!subQueryGot){ subQueryGot = true; return subQuery; @@ -536,11 +535,11 @@ public class ADQLTable implements ADQLObject, FromContent { throw new NoSuchElementException(); } - public boolean hasNext() { + public boolean hasNext(){ return !subQueryGot; } - public void replace(ADQLObject replacer) throws UnsupportedOperationException, IllegalStateException { + public void replace(ADQLObject replacer) throws UnsupportedOperationException, IllegalStateException{ if (!subQueryGot) throw new IllegalStateException("replace(ADQLObject) impossible: next() has not yet been called !"); @@ -550,21 +549,20 @@ public class ADQLTable implements ADQLObject, FromContent { if (replacer instanceof ADQLQuery) subQuery = (ADQLQuery)replacer; else - throw new UnsupportedOperationException("Impossible to replace a sub-query ("+subQuery.toADQL()+") by a "+replacer.getClass().getName()+" ("+replacer.toADQL()+") !"); + throw new UnsupportedOperationException("Impossible to replace a sub-query (" + subQuery.toADQL() + ") by a " + replacer.getClass().getName() + " (" + replacer.toADQL() + ") !"); } - public void remove() { + public void remove(){ if (!subQueryGot) throw new IllegalStateException("remove() impossible: next() has not yet been called !"); else - throw new UnsupportedOperationException("Impossible to remove the sub-query of an ADQLTable ("+toADQL()+") !"); + throw new UnsupportedOperationException("Impossible to remove the sub-query of an ADQLTable (" + toADQL() + ") !"); } }; } - public String toADQL() { - return (isSubQuery()?("("+subQuery.toADQL()+")"):getFullTableName()) - +((alias==null)?"":(" AS "+(isCaseSensitive(IdentifierField.ALIAS)?("\""+alias+"\""):alias))); + public String toADQL(){ + return (isSubQuery() ? ("(" + subQuery.toADQL() + ")") : getFullTableName()) + ((alias == null) ? "" : (" AS " + (isCaseSensitive(IdentifierField.ALIAS) ? ("\"" + alias + "\"") : alias))); } } \ No newline at end of file diff --git a/src/adql/query/from/CrossJoin.java b/src/adql/query/from/CrossJoin.java index 299a57f866308ce64ec75305c47194f2c92053b9..86c5628f825d557b6d1dafddad29f25118afcbdb 100644 --- a/src/adql/query/from/CrossJoin.java +++ b/src/adql/query/from/CrossJoin.java @@ -42,7 +42,7 @@ public class CrossJoin extends ADQLJoin { * * @see ADQLJoin#ADQLJoin(FromContent, FromContent) */ - public CrossJoin(FromContent left, FromContent right) { + public CrossJoin(FromContent left, FromContent right){ super(left, right); } @@ -55,12 +55,14 @@ public class CrossJoin extends ADQLJoin { * * @see ADQLJoin#ADQLJoin(ADQLJoin) */ - public CrossJoin(CrossJoin toCopy) throws Exception { + public CrossJoin(CrossJoin toCopy) throws Exception{ super(toCopy); } @Override - public String getJoinType() { return "CROSS JOIN"; } + public String getJoinType(){ + return "CROSS JOIN"; + } /** * Effect-less method: a CROSS join can not be NATURAL. @@ -68,7 +70,9 @@ public class CrossJoin extends ADQLJoin { * @see adql.query.from.ADQLJoin#setNatural(boolean) */ @Override - public void setNatural(boolean natural) { ; } + public void setNatural(boolean natural){ + ; + } /** * Effect-less method: no join condition can be specified to make a CROSS join. @@ -76,7 +80,9 @@ public class CrossJoin extends ADQLJoin { * @see adql.query.from.ADQLJoin#setJoinCondition(adql.query.ClauseConstraints) */ @Override - public void setJoinCondition(ClauseConstraints cond) { ; } + public void setJoinCondition(ClauseConstraints cond){ + ; + } /** * Effect-less method: no columns can be joined in a CROSS join. @@ -84,10 +90,12 @@ public class CrossJoin extends ADQLJoin { * @see adql.query.from.ADQLJoin#setJoinedColumns(java.util.Collection) */ @Override - public void setJoinedColumns(Collection<ADQLColumn> columns) { ; } + public void setJoinedColumns(Collection<ADQLColumn> columns){ + ; + } @Override - public ADQLObject getCopy() throws Exception { + public ADQLObject getCopy() throws Exception{ return new CrossJoin(this); } diff --git a/src/adql/query/from/InnerJoin.java b/src/adql/query/from/InnerJoin.java index e5adbbe8af6aa781cca500ef66d351419973a59a..d89b4143d4265e4e3375c577f5233d409ebe4241 100644 --- a/src/adql/query/from/InnerJoin.java +++ b/src/adql/query/from/InnerJoin.java @@ -51,7 +51,7 @@ public class InnerJoin extends ADQLJoin { * @see ADQLJoin#ADQLJoin(FromContent, FromContent) * @see #setNatural(boolean) */ - public InnerJoin(FromContent left, FromContent right) { + public InnerJoin(FromContent left, FromContent right){ super(left, right); setNatural(true); } @@ -66,7 +66,7 @@ public class InnerJoin extends ADQLJoin { * @see ADQLJoin#ADQLJoin(FromContent, FromContent) * @see #setJoinCondition(ClauseConstraints) */ - public InnerJoin(FromContent left, FromContent right, ClauseConstraints condition) { + public InnerJoin(FromContent left, FromContent right, ClauseConstraints condition){ super(left, right); setJoinCondition(condition); } @@ -81,7 +81,7 @@ public class InnerJoin extends ADQLJoin { * @see ADQLJoin#ADQLJoin(FromContent, FromContent) * @see #setJoinedColumns(Collection) */ - public InnerJoin(FromContent left, FromContent right, Collection<ADQLColumn> lstColumns) { + public InnerJoin(FromContent left, FromContent right, Collection<ADQLColumn> lstColumns){ super(left, right); setJoinedColumns(new ArrayList<ADQLColumn>(lstColumns)); } @@ -95,15 +95,17 @@ public class InnerJoin extends ADQLJoin { * * @see ADQLJoin#ADQLJoin(ADQLJoin) */ - public InnerJoin(InnerJoin toCopy) throws Exception { + public InnerJoin(InnerJoin toCopy) throws Exception{ super(toCopy); } @Override - public String getJoinType() { return "INNER JOIN"; } + public String getJoinType(){ + return "INNER JOIN"; + } @Override - public ADQLObject getCopy() throws Exception { + public ADQLObject getCopy() throws Exception{ return new InnerJoin(this); } diff --git a/src/adql/query/from/OuterJoin.java b/src/adql/query/from/OuterJoin.java index 20d199c459c880d817b3853da842429bc628de40..0332ca5fb4cbc2de2c35bffb02b53d61a3f1d79d 100644 --- a/src/adql/query/from/OuterJoin.java +++ b/src/adql/query/from/OuterJoin.java @@ -46,14 +46,13 @@ public class OuterJoin extends ADQLJoin { * @author Grégory Mantelet (CDS) * @version 08/2011 */ - public static enum OuterType { + public static enum OuterType{ LEFT, RIGHT, FULL; } /** Type of this OUTER join. */ private OuterType type = OuterType.LEFT; - /** * Builds a NATURAL OUTER join between the two given "tables". * @@ -65,7 +64,7 @@ public class OuterJoin extends ADQLJoin { * @see #setNatural(boolean) * @see #setType(OuterType) */ - public OuterJoin(FromContent left, FromContent right, OuterType type) { + public OuterJoin(FromContent left, FromContent right, OuterType type){ super(left, right); setNatural(true); setType(type); @@ -83,7 +82,7 @@ public class OuterJoin extends ADQLJoin { * @see #setJoinCondition(ClauseConstraints) * @see #setType(OuterType) */ - public OuterJoin(FromContent left, FromContent right, OuterType type, ClauseConstraints condition) { + public OuterJoin(FromContent left, FromContent right, OuterType type, ClauseConstraints condition){ super(left, right); setJoinCondition(condition); setType(type); @@ -101,7 +100,7 @@ public class OuterJoin extends ADQLJoin { * @see #setJoinedColumns(Collection) * @see #setType(OuterType) */ - public OuterJoin(FromContent left, FromContent right, OuterType type, Collection<ADQLColumn> lstColumns) { + public OuterJoin(FromContent left, FromContent right, OuterType type, Collection<ADQLColumn> lstColumns){ super(left, right); setJoinedColumns(new ArrayList<ADQLColumn>(lstColumns)); setType(type); @@ -117,13 +116,15 @@ public class OuterJoin extends ADQLJoin { * @see ADQLJoin#ADQLJoin(ADQLJoin) * @see #setType(OuterType) */ - public OuterJoin(OuterJoin toCopy) throws Exception { + public OuterJoin(OuterJoin toCopy) throws Exception{ super(toCopy); setType(toCopy.type); } @Override - public String getJoinType() { return type.toString()+" OUTER JOIN"; } + public String getJoinType(){ + return type.toString() + " OUTER JOIN"; + } /** * Gets the OUTER join type (left, right or full). @@ -145,7 +146,7 @@ public class OuterJoin extends ADQLJoin { } @Override - public ADQLObject getCopy() throws Exception { + public ADQLObject getCopy() throws Exception{ return new OuterJoin(this); } diff --git a/src/adql/query/operand/ADQLColumn.java b/src/adql/query/operand/ADQLColumn.java index 6a24692b89f77c080f1851bcc3ad73daf773f7e8..d148bd70b061976d74f32df28891bed940bd9e11 100644 --- a/src/adql/query/operand/ADQLColumn.java +++ b/src/adql/query/operand/ADQLColumn.java @@ -60,7 +60,6 @@ public class ADQLColumn implements ADQLOperand { /** The {@link ADQLTable} which is supposed to contain this column. By default, this field is automatically filled by {@link adql.db.DBChecker}. */ private ADQLTable adqlTable = null; - /* ************ */ /* CONSTRUCTORS */ /* ************ */ @@ -148,9 +147,9 @@ public class ADQLColumn implements ADQLOperand { if (n.length() == 0) return null; else{ - if (n.length() > 1 && n.charAt(0) == '\"' && n.charAt(n.length()-1) == '\"'){ + if (n.length() > 1 && n.charAt(0) == '\"' && n.charAt(n.length() - 1) == '\"'){ n.deleteCharAt(0); - n.deleteCharAt(n.length()-1); + n.deleteCharAt(n.length() - 1); n.trimToSize(); if (n.length() == 0) return null; @@ -161,7 +160,6 @@ public class ADQLColumn implements ADQLOperand { return n.toString(); } - /* ***************** */ /* GETTERS & SETTERS */ /* ***************** */ @@ -179,7 +177,7 @@ public class ADQLColumn implements ADQLOperand { * * @param pos Position of this {@link ADQLColumn}. */ - public void setPosition(final TextPosition pos) { + public void setPosition(final TextPosition pos){ position = pos; } @@ -188,7 +186,7 @@ public class ADQLColumn implements ADQLOperand { * * @return Catalog name. */ - public final String getCatalogName() { + public final String getCatalogName(){ return catalog; } @@ -197,7 +195,7 @@ public class ADQLColumn implements ADQLOperand { * * @param catalog New name of the catalog. */ - public final void setCatalogName(String catalog) { + public final void setCatalogName(String catalog){ final String temp = normalizeName(catalog, IdentifierField.CATALOG); if ((this.catalog == null && temp != null) || (this.catalog != null && !this.catalog.equalsIgnoreCase(temp))) dbLink = null; @@ -209,7 +207,7 @@ public class ADQLColumn implements ADQLOperand { * * @return Schema name. */ - public final String getSchemaName() { + public final String getSchemaName(){ return schema; } @@ -218,7 +216,7 @@ public class ADQLColumn implements ADQLOperand { * * @param schema New name of the schema. */ - public final void setSchemaName(String schema) { + public final void setSchemaName(String schema){ final String temp = normalizeName(schema, IdentifierField.SCHEMA); if ((this.schema == null && temp != null) || (this.schema != null && !this.schema.equalsIgnoreCase(temp))) dbLink = null; @@ -332,15 +330,15 @@ public class ADQLColumn implements ADQLOperand { * @param columnRef The complete column reference ({catalog}.{schema}.{table}.{column}). */ public final void setColumn(String columnRef){ - String[] parts = (columnRef == null)?null:columnRef.split("\\."); + String[] parts = (columnRef == null) ? null : columnRef.split("\\."); if (parts != null && parts.length > 4) return; else{ - int i = (parts==null)?-1:(parts.length-1); - setColumnName((i<0)?null:parts[i--]); - setTableName((i<0)?null:parts[i--]); - setSchemaName((i<0)?null:parts[i--]); - setCatalogName((i<0)?null:parts[i]); + int i = (parts == null) ? -1 : (parts.length - 1); + setColumnName((i < 0) ? null : parts[i--]); + setTableName((i < 0) ? null : parts[i--]); + setSchemaName((i < 0) ? null : parts[i--]); + setCatalogName((i < 0) ? null : parts[i]); } } @@ -421,7 +419,7 @@ public class ADQLColumn implements ADQLOperand { * * @return The corresponding {@link DBColumn}. */ - public final DBColumn getDBLink() { + public final DBColumn getDBLink(){ return dbLink; } @@ -432,7 +430,7 @@ public class ADQLColumn implements ADQLOperand { * * @param dbLink Its corresponding {@link DBColumn}. */ - public final void setDBLink(DBColumn dbLink) { + public final void setDBLink(DBColumn dbLink){ this.dbLink = dbLink; } @@ -441,7 +439,7 @@ public class ADQLColumn implements ADQLOperand { * * @return Its source table. */ - public final ADQLTable getAdqlTable() { + public final ADQLTable getAdqlTable(){ return adqlTable; } @@ -452,11 +450,10 @@ public class ADQLColumn implements ADQLOperand { * * @param adqlTable Its source table. */ - public final void setAdqlTable(ADQLTable adqlTable) { + public final void setAdqlTable(ADQLTable adqlTable){ this.adqlTable = adqlTable; } - /* ***************** */ /* INHERITED METHODS */ /* ***************** */ @@ -464,15 +461,15 @@ public class ADQLColumn implements ADQLOperand { return true; } - public boolean isString() { + public boolean isString(){ return true; } - public ADQLObject getCopy() throws Exception { + public ADQLObject getCopy() throws Exception{ return new ADQLColumn(this); } - public String getName() { + public String getName(){ return getColumnName(); } @@ -480,7 +477,7 @@ public class ADQLColumn implements ADQLOperand { return new NullADQLIterator(); } - public String toADQL() { + public String toADQL(){ return getFullColumnName(); } diff --git a/src/adql/query/operand/Concatenation.java b/src/adql/query/operand/Concatenation.java index 639f747e80f751fdfda7e84fff61306bf35b2c21..a09b7905adc6e885cb0af492d19ef8a05e990782 100644 --- a/src/adql/query/operand/Concatenation.java +++ b/src/adql/query/operand/Concatenation.java @@ -44,32 +44,32 @@ public final class Concatenation extends ADQLList<ADQLOperand> implements ADQLOp * @param toCopy The {@link Concatenation} to copy. * @throws Exception If there is an error during the copy. */ - public Concatenation(Concatenation toCopy) throws Exception { + public Concatenation(Concatenation toCopy) throws Exception{ super(toCopy); } @Override - public ADQLObject getCopy() throws Exception { + public ADQLObject getCopy() throws Exception{ return new Concatenation(this); } @Override - public String[] getPossibleSeparators() { + public String[] getPossibleSeparators(){ return new String[]{"||"}; } @Override - public String getSeparator(int index) throws ArrayIndexOutOfBoundsException { + public String getSeparator(int index) throws ArrayIndexOutOfBoundsException{ if (index <= 0 || index > size()) - throw new ArrayIndexOutOfBoundsException("Impossible to get the concatenation operator between the item "+(index-1)+" and "+index+" !"); + throw new ArrayIndexOutOfBoundsException("Impossible to get the concatenation operator between the item " + (index - 1) + " and " + index + " !"); return "||"; } - public final boolean isNumeric() { + public final boolean isNumeric(){ return false; } - public final boolean isString() { + public final boolean isString(){ return true; } diff --git a/src/adql/query/operand/NegativeOperand.java b/src/adql/query/operand/NegativeOperand.java index 354cfa7fa19bf4ca3ab350ff1e2e907b3adf53e7..82fad6bb3691b3dbaa474902526b68a8c3fdbc4c 100644 --- a/src/adql/query/operand/NegativeOperand.java +++ b/src/adql/query/operand/NegativeOperand.java @@ -44,14 +44,14 @@ public final class NegativeOperand implements ADQLOperand { * @throws NullPointerException If the given operand is <i>null</i>. * @throws UnsupportedOperationException If the given operand is not numeric (if {@link ADQLOperand#isNumeric()} does not return <i>true</i>). */ - public NegativeOperand(ADQLOperand operand) throws NullPointerException, UnsupportedOperationException { + public NegativeOperand(ADQLOperand operand) throws NullPointerException, UnsupportedOperationException{ if (operand == null) throw new NullPointerException("Impossible to negativate an operand equals to NULL !"); if (operand.isNumeric()) this.operand = operand; else - throw new UnsupportedOperationException("Impossible to negativate a non-numeric operand ("+operand.toADQL()+") !"); + throw new UnsupportedOperationException("Impossible to negativate a non-numeric operand (" + operand.toADQL() + ") !"); } /** @@ -77,32 +77,32 @@ public final class NegativeOperand implements ADQLOperand { return false; } - public ADQLObject getCopy() throws Exception { + public ADQLObject getCopy() throws Exception{ NegativeOperand copy = new NegativeOperand((ADQLOperand)operand.getCopy()); return copy; } - public String getName() { - return "-"+operand.getName(); + public String getName(){ + return "-" + operand.getName(); } public ADQLIterator adqlIterator(){ - return new ADQLIterator() { + return new ADQLIterator(){ private boolean operandGot = (operand == null); - public ADQLObject next() { + public ADQLObject next(){ if (operandGot) throw new NoSuchElementException(); operandGot = true; return operand; } - public boolean hasNext() { + public boolean hasNext(){ return !operandGot; } - public void replace(ADQLObject replacer) throws UnsupportedOperationException, IllegalStateException { + public void replace(ADQLObject replacer) throws UnsupportedOperationException, IllegalStateException{ if (!operandGot) throw new IllegalStateException("replace(ADQLObject) impossible: next() has not yet been called !"); @@ -111,20 +111,20 @@ public final class NegativeOperand implements ADQLOperand { else if (replacer instanceof ADQLOperand && ((ADQLOperand)replacer).isNumeric()) operand = (ADQLOperand)replacer; else - throw new UnsupportedOperationException("Impossible to replace the operand \""+operand.toADQL()+"\" by \""+replacer.toADQL()+"\" in the NegativeOperand \""+toADQL()+"\" because the replacer is not an ADQLOperand or is not numeric !"); + throw new UnsupportedOperationException("Impossible to replace the operand \"" + operand.toADQL() + "\" by \"" + replacer.toADQL() + "\" in the NegativeOperand \"" + toADQL() + "\" because the replacer is not an ADQLOperand or is not numeric !"); } - public void remove() { + public void remove(){ if (!operandGot) throw new IllegalStateException("remove() impossible: next() has not yet been called !"); else - throw new UnsupportedOperationException("Impossible to remove the only operand ("+operand.toADQL()+") of a NegativeOperand ("+toADQL()+"). However you can remove the whole NegativeOperand."); + throw new UnsupportedOperationException("Impossible to remove the only operand (" + operand.toADQL() + ") of a NegativeOperand (" + toADQL() + "). However you can remove the whole NegativeOperand."); } }; } - public String toADQL() { - return "-"+operand.toADQL(); + public String toADQL(){ + return "-" + operand.toADQL(); } } diff --git a/src/adql/query/operand/NumericConstant.java b/src/adql/query/operand/NumericConstant.java index 7cdbbd49209fa64d92c3ba7df3004215c76886fc..2baa6d260079d0f290cab19b9f1983f1a1d3881f 100644 --- a/src/adql/query/operand/NumericConstant.java +++ b/src/adql/query/operand/NumericConstant.java @@ -42,7 +42,7 @@ public final class NumericConstant implements ADQLOperand { * * @see NumericConstant#setValue(String) */ - public NumericConstant(String value) throws NumberFormatException { + public NumericConstant(String value) throws NumberFormatException{ this(value, true); } @@ -51,8 +51,8 @@ public final class NumericConstant implements ADQLOperand { * * @param val The numeric value. */ - public NumericConstant(long val) { - this(""+val, false); + public NumericConstant(long val){ + this("" + val, false); } /** @@ -61,7 +61,7 @@ public final class NumericConstant implements ADQLOperand { * @param val The numeric value. */ public NumericConstant(double val){ - this(""+val, false); + this("" + val, false); } /** @@ -75,7 +75,7 @@ public final class NumericConstant implements ADQLOperand { * * @see NumericConstant#setValue(String, boolean) */ - public NumericConstant(String value, boolean checkNumeric) throws NumberFormatException { + public NumericConstant(String value, boolean checkNumeric) throws NumberFormatException{ setValue(value, checkNumeric); } @@ -84,7 +84,7 @@ public final class NumericConstant implements ADQLOperand { * * @param toCopy The NumericConstant to copy. */ - public NumericConstant(NumericConstant toCopy) { + public NumericConstant(NumericConstant toCopy){ this.value = toCopy.value; } @@ -92,7 +92,7 @@ public final class NumericConstant implements ADQLOperand { return value; } - public final double getNumericValue() { + public final double getNumericValue(){ try{ return Double.parseDouble(value); }catch(NumberFormatException nfe){ @@ -105,8 +105,8 @@ public final class NumericConstant implements ADQLOperand { * * @param value The numeric value. */ - public final void setValue(long value) { - this.value = ""+value; + public final void setValue(long value){ + this.value = "" + value; } /** @@ -114,8 +114,8 @@ public final class NumericConstant implements ADQLOperand { * * @param value The numeric value. */ - public final void setValue(double value) { - this.value = ""+value; + public final void setValue(double value){ + this.value = "" + value; } /** @@ -126,7 +126,7 @@ public final class NumericConstant implements ADQLOperand { * * @see NumericConstant#setValue(String, boolean) */ - public final void setValue(String value) throws NumberFormatException { + public final void setValue(String value) throws NumberFormatException{ setValue(value, true); } @@ -139,7 +139,7 @@ public final class NumericConstant implements ADQLOperand { * @param checkNumeric <i>true</i> to check whether the given value is numeric, <i>false</i> otherwise. * @throws NumberFormatException If the given value can not be converted in a Double. */ - public final void setValue(String value, boolean checkNumeric) throws NumberFormatException { + public final void setValue(String value, boolean checkNumeric) throws NumberFormatException{ if (checkNumeric) Double.parseDouble(value); @@ -160,11 +160,11 @@ public final class NumericConstant implements ADQLOperand { return false; } - public ADQLObject getCopy() { + public ADQLObject getCopy(){ return new NumericConstant(this); } - public String getName() { + public String getName(){ return value; } @@ -172,7 +172,7 @@ public final class NumericConstant implements ADQLOperand { return new NullADQLIterator(); } - public String toADQL() { + public String toADQL(){ return value; } diff --git a/src/adql/query/operand/Operation.java b/src/adql/query/operand/Operation.java index 43997d6b851a7aea8f7e398a57cd09d4ed6062e7..b5398ffeabc4864e09e40bf369402850cefd1c6e 100644 --- a/src/adql/query/operand/Operation.java +++ b/src/adql/query/operand/Operation.java @@ -46,7 +46,6 @@ public class Operation implements ADQLOperand { /** Part of the operation at the right of the operator. */ private ADQLOperand rightOperand; - /** * Builds an operation. * @@ -59,7 +58,7 @@ public class Operation implements ADQLOperand { * @see Operation#setLeftOperand(ADQLOperand) * @see Operation#setRightOperand(ADQLOperand) */ - public Operation(ADQLOperand leftOp, OperationType op, ADQLOperand rightOp) throws NullPointerException, UnsupportedOperationException { + public Operation(ADQLOperand leftOp, OperationType op, ADQLOperand rightOp) throws NullPointerException, UnsupportedOperationException{ setLeftOperand(leftOp); @@ -78,7 +77,7 @@ public class Operation implements ADQLOperand { * * @throws Exception If there is an error during the copy. */ - public Operation(Operation toCopy) throws Exception { + public Operation(Operation toCopy) throws Exception{ leftOperand = (ADQLOperand)toCopy.leftOperand.getCopy(); operation = toCopy.operation; rightOperand = (ADQLOperand)toCopy.rightOperand.getCopy(); @@ -89,7 +88,7 @@ public class Operation implements ADQLOperand { * * @return The left operand. */ - public final ADQLOperand getLeftOperand() { + public final ADQLOperand getLeftOperand(){ return leftOperand; } @@ -101,11 +100,11 @@ public class Operation implements ADQLOperand { * @throws NullPointerException If the given operand is <i>null</i>. * @throws UnsupportedOperationException If the given operand is not numeric (see {@link ADQLOperand#isNumeric()}). */ - public void setLeftOperand(ADQLOperand newLeftOperand) throws NullPointerException, UnsupportedOperationException { + public void setLeftOperand(ADQLOperand newLeftOperand) throws NullPointerException, UnsupportedOperationException{ if (newLeftOperand == null) throw new NullPointerException("Impossible to update an Operation with a left operand equals to NULL !"); else if (!newLeftOperand.isNumeric()) - throw new UnsupportedOperationException("Impossible to update an Operation because the left operand is not numeric ("+newLeftOperand.toADQL()+") !"); + throw new UnsupportedOperationException("Impossible to update an Operation because the left operand is not numeric (" + newLeftOperand.toADQL() + ") !"); leftOperand = newLeftOperand; } @@ -116,7 +115,7 @@ public class Operation implements ADQLOperand { * @return The operation type. * @see OperationType */ - public final OperationType getOperation() { + public final OperationType getOperation(){ return operation; } @@ -127,7 +126,7 @@ public class Operation implements ADQLOperand { * * @see OperationType */ - public void setOperation(OperationType newOperation) { + public void setOperation(OperationType newOperation){ if (newOperation != null) operation = newOperation; } @@ -137,7 +136,7 @@ public class Operation implements ADQLOperand { * * @return The right operand. */ - public final ADQLOperand getRightOperand() { + public final ADQLOperand getRightOperand(){ return rightOperand; } @@ -149,11 +148,11 @@ public class Operation implements ADQLOperand { * @throws NullPointerException If the given operand is <i>null</i>. * @throws UnsupportedOperationException If the given operand is not numeric (see {@link ADQLOperand#isNumeric()}). */ - public void setRightOperand(ADQLOperand newRightOperand) throws NullPointerException, UnsupportedOperationException { + public void setRightOperand(ADQLOperand newRightOperand) throws NullPointerException, UnsupportedOperationException{ if (newRightOperand == null) throw new NullPointerException("Impossible to update an Operation with a right operand equals to NULL !"); else if (!newRightOperand.isNumeric()) - throw new UnsupportedOperationException("Impossible to update an Operation because the right operand is not numeric ("+newRightOperand.toADQL()+") !"); + throw new UnsupportedOperationException("Impossible to update an Operation because the right operand is not numeric (" + newRightOperand.toADQL() + ") !"); rightOperand = newRightOperand; } @@ -161,32 +160,32 @@ public class Operation implements ADQLOperand { /** Always returns <i>true</i>. * @see adql.query.operand.ADQLOperand#isNumeric() */ - public final boolean isNumeric() { + public final boolean isNumeric(){ return true; } /** Always returns <i>false</i>. * @see adql.query.operand.ADQLOperand#isString() */ - public final boolean isString() { + public final boolean isString(){ return false; } - public ADQLObject getCopy() throws Exception { + public ADQLObject getCopy() throws Exception{ return new Operation(this); } - public String getName() { + public String getName(){ return operation.toString(); } public ADQLIterator adqlIterator(){ - return new ADQLIterator() { + return new ADQLIterator(){ private int index = -1; private ADQLOperand operand = null; - public ADQLObject next() { + public ADQLObject next(){ index++; if (index == 0) @@ -198,11 +197,11 @@ public class Operation implements ADQLOperand { return operand; } - public boolean hasNext() { - return index+1 < 2; + public boolean hasNext(){ + return index + 1 < 2; } - public void replace(ADQLObject replacer) throws UnsupportedOperationException, IllegalStateException { + public void replace(ADQLObject replacer) throws UnsupportedOperationException, IllegalStateException{ if (index <= -1) throw new IllegalStateException("replace(ADQLObject) impossible: next() has not yet been called !"); @@ -210,26 +209,26 @@ public class Operation implements ADQLOperand { remove(); else{ if (replacer instanceof ADQLOperand && ((ADQLOperand)replacer).isNumeric()){ - if (index==0) + if (index == 0) leftOperand = (ADQLOperand)replacer; - else if (index==1) + else if (index == 1) rightOperand = (ADQLOperand)replacer; }else - throw new UnsupportedOperationException("Impossible to replace the operand \""+operand.toADQL()+"\" by \""+replacer.toADQL()+"\" in the operation \""+toADQL()+"\" because the replacer is not an ADQLOperand or is not numeric !"); + throw new UnsupportedOperationException("Impossible to replace the operand \"" + operand.toADQL() + "\" by \"" + replacer.toADQL() + "\" in the operation \"" + toADQL() + "\" because the replacer is not an ADQLOperand or is not numeric !"); } } - public void remove() { + public void remove(){ if (index <= -1) throw new IllegalStateException("remove() impossible: next() has not yet been called !"); else - throw new UnsupportedOperationException("Impossible to remove one operand ("+operand.toADQL()+") of an operation ("+toADQL()+"). However you can replace the whole operation by the remaining operand."); + throw new UnsupportedOperationException("Impossible to remove one operand (" + operand.toADQL() + ") of an operation (" + toADQL() + "). However you can replace the whole operation by the remaining operand."); } }; } - public String toADQL() { - return leftOperand.toADQL()+operation.toADQL()+rightOperand.toADQL(); + public String toADQL(){ + return leftOperand.toADQL() + operation.toADQL() + rightOperand.toADQL(); } } \ No newline at end of file diff --git a/src/adql/query/operand/OperationType.java b/src/adql/query/operand/OperationType.java index f846e6aab1def3854863b84a711e57b97cdc5905..3e5590069f550cfbcd0641bcfae23b6d7fe33e2d 100644 --- a/src/adql/query/operand/OperationType.java +++ b/src/adql/query/operand/OperationType.java @@ -27,14 +27,14 @@ package adql.query.operand; * * @see Operation */ -public enum OperationType { +public enum OperationType{ SUM, SUB, MULT, DIV; public static String[] getOperators(){ - return new String[]{SUM.toString(), SUB.toString(), MULT.toString(), DIV.toString()}; + return new String[]{SUM.toString(),SUB.toString(),MULT.toString(),DIV.toString()}; } - public static OperationType getOperator(String str) throws UnsupportedOperationException { + public static OperationType getOperator(String str) throws UnsupportedOperationException{ if (str.equalsIgnoreCase("+")) return SUM; else if (str.equalsIgnoreCase("-")) @@ -44,7 +44,7 @@ public enum OperationType { else if (str.equalsIgnoreCase("/")) return DIV; else - throw new UnsupportedOperationException("Numeric operation unknown: \""+str+"\" !"); + throw new UnsupportedOperationException("Numeric operation unknown: \"" + str + "\" !"); } public String toADQL(){ @@ -54,16 +54,16 @@ public enum OperationType { @Override public String toString(){ switch(this){ - case SUM: - return "+"; - case SUB: - return "-"; - case MULT: - return "*"; - case DIV: - return "/"; - default: - return "???"; + case SUM: + return "+"; + case SUB: + return "-"; + case MULT: + return "*"; + case DIV: + return "/"; + default: + return "???"; } } } diff --git a/src/adql/query/operand/StringConstant.java b/src/adql/query/operand/StringConstant.java index f20fc1c99be2050cb8c31a283e1543c8333a8c9c..2e2b0d4ff1e5cc5e942f9c16120909ff5d687a0c 100644 --- a/src/adql/query/operand/StringConstant.java +++ b/src/adql/query/operand/StringConstant.java @@ -49,28 +49,28 @@ public final class StringConstant implements ADQLOperand { this.value = value; } - public final boolean isNumeric() { + public final boolean isNumeric(){ return false; } - public final boolean isString() { + public final boolean isString(){ return true; } - public ADQLObject getCopy() { + public ADQLObject getCopy(){ return new StringConstant(this); } - public String getName() { - return "'"+value+"'"; + public String getName(){ + return "'" + value + "'"; } public ADQLIterator adqlIterator(){ return new NullADQLIterator(); } - public String toADQL() { - return "'"+value+"'"; + public String toADQL(){ + return "'" + value + "'"; } } diff --git a/src/adql/query/operand/WrappedOperand.java b/src/adql/query/operand/WrappedOperand.java index 556fc4846efc7a6a7a4fcbc2dcd422cf2d5b7e7b..2ffae9bfd13bb85ed39029eef00bea7b5f9760dc 100644 --- a/src/adql/query/operand/WrappedOperand.java +++ b/src/adql/query/operand/WrappedOperand.java @@ -42,7 +42,7 @@ public class WrappedOperand implements ADQLOperand { * * @throws NullPointerException If the given operand is <i>NULL</i>. */ - public WrappedOperand(ADQLOperand operand) throws NullPointerException { + public WrappedOperand(ADQLOperand operand) throws NullPointerException{ if (operand == null) throw new NullPointerException("Impossible to wrap a NULL operand: (NULL) has no sense !"); this.operand = operand; @@ -57,39 +57,39 @@ public class WrappedOperand implements ADQLOperand { return operand; } - public final boolean isNumeric() { + public final boolean isNumeric(){ return operand.isNumeric(); } - public final boolean isString() { + public final boolean isString(){ return operand.isString(); } - public ADQLObject getCopy() throws Exception { + public ADQLObject getCopy() throws Exception{ return new WrappedOperand((ADQLOperand)operand.getCopy()); } - public String getName() { - return "("+operand.getName()+")"; + public String getName(){ + return "(" + operand.getName() + ")"; } public ADQLIterator adqlIterator(){ - return new ADQLIterator() { + return new ADQLIterator(){ private boolean operandGot = (operand == null); - public ADQLObject next() { + public ADQLObject next(){ if (operandGot) throw new NoSuchElementException(); operandGot = true; return operand; } - public boolean hasNext() { + public boolean hasNext(){ return !operandGot; } - public void replace(ADQLObject replacer) throws UnsupportedOperationException, IllegalStateException { + public void replace(ADQLObject replacer) throws UnsupportedOperationException, IllegalStateException{ if (!operandGot) throw new IllegalStateException("replace(ADQLObject) impossible: next() has not yet been called !"); @@ -98,20 +98,20 @@ public class WrappedOperand implements ADQLOperand { else if (replacer instanceof ADQLOperand) operand = (ADQLOperand)replacer; else - throw new UnsupportedOperationException("Impossible to replace an ADQLOperand (\""+operand+"\") by a "+replacer.getClass().getName()+" (\""+replacer.toADQL()+"\") !"); + throw new UnsupportedOperationException("Impossible to replace an ADQLOperand (\"" + operand + "\") by a " + replacer.getClass().getName() + " (\"" + replacer.toADQL() + "\") !"); } - public void remove() { + public void remove(){ if (!operandGot) throw new IllegalStateException("remove() impossible: next() has not yet been called !"); else - throw new UnsupportedOperationException("Impossible to remove the only item of the WrappedOperand \""+toADQL()+"\": the WrappedOperand would be empty !"); + throw new UnsupportedOperationException("Impossible to remove the only item of the WrappedOperand \"" + toADQL() + "\": the WrappedOperand would be empty !"); } }; } - public String toADQL() { - return "("+operand.toADQL()+")"; + public String toADQL(){ + return "(" + operand.toADQL() + ")"; } } diff --git a/src/adql/query/operand/function/ADQLFunction.java b/src/adql/query/operand/function/ADQLFunction.java index 7a3a3c76bd6f3693cddda8d130739bf3220c3d35..97a22b7f30340c0fcd5d74be2febc83ff9e0675b 100644 --- a/src/adql/query/operand/function/ADQLFunction.java +++ b/src/adql/query/operand/function/ADQLFunction.java @@ -83,11 +83,11 @@ public abstract class ADQLFunction implements ADQLOperand { } public ADQLIterator adqlIterator(){ - return new ADQLIterator() { + return new ADQLIterator(){ private int index = -1; - public ADQLObject next() { + public ADQLObject next(){ try{ return getParameter(++index); }catch(ArrayIndexOutOfBoundsException ex){ @@ -95,43 +95,43 @@ public abstract class ADQLFunction implements ADQLOperand { } } - public boolean hasNext() { - return index+1 < getNbParameters(); + public boolean hasNext(){ + return index + 1 < getNbParameters(); } - public void replace(ADQLObject replacer) throws UnsupportedOperationException, IllegalStateException { + public void replace(ADQLObject replacer) throws UnsupportedOperationException, IllegalStateException{ if (index <= -1) throw new IllegalStateException("replace(ADQLObject) impossible: next() has not yet been called !"); if (replacer == null) remove(); else if (replacer instanceof ADQLOperand){ - try { + try{ setParameter(index, (ADQLOperand)replacer); - } catch (Exception e) { + }catch(Exception e){ e.printStackTrace(); throw new UnsupportedOperationException(e); } }else - throw new UnsupportedOperationException("Impossible to replace the "+index+"-th parameter of \""+toADQL()+"\" by an object whose the class ("+replacer.getClass().getName()+") is not ADQLOperand !"); + throw new UnsupportedOperationException("Impossible to replace the " + index + "-th parameter of \"" + toADQL() + "\" by an object whose the class (" + replacer.getClass().getName() + ") is not ADQLOperand !"); } - public void remove() { + public void remove(){ if (index <= -1) throw new IllegalStateException("remove() impossible: next() has not yet been called !"); else - throw new UnsupportedOperationException("Impossible to remove a parameter of an ADQL function (here the "+index+"-th parameter of \""+toADQL()+"\")"); + throw new UnsupportedOperationException("Impossible to remove a parameter of an ADQL function (here the " + index + "-th parameter of \"" + toADQL() + "\")"); } }; } - public String toADQL() { - String adql = getName()+"("; + public String toADQL(){ + String adql = getName() + "("; - for(int i=0; i<getNbParameters(); i++) - adql += ((i==0)?"":", ")+getParameter(i).toADQL(); + for(int i = 0; i < getNbParameters(); i++) + adql += ((i == 0) ? "" : ", ") + getParameter(i).toADQL(); - return adql+")"; + return adql + ")"; } /** @@ -145,26 +145,26 @@ public abstract class ADQLFunction implements ADQLOperand { protected final ADQLFunction function; protected int index = -1; - public ParameterIterator(ADQLFunction fct) throws NullPointerException { + public ParameterIterator(ADQLFunction fct) throws NullPointerException{ if (fct == null) throw new NullPointerException("Impossible to build an iterator on a function without the function on which the iterator must be applied !"); else function = fct; } - public boolean hasNext() { - return (index+1)<function.getNbParameters(); + public boolean hasNext(){ + return (index + 1) < function.getNbParameters(); } - public ADQLOperand next() { + public ADQLOperand next(){ index++; return function.getParameter(index); } - public void remove() throws UnsupportedOperationException { - try { + public void remove() throws UnsupportedOperationException{ + try{ function.setParameter(index, null); - } catch (Exception e) { + }catch(Exception e){ throw new UnsupportedOperationException(e); } } diff --git a/src/adql/query/operand/function/MathFunction.java b/src/adql/query/operand/function/MathFunction.java index 48302f58eb3f9d3ad09bc57fd39365180a6f96eb..24ce621ce5a09b92007f5c059bd7b6d1897f1f9c 100644 --- a/src/adql/query/operand/function/MathFunction.java +++ b/src/adql/query/operand/function/MathFunction.java @@ -42,7 +42,6 @@ public class MathFunction extends ADQLFunction { /** Second parameter of this function (may be null). */ private ADQLOperand param2 = null; - /** * Creates a mathematical function without parameter. * @@ -75,23 +74,23 @@ public class MathFunction extends ADQLFunction { * @param parameter2 Its second parameter. * @throws Exception If the given function parameters are incorrect. */ - public MathFunction(MathFunctionType t, ADQLOperand parameter1, ADQLOperand parameter2) throws Exception { + public MathFunction(MathFunctionType t, ADQLOperand parameter1, ADQLOperand parameter2) throws Exception{ type = t; switch(type.nbParams()){ - case 0: - if (parameter1 != null || parameter2 != null) - throw new Exception("The function "+type.name()+" must have no parameter !"); - break; - case 1: - if (parameter1 == null || parameter2 != null) - throw new Exception("The function "+type.name()+" must have only one parameter !"); - break; - case 2: - if (parameter1 == null || parameter2 == null) - throw new Exception("The function "+type.name()+" must have two parameters !"); - break; - default: - throw new Exception("Impossible for MathFunction object to have "+type.nbParams()+" ! It is limited to 2 parameters !"); + case 0: + if (parameter1 != null || parameter2 != null) + throw new Exception("The function " + type.name() + " must have no parameter !"); + break; + case 1: + if (parameter1 == null || parameter2 != null) + throw new Exception("The function " + type.name() + " must have only one parameter !"); + break; + case 2: + if (parameter1 == null || parameter2 == null) + throw new Exception("The function " + type.name() + " must have two parameters !"); + break; + default: + throw new Exception("Impossible for MathFunction object to have " + type.nbParams() + " ! It is limited to 2 parameters !"); } param1 = parameter1; param2 = parameter2; @@ -103,7 +102,7 @@ public class MathFunction extends ADQLFunction { * @param toCopy The mathematical function to copy. * @throws Exception If there is an error during the copy. */ - public MathFunction(MathFunction toCopy) throws Exception { + public MathFunction(MathFunction toCopy) throws Exception{ type = toCopy.type; param1 = (ADQLOperand)toCopy.param1.getCopy(); param2 = (ADQLOperand)toCopy.param2.getCopy(); @@ -120,27 +119,27 @@ public class MathFunction extends ADQLFunction { return type; } - public ADQLObject getCopy() throws Exception { + public ADQLObject getCopy() throws Exception{ return new MathFunction(this); } - public String getName() { + public String getName(){ return type.name(); } - public final boolean isNumeric() { + public final boolean isNumeric(){ return true; } - public final boolean isString() { + public final boolean isString(){ return false; } @Override - public ADQLOperand[] getParameters() { + public ADQLOperand[] getParameters(){ if (param1 != null){ if (param2 != null) - return new ADQLOperand[]{param1, param2}; + return new ADQLOperand[]{param1,param2}; else return new ADQLOperand[]{param1}; }else @@ -148,40 +147,42 @@ public class MathFunction extends ADQLFunction { } @Override - public int getNbParameters() { + public int getNbParameters(){ return type.nbParams(); } @Override - public ADQLOperand getParameter(int index) throws ArrayIndexOutOfBoundsException { + public ADQLOperand getParameter(int index) throws ArrayIndexOutOfBoundsException{ if (index < 0 || index >= getNbParameters()) - throw new ArrayIndexOutOfBoundsException("No "+index+"-th parameter for the function \""+type.name()+"\" (nb required params = "+type.nbParams()+") !"); + throw new ArrayIndexOutOfBoundsException("No " + index + "-th parameter for the function \"" + type.name() + "\" (nb required params = " + type.nbParams() + ") !"); switch(index){ - case 0: - return param1; - case 1: - return param2; - default: - return null; + case 0: + return param1; + case 1: + return param2; + default: + return null; } } @Override - public ADQLOperand setParameter(int index, ADQLOperand replacer) throws ArrayIndexOutOfBoundsException, NullPointerException, Exception { + public ADQLOperand setParameter(int index, ADQLOperand replacer) throws ArrayIndexOutOfBoundsException, NullPointerException, Exception{ if (index < 0 || index >= getNbParameters()) - throw new ArrayIndexOutOfBoundsException("No "+index+"-th parameter for the function \""+type.name()+"\" (nb required params = "+type.nbParams()+") !"); + throw new ArrayIndexOutOfBoundsException("No " + index + "-th parameter for the function \"" + type.name() + "\" (nb required params = " + type.nbParams() + ") !"); else if (replacer == null) throw new NullPointerException("Impossible to remove any parameter from a mathematical function ! All parameters are required !"); else{ ADQLOperand replaced = null; switch(index){ - case 0: - replaced = param1; - param1 = replacer; break; - case 1: - replaced = param2; - param2 = replacer; break; + case 0: + replaced = param1; + param1 = replacer; + break; + case 1: + replaced = param2; + param2 = replacer; + break; } return replaced; } diff --git a/src/adql/query/operand/function/MathFunctionType.java b/src/adql/query/operand/function/MathFunctionType.java index 9680c18eb98cced1e31c96d67642928959e9ad61..3dca4aaf07215edda6e5562bed1fe1a3baa4d951 100644 --- a/src/adql/query/operand/function/MathFunctionType.java +++ b/src/adql/query/operand/function/MathFunctionType.java @@ -27,31 +27,12 @@ package adql.query.operand.function; * * @see MathFunction */ -public enum MathFunctionType { - ABS(1), - CEILING(1), - DEGREES(1), - EXP(1), - FLOOR(1), - LOG(1), // returns the natural logarithm (base e) of a double value. +public enum MathFunctionType{ + ABS(1), CEILING(1), DEGREES(1), EXP(1), FLOOR(1), LOG(1), // returns the natural logarithm (base e) of a double value. LOG10(1), // returns the base 10 logarithm of a double value. - MOD(2), - PI(0), - POWER(2), - RADIANS(1), - SQRT(1), - RAND(1), - ROUND(2), - TRUNCATE(2), + MOD(2), PI(0), POWER(2), RADIANS(1), SQRT(1), RAND(1), ROUND(2), TRUNCATE(2), - ACOS(1), - ASIN(1), - ATAN(1), - ATAN2(2), - COS(1), - COT(1), - SIN(1), - TAN(1); + ACOS(1), ASIN(1), ATAN(1), ATAN2(2), COS(1), COT(1), SIN(1), TAN(1); private final int nbRequiredParameters; diff --git a/src/adql/query/operand/function/SQLFunction.java b/src/adql/query/operand/function/SQLFunction.java index fb17ecb075861c4e74ce6168f3a776b495414c42..3442aea581efa2e092d1eb65a78bdab9f62db74c 100644 --- a/src/adql/query/operand/function/SQLFunction.java +++ b/src/adql/query/operand/function/SQLFunction.java @@ -42,7 +42,6 @@ public class SQLFunction extends ADQLFunction { /** Distinct values of the parameter ? */ private boolean distinct = false; - /** * Creates a SQL function with one parameter. * @@ -50,7 +49,7 @@ public class SQLFunction extends ADQLFunction { * @param operand The only parameter of this function. * @throws NullPointerException If the given is <i>null</i> or if the given operand is <i>null</i> EXCEPT when the given type is {@link SQLFunctionType#COUNT_ALL}. */ - public SQLFunction(SQLFunctionType t, ADQLOperand operand) throws NullPointerException { + public SQLFunction(SQLFunctionType t, ADQLOperand operand) throws NullPointerException{ this(t, operand, false); } @@ -62,7 +61,7 @@ public class SQLFunction extends ADQLFunction { * @param distinctValues <i>true</i> if the quantifier DISTINCT must be used, <i>false</i> otherwise (ALL). * @throws NullPointerException If the given is <i>null</i> or if the given operand is <i>null</i> EXCEPT when the given type is {@link SQLFunctionType#COUNT_ALL}. */ - public SQLFunction(SQLFunctionType t, ADQLOperand operand, boolean distinctValues) throws NullPointerException { + public SQLFunction(SQLFunctionType t, ADQLOperand operand, boolean distinctValues) throws NullPointerException{ if (t == null) throw new NullPointerException("Impossible to build a SQLFunction without its type (COUNT, SUM, AVG, ...) !"); else @@ -71,7 +70,7 @@ public class SQLFunction extends ADQLFunction { if (type == SQLFunctionType.COUNT_ALL) param = null; else if (operand == null) - throw new NullPointerException("Impossible to build the SQL function \""+type.name()+"\" without the operand on which it must apply !"); + throw new NullPointerException("Impossible to build the SQL function \"" + type.name() + "\" without the operand on which it must apply !"); else param = operand; @@ -84,7 +83,7 @@ public class SQLFunction extends ADQLFunction { * @param toCopy The SQL function to copy. * @throws Exception If there is an error during the copy. */ - public SQLFunction(SQLFunction toCopy) throws Exception { + public SQLFunction(SQLFunction toCopy) throws Exception{ type = toCopy.type; param = (ADQLOperand)toCopy.param.getCopy(); distinct = toCopy.distinct; @@ -104,7 +103,7 @@ public class SQLFunction extends ADQLFunction { * * @param distinctValues <i>true</i> means distinct values, <i>false</i> else. */ - public void setDistinct(boolean distinctValues) { + public void setDistinct(boolean distinctValues){ distinct = distinctValues; } @@ -117,24 +116,24 @@ public class SQLFunction extends ADQLFunction { return type; } - public ADQLObject getCopy() throws Exception { + public ADQLObject getCopy() throws Exception{ return new SQLFunction(this); } - public String getName() { + public String getName(){ return type.name(); } - public final boolean isNumeric() { + public final boolean isNumeric(){ return true; } - public final boolean isString() { + public final boolean isString(){ return false; } @Override - public ADQLOperand[] getParameters() { + public ADQLOperand[] getParameters(){ if (param != null) return new ADQLOperand[]{param}; else @@ -143,24 +142,24 @@ public class SQLFunction extends ADQLFunction { @Override public int getNbParameters(){ - return (type == SQLFunctionType.COUNT_ALL)?0:1; + return (type == SQLFunctionType.COUNT_ALL) ? 0 : 1; } @Override - public ADQLOperand getParameter(int index) throws ArrayIndexOutOfBoundsException { + public ADQLOperand getParameter(int index) throws ArrayIndexOutOfBoundsException{ if (index < 0 || index >= getNbParameters()) - throw new ArrayIndexOutOfBoundsException("No "+index+"-th parameter for the function \""+type.name()+"\" !"); + throw new ArrayIndexOutOfBoundsException("No " + index + "-th parameter for the function \"" + type.name() + "\" !"); else return param; } @Override - public ADQLOperand setParameter(int index, ADQLOperand replacer) throws ArrayIndexOutOfBoundsException, NullPointerException, Exception { + public ADQLOperand setParameter(int index, ADQLOperand replacer) throws ArrayIndexOutOfBoundsException, NullPointerException, Exception{ if (index < 0 || index >= getNbParameters()) - throw new ArrayIndexOutOfBoundsException("No "+index+"-th parameter for the function \""+type.name()+"\" !"); + throw new ArrayIndexOutOfBoundsException("No " + index + "-th parameter for the function \"" + type.name() + "\" !"); if (replacer == null) - throw new NullPointerException("Impossible to remove the only required parameter of the function \""+type.name()+"\" !"); + throw new NullPointerException("Impossible to remove the only required parameter of the function \"" + type.name() + "\" !"); ADQLOperand replaced = param; param = replacer; @@ -169,13 +168,11 @@ public class SQLFunction extends ADQLFunction { } @Override - public String toADQL() { + public String toADQL(){ if (type == SQLFunctionType.COUNT_ALL) - return "COUNT("+(distinct?"DISTINCT ":"")+"*)"; + return "COUNT(" + (distinct ? "DISTINCT " : "") + "*)"; else - return getName()+"("+(distinct?"DISTINCT ":"")+param.toADQL()+")"; + return getName() + "(" + (distinct ? "DISTINCT " : "") + param.toADQL() + ")"; } - - } \ No newline at end of file diff --git a/src/adql/query/operand/function/SQLFunctionType.java b/src/adql/query/operand/function/SQLFunctionType.java index 51a44edcd81408a26a27b740cf61409e204d56b1..8287a9f763944f3f4c0e93c9c904ba4d72cec195 100644 --- a/src/adql/query/operand/function/SQLFunctionType.java +++ b/src/adql/query/operand/function/SQLFunctionType.java @@ -27,11 +27,6 @@ package adql.query.operand.function; * * @see SQLFunction */ -public enum SQLFunctionType { - COUNT_ALL, - COUNT, - AVG, - MAX, - MIN, - SUM; +public enum SQLFunctionType{ + COUNT_ALL, COUNT, AVG, MAX, MIN, SUM; } diff --git a/src/adql/query/operand/function/geometry/AreaFunction.java b/src/adql/query/operand/function/geometry/AreaFunction.java index c70808ef6f621742e0964982ae755199ce6a4542..42906c9811341c3c2929f26b3befe67f801fddef 100644 --- a/src/adql/query/operand/function/geometry/AreaFunction.java +++ b/src/adql/query/operand/function/geometry/AreaFunction.java @@ -41,7 +41,6 @@ public class AreaFunction extends GeometryFunction { /** The only parameter of this function. */ private GeometryValue<GeometryFunction> parameter; - /** * Builds an AREA function with its parameter. * @@ -49,7 +48,7 @@ public class AreaFunction extends GeometryFunction { * @throws NullPointerException If the given operand is <i>null</i> or if it's not a {@link GeometryFunction}. */ @SuppressWarnings("unchecked") - public AreaFunction(GeometryValue<GeometryFunction> param) throws NullPointerException { + public AreaFunction(GeometryValue<GeometryFunction> param) throws NullPointerException{ super(); if (param == null) throw new NullPointerException("The only parameter of an AREA function must be different from NULL !"); @@ -66,7 +65,7 @@ public class AreaFunction extends GeometryFunction { * @throws Exception If there is an error during the copy. */ @SuppressWarnings("unchecked") - public AreaFunction(AreaFunction toCopy) throws Exception { + public AreaFunction(AreaFunction toCopy) throws Exception{ super(); parameter = (GeometryValue<GeometryFunction>)(toCopy.parameter.getCopy()); } @@ -76,7 +75,7 @@ public class AreaFunction extends GeometryFunction { * * @return A region. */ - public final GeometryValue<GeometryFunction> getParameter() { + public final GeometryValue<GeometryFunction> getParameter(){ return parameter; } @@ -85,47 +84,47 @@ public class AreaFunction extends GeometryFunction { * * @param parameter A region. */ - public final void setParameter(GeometryValue<GeometryFunction> parameter) { + public final void setParameter(GeometryValue<GeometryFunction> parameter){ this.parameter = parameter; } - public ADQLObject getCopy() throws Exception { + public ADQLObject getCopy() throws Exception{ return new AreaFunction(this); } - public String getName() { + public String getName(){ return "AREA"; } - public boolean isNumeric() { + public boolean isNumeric(){ return true; } - public boolean isString() { + public boolean isString(){ return false; } @Override - public ADQLOperand[] getParameters() { + public ADQLOperand[] getParameters(){ return new ADQLOperand[]{parameter.getValue()}; } @Override - public int getNbParameters() { + public int getNbParameters(){ return 1; } @Override - public ADQLOperand getParameter(int index) throws ArrayIndexOutOfBoundsException { + public ADQLOperand getParameter(int index) throws ArrayIndexOutOfBoundsException{ if (index == 0) return parameter.getValue(); else - throw new ArrayIndexOutOfBoundsException("No "+index+"-th parameter for the function \""+getName()+"\" !"); + throw new ArrayIndexOutOfBoundsException("No " + index + "-th parameter for the function \"" + getName() + "\" !"); } @SuppressWarnings("unchecked") @Override - public ADQLOperand setParameter(int index, ADQLOperand replacer) throws ArrayIndexOutOfBoundsException, NullPointerException, Exception { + public ADQLOperand setParameter(int index, ADQLOperand replacer) throws ArrayIndexOutOfBoundsException, NullPointerException, Exception{ if (index == 0){ ADQLOperand replaced = parameter.getValue(); if (replacer == null) @@ -137,10 +136,10 @@ public class AreaFunction extends GeometryFunction { else if (replacer instanceof GeometryFunction) parameter.setGeometry((GeometryFunction)replacer); else - throw new Exception("Impossible to replace a GeometryValue/Column/GeometryFunction by a "+replacer.getClass().getName()+" ("+replacer.toADQL()+") !"); + throw new Exception("Impossible to replace a GeometryValue/Column/GeometryFunction by a " + replacer.getClass().getName() + " (" + replacer.toADQL() + ") !"); return replaced; }else - throw new ArrayIndexOutOfBoundsException("No "+index+"-th parameter for the function \""+getName()+"\" !"); + throw new ArrayIndexOutOfBoundsException("No " + index + "-th parameter for the function \"" + getName() + "\" !"); } } \ No newline at end of file diff --git a/src/adql/query/operand/function/geometry/BoxFunction.java b/src/adql/query/operand/function/geometry/BoxFunction.java index 07700c07dc4a14cffb303a10842eb2fa7caf67c4..e9071330227d2d550e05cebba42a20ae8faca7fa 100644 --- a/src/adql/query/operand/function/geometry/BoxFunction.java +++ b/src/adql/query/operand/function/geometry/BoxFunction.java @@ -56,7 +56,6 @@ public class BoxFunction extends GeometryFunction { /** The height of this box (in degrees). */ private ADQLOperand height; - /** * <p>Builds a BOX function.</p> * @@ -68,7 +67,7 @@ public class BoxFunction extends GeometryFunction { * @throws NullPointerException If one parameter is <i>null</i>. * @throws Exception If there is another error. */ - public BoxFunction(ADQLOperand coordinateSystem, ADQLOperand firstCoord, ADQLOperand secondCoord, ADQLOperand boxWidth, ADQLOperand boxHeight) throws NullPointerException, Exception { + public BoxFunction(ADQLOperand coordinateSystem, ADQLOperand firstCoord, ADQLOperand secondCoord, ADQLOperand boxWidth, ADQLOperand boxHeight) throws NullPointerException, Exception{ super(coordinateSystem); if (firstCoord == null || secondCoord == null || boxWidth == null || boxHeight == null) @@ -86,7 +85,7 @@ public class BoxFunction extends GeometryFunction { * @param toCopy The BOX function to copy. * @throws Exception If there is an error during the copy. */ - public BoxFunction(BoxFunction toCopy) throws Exception { + public BoxFunction(BoxFunction toCopy) throws Exception{ super(toCopy); coord1 = (ADQLOperand)(toCopy.coord1.getCopy()); coord2 = (ADQLOperand)(toCopy.coord2.getCopy()); @@ -94,19 +93,19 @@ public class BoxFunction extends GeometryFunction { height = (ADQLOperand)(toCopy.height.getCopy()); } - public ADQLObject getCopy() throws Exception { + public ADQLObject getCopy() throws Exception{ return new BoxFunction(this); } - public String getName() { + public String getName(){ return "BOX"; } - public boolean isNumeric() { + public boolean isNumeric(){ return false; } - public boolean isString() { + public boolean isString(){ return true; } @@ -115,7 +114,7 @@ public class BoxFunction extends GeometryFunction { * * @return The first coordinate. */ - public final ADQLOperand getCoord1() { + public final ADQLOperand getCoord1(){ return coord1; } @@ -124,7 +123,7 @@ public class BoxFunction extends GeometryFunction { * * @param coord1 The first coordinate. */ - public final void setCoord1(ADQLOperand coord1) { + public final void setCoord1(ADQLOperand coord1){ this.coord1 = coord1; } @@ -133,7 +132,7 @@ public class BoxFunction extends GeometryFunction { * * @return The second coordinate. */ - public final ADQLOperand getCoord2() { + public final ADQLOperand getCoord2(){ return coord2; } @@ -142,7 +141,7 @@ public class BoxFunction extends GeometryFunction { * * @param coord2 The second coordinate. */ - public final void setCoord2(ADQLOperand coord2) { + public final void setCoord2(ADQLOperand coord2){ this.coord2 = coord2; } @@ -151,7 +150,7 @@ public class BoxFunction extends GeometryFunction { * * @return The width. */ - public final ADQLOperand getWidth() { + public final ADQLOperand getWidth(){ return width; } @@ -160,7 +159,7 @@ public class BoxFunction extends GeometryFunction { * * @param width The width. */ - public final void setWidth(ADQLOperand width) { + public final void setWidth(ADQLOperand width){ this.width = width; } @@ -169,7 +168,7 @@ public class BoxFunction extends GeometryFunction { * * @return The height. */ - public final ADQLOperand getHeight() { + public final ADQLOperand getHeight(){ return height; } @@ -178,69 +177,69 @@ public class BoxFunction extends GeometryFunction { * * @param height The height. */ - public final void setHeight(ADQLOperand height) { + public final void setHeight(ADQLOperand height){ this.height = height; } @Override - public ADQLOperand[] getParameters() { - return new ADQLOperand[]{coordSys, coord1, coord2, width, height}; + public ADQLOperand[] getParameters(){ + return new ADQLOperand[]{coordSys,coord1,coord2,width,height}; } @Override - public int getNbParameters() { + public int getNbParameters(){ return 5; } @Override - public ADQLOperand getParameter(int index) throws ArrayIndexOutOfBoundsException { + public ADQLOperand getParameter(int index) throws ArrayIndexOutOfBoundsException{ switch(index){ - case 0: - return coordSys; - case 1: - return coord1; - case 2: - return coord2; - case 3: - return width; - case 4: - return height; - default: - throw new ArrayIndexOutOfBoundsException("No "+index+"-th parameter for the function \""+getName()+"\" !"); + case 0: + return coordSys; + case 1: + return coord1; + case 2: + return coord2; + case 3: + return width; + case 4: + return height; + default: + throw new ArrayIndexOutOfBoundsException("No " + index + "-th parameter for the function \"" + getName() + "\" !"); } } @Override - public ADQLOperand setParameter(int index, ADQLOperand replacer) throws ArrayIndexOutOfBoundsException, NullPointerException, Exception { + public ADQLOperand setParameter(int index, ADQLOperand replacer) throws ArrayIndexOutOfBoundsException, NullPointerException, Exception{ if (replacer == null) - throw new NullPointerException("Impossible to remove one parameter from a "+getName()+" function !"); + throw new NullPointerException("Impossible to remove one parameter from a " + getName() + " function !"); else if (!(replacer instanceof ADQLOperand)) - throw new Exception("Impossible to replace an ADQLOperand by a "+replacer.getClass().getName()+" ("+replacer.toADQL()+") !"); + throw new Exception("Impossible to replace an ADQLOperand by a " + replacer.getClass().getName() + " (" + replacer.toADQL() + ") !"); ADQLOperand replaced = null; switch(index){ - case 0: - replaced = coordSys; - setCoordinateSystem(replacer); - break; - case 1: - replaced = coord1; - coord1 = replacer; - break; - case 2: - replaced = coord2; - coord2 = replacer; - break; - case 3: - replaced = width; - width = replacer; - break; - case 4: - replaced = height; - height = replacer; - break; - default: - throw new ArrayIndexOutOfBoundsException("No "+index+"-th parameter for the function \""+getName()+"\" !"); + case 0: + replaced = coordSys; + setCoordinateSystem(replacer); + break; + case 1: + replaced = coord1; + coord1 = replacer; + break; + case 2: + replaced = coord2; + coord2 = replacer; + break; + case 3: + replaced = width; + width = replacer; + break; + case 4: + replaced = height; + height = replacer; + break; + default: + throw new ArrayIndexOutOfBoundsException("No " + index + "-th parameter for the function \"" + getName() + "\" !"); } return replaced; } diff --git a/src/adql/query/operand/function/geometry/CentroidFunction.java b/src/adql/query/operand/function/geometry/CentroidFunction.java index cabce5e08e6c9364a6f990aa1d21446062bc9bb6..88f80e3fe0a3d97d516f0b73b79ec35c71fcc0af 100644 --- a/src/adql/query/operand/function/geometry/CentroidFunction.java +++ b/src/adql/query/operand/function/geometry/CentroidFunction.java @@ -43,14 +43,13 @@ public class CentroidFunction extends GeometryFunction { /** The geometry whose the centroid must be extracted. */ protected GeometryValue<GeometryFunction> parameter; - /** * Builds a CENTROID function. * * @param param The geometry whose the centroid must be extracted. * @throws NullPointerException If the given parameter is <i>null</i>. */ - public CentroidFunction(GeometryValue<GeometryFunction> param) throws NullPointerException { + public CentroidFunction(GeometryValue<GeometryFunction> param) throws NullPointerException{ super(); if (param == null) throw new NullPointerException("The ADQL function CENTROID must have exactly one parameter !"); @@ -64,52 +63,52 @@ public class CentroidFunction extends GeometryFunction { * @throws Exception If there is an error during the copy. */ @SuppressWarnings("unchecked") - public CentroidFunction(CentroidFunction toCopy) throws Exception { + public CentroidFunction(CentroidFunction toCopy) throws Exception{ super(); parameter = (GeometryValue<GeometryFunction>)(toCopy.parameter.getCopy()); } - public ADQLObject getCopy() throws Exception { + public ADQLObject getCopy() throws Exception{ return new CentroidFunction(this); } - public String getName() { + public String getName(){ return "CENTROID"; } - public boolean isNumeric() { + public boolean isNumeric(){ return true; } - public boolean isString() { + public boolean isString(){ return false; } @Override - public ADQLOperand[] getParameters() { + public ADQLOperand[] getParameters(){ return new ADQLOperand[]{parameter.getValue()}; } @Override - public int getNbParameters() { + public int getNbParameters(){ return 1; } @Override - public ADQLOperand getParameter(int index) throws ArrayIndexOutOfBoundsException { + public ADQLOperand getParameter(int index) throws ArrayIndexOutOfBoundsException{ if (index == 0) return parameter.getValue(); else - throw new ArrayIndexOutOfBoundsException("No "+index+"-th parameter for the function \""+getName()+"\" !"); + throw new ArrayIndexOutOfBoundsException("No " + index + "-th parameter for the function \"" + getName() + "\" !"); } @SuppressWarnings("unchecked") @Override - public ADQLOperand setParameter(int index, ADQLOperand replacer) throws ArrayIndexOutOfBoundsException, NullPointerException, Exception { + public ADQLOperand setParameter(int index, ADQLOperand replacer) throws ArrayIndexOutOfBoundsException, NullPointerException, Exception{ if (index == 0){ ADQLOperand replaced = null; if (replacer == null) - throw new NullPointerException("Impossible to remove the only required parameter of the "+getName()+" function !"); + throw new NullPointerException("Impossible to remove the only required parameter of the " + getName() + " function !"); else if (replacer instanceof GeometryValue) parameter = (GeometryValue<GeometryFunction>)replacer; else if (replacer instanceof ADQLColumn) @@ -117,10 +116,10 @@ public class CentroidFunction extends GeometryFunction { else if (replacer instanceof GeometryFunction) parameter.setGeometry((GeometryFunction)replacer); else - throw new Exception("Impossible to replace a GeometryValue/Column/GeometryFunction by a "+replacer.getClass().getName()+" ("+replacer.toADQL()+") !"); + throw new Exception("Impossible to replace a GeometryValue/Column/GeometryFunction by a " + replacer.getClass().getName() + " (" + replacer.toADQL() + ") !"); return replaced; }else - throw new ArrayIndexOutOfBoundsException("No "+index+"-th parameter for the function \""+getName()+"\" !"); + throw new ArrayIndexOutOfBoundsException("No " + index + "-th parameter for the function \"" + getName() + "\" !"); } } \ No newline at end of file diff --git a/src/adql/query/operand/function/geometry/CircleFunction.java b/src/adql/query/operand/function/geometry/CircleFunction.java index b764b86aaa559c2dd13997e7962099773b7c10a8..aff59d89e1832212617fff22d4a6a8f2b27ad34a 100644 --- a/src/adql/query/operand/function/geometry/CircleFunction.java +++ b/src/adql/query/operand/function/geometry/CircleFunction.java @@ -49,7 +49,6 @@ public class CircleFunction extends GeometryFunction { /** The radius of the circle (in degrees). */ private ADQLOperand radius; - /** * Builds a CIRCLE function. * @@ -60,7 +59,7 @@ public class CircleFunction extends GeometryFunction { * @throws NullPointerException If at least one parameter is incorrect or if the coordinate system is unknown. * @throws Exception If there is another error. */ - public CircleFunction(ADQLOperand coordinateSystem, ADQLOperand firstCoord, ADQLOperand secondCoord, ADQLOperand radius) throws NullPointerException, Exception { + public CircleFunction(ADQLOperand coordinateSystem, ADQLOperand firstCoord, ADQLOperand secondCoord, ADQLOperand radius) throws NullPointerException, Exception{ super(coordinateSystem); if (firstCoord == null || secondCoord == null || radius == null) @@ -77,26 +76,26 @@ public class CircleFunction extends GeometryFunction { * @param toCopy The CIRCLE function to copy. * @throws Exception If there is an error during the copy. */ - public CircleFunction(CircleFunction toCopy) throws Exception { + public CircleFunction(CircleFunction toCopy) throws Exception{ super(toCopy); coord1 = (ADQLOperand)(toCopy.coord1.getCopy()); coord2 = (ADQLOperand)(toCopy.coord2.getCopy()); radius = (ADQLOperand)(toCopy.radius.getCopy()); } - public ADQLObject getCopy() throws Exception { + public ADQLObject getCopy() throws Exception{ return new CircleFunction(this); } - public String getName() { + public String getName(){ return "CIRCLE"; } - public boolean isNumeric() { + public boolean isNumeric(){ return false; } - public boolean isString() { + public boolean isString(){ return true; } @@ -105,7 +104,7 @@ public class CircleFunction extends GeometryFunction { * * @return The first coordinate. */ - public final ADQLOperand getCoord1() { + public final ADQLOperand getCoord1(){ return coord1; } @@ -114,7 +113,7 @@ public class CircleFunction extends GeometryFunction { * * @param coord1 The first coordinate. */ - public final void setCoord1(ADQLOperand coord1) { + public final void setCoord1(ADQLOperand coord1){ this.coord1 = coord1; } @@ -123,7 +122,7 @@ public class CircleFunction extends GeometryFunction { * * @return The second coordinate. */ - public final ADQLOperand getCoord2() { + public final ADQLOperand getCoord2(){ return coord2; } @@ -132,7 +131,7 @@ public class CircleFunction extends GeometryFunction { * * @param coord2 The second coordinate. */ - public final void setCoord2(ADQLOperand coord2) { + public final void setCoord2(ADQLOperand coord2){ this.coord2 = coord2; } @@ -141,7 +140,7 @@ public class CircleFunction extends GeometryFunction { * * @return The radius. */ - public final ADQLOperand getRadius() { + public final ADQLOperand getRadius(){ return radius; } @@ -150,61 +149,61 @@ public class CircleFunction extends GeometryFunction { * * @param radius The radius. */ - public final void setRadius(ADQLOperand radius) { + public final void setRadius(ADQLOperand radius){ this.radius = radius; } @Override - public ADQLOperand[] getParameters() { - return new ADQLOperand[]{coordSys, coord1, coord2, radius}; + public ADQLOperand[] getParameters(){ + return new ADQLOperand[]{coordSys,coord1,coord2,radius}; } @Override - public int getNbParameters() { + public int getNbParameters(){ return 4; } @Override - public ADQLOperand getParameter(int index) throws ArrayIndexOutOfBoundsException { + public ADQLOperand getParameter(int index) throws ArrayIndexOutOfBoundsException{ switch(index){ - case 0: - return coordSys; - case 1: - return coord1; - case 2: - return coord2; - case 3: - return radius; - default: - throw new ArrayIndexOutOfBoundsException("No "+index+"-th parameter for the function \""+getName()+"\" !"); + case 0: + return coordSys; + case 1: + return coord1; + case 2: + return coord2; + case 3: + return radius; + default: + throw new ArrayIndexOutOfBoundsException("No " + index + "-th parameter for the function \"" + getName() + "\" !"); } } @Override - public ADQLOperand setParameter(int index, ADQLOperand replacer) throws ArrayIndexOutOfBoundsException, NullPointerException, Exception { + public ADQLOperand setParameter(int index, ADQLOperand replacer) throws ArrayIndexOutOfBoundsException, NullPointerException, Exception{ if (replacer == null) - throw new NullPointerException("Impossible to remove one parameter of a "+getName()+" function !"); + throw new NullPointerException("Impossible to remove one parameter of a " + getName() + " function !"); ADQLOperand replaced = null; switch(index){ - case 0: - replaced = coordSys; - setCoordinateSystem(replacer); - break; - case 1: - replaced = coord1; - coord1 = replacer; - break; - case 2: - replaced = coord2; - coord2 = replacer; - break; - case 3: - replaced = radius; - radius = replacer; - break; - default: - throw new ArrayIndexOutOfBoundsException("No "+index+"-th parameter for the function \""+getName()+"\" !"); + case 0: + replaced = coordSys; + setCoordinateSystem(replacer); + break; + case 1: + replaced = coord1; + coord1 = replacer; + break; + case 2: + replaced = coord2; + coord2 = replacer; + break; + case 3: + replaced = radius; + radius = replacer; + break; + default: + throw new ArrayIndexOutOfBoundsException("No " + index + "-th parameter for the function \"" + getName() + "\" !"); } return replaced; } diff --git a/src/adql/query/operand/function/geometry/ContainsFunction.java b/src/adql/query/operand/function/geometry/ContainsFunction.java index 88d44fc77d143359506dcfb985e021ad642bf1f0..f97a9c7614240b3703aa1c75c97c9bcef54bbc2d 100644 --- a/src/adql/query/operand/function/geometry/ContainsFunction.java +++ b/src/adql/query/operand/function/geometry/ContainsFunction.java @@ -52,7 +52,6 @@ public class ContainsFunction extends GeometryFunction { /** The second geometry. */ private GeometryValue<GeometryFunction> rightParam; - /** * Builds a CONTAINS function. * @@ -60,7 +59,7 @@ public class ContainsFunction extends GeometryFunction { * @param right Its second geometry (the one which must include the first). * @throws NullPointerException If one parameter is <i>null</i>. */ - public ContainsFunction(GeometryValue<GeometryFunction> left, GeometryValue<GeometryFunction> right) throws NullPointerException { + public ContainsFunction(GeometryValue<GeometryFunction> left, GeometryValue<GeometryFunction> right) throws NullPointerException{ super(); if (left == null || right == null) throw new NullPointerException("A CONTAINS function must have two parameters different from NULL !"); @@ -76,39 +75,39 @@ public class ContainsFunction extends GeometryFunction { * @throws Exception If there is an error during the copy. */ @SuppressWarnings("unchecked") - public ContainsFunction(ContainsFunction toCopy) throws Exception { + public ContainsFunction(ContainsFunction toCopy) throws Exception{ super(); leftParam = (GeometryValue<GeometryFunction>)(toCopy.leftParam.getCopy()); rightParam = (GeometryValue<GeometryFunction>)(toCopy.rightParam.getCopy()); } - public ADQLObject getCopy() throws Exception { + public ADQLObject getCopy() throws Exception{ return new ContainsFunction(this); } - public String getName() { + public String getName(){ return "CONTAINS"; } - public boolean isNumeric() { + public boolean isNumeric(){ return true; } - public boolean isString() { + public boolean isString(){ return false; } /** * @return The leftParam. */ - public final GeometryValue<GeometryFunction> getLeftParam() { + public final GeometryValue<GeometryFunction> getLeftParam(){ return leftParam; } /** * @param leftParam The leftParam to set. */ - public final void setLeftParam(GeometryValue<GeometryFunction> leftParam) { + public final void setLeftParam(GeometryValue<GeometryFunction> leftParam){ if (leftParam != null) this.leftParam = leftParam; } @@ -116,45 +115,45 @@ public class ContainsFunction extends GeometryFunction { /** * @return The rightParam. */ - public final GeometryValue<GeometryFunction> getRightParam() { + public final GeometryValue<GeometryFunction> getRightParam(){ return rightParam; } /** * @param rightParam The rightParam to set. */ - public final void setRightParam(GeometryValue<GeometryFunction> rightParam) { + public final void setRightParam(GeometryValue<GeometryFunction> rightParam){ if (rightParam != null) this.rightParam = rightParam; } @Override - public ADQLOperand[] getParameters() { - return new ADQLOperand[]{leftParam, rightParam}; + public ADQLOperand[] getParameters(){ + return new ADQLOperand[]{leftParam,rightParam}; } @Override - public int getNbParameters() { + public int getNbParameters(){ return 2; } @Override - public ADQLOperand getParameter(int index) throws ArrayIndexOutOfBoundsException { + public ADQLOperand getParameter(int index) throws ArrayIndexOutOfBoundsException{ if (index == 0) return leftParam.getValue(); else if (index == 1) return rightParam.getValue(); else - throw new ArrayIndexOutOfBoundsException("No "+index+"-th parameter for the function \""+getName()+"\" !"); + throw new ArrayIndexOutOfBoundsException("No " + index + "-th parameter for the function \"" + getName() + "\" !"); } @Override @SuppressWarnings("unchecked") - public ADQLOperand setParameter(int index, ADQLOperand replacer) throws ArrayIndexOutOfBoundsException, NullPointerException, Exception { + public ADQLOperand setParameter(int index, ADQLOperand replacer) throws ArrayIndexOutOfBoundsException, NullPointerException, Exception{ if (replacer == null) - throw new NullPointerException("Impossible to remove one parameter from the "+getName()+" function !"); + throw new NullPointerException("Impossible to remove one parameter from the " + getName() + " function !"); else if (!(replacer instanceof GeometryValue || replacer instanceof ADQLColumn || replacer instanceof GeometryFunction)) - throw new Exception("Impossible to replace GeometryValue/Column/GeometryFunction by a "+replacer.getClass().getName()+" ("+replacer.toADQL()+") !"); + throw new Exception("Impossible to replace GeometryValue/Column/GeometryFunction by a " + replacer.getClass().getName() + " (" + replacer.toADQL() + ") !"); ADQLOperand replaced = null; if (index == 0){ @@ -174,7 +173,7 @@ public class ContainsFunction extends GeometryFunction { else if (replacer instanceof GeometryFunction) rightParam.setGeometry((GeometryFunction)replacer); }else - throw new ArrayIndexOutOfBoundsException("No "+index+"-th parameter for the function \""+getName()+"\" !"); + throw new ArrayIndexOutOfBoundsException("No " + index + "-th parameter for the function \"" + getName() + "\" !"); return replaced; } diff --git a/src/adql/query/operand/function/geometry/DistanceFunction.java b/src/adql/query/operand/function/geometry/DistanceFunction.java index 774585d49840c04121173f6aad9eaa85d8ee083b..d9429675837a943e30a23ad807ef5611ba98964c 100644 --- a/src/adql/query/operand/function/geometry/DistanceFunction.java +++ b/src/adql/query/operand/function/geometry/DistanceFunction.java @@ -45,7 +45,6 @@ public class DistanceFunction extends GeometryFunction { /** The second point. */ private GeometryValue<PointFunction> p2; - /** * Builds a DISTANCE function. * @@ -53,7 +52,7 @@ public class DistanceFunction extends GeometryFunction { * @param point2 The second point. * @throws NullPointerException If one of the parameters are incorrect. */ - public DistanceFunction(GeometryValue<PointFunction> point1, GeometryValue<PointFunction> point2) throws NullPointerException { + public DistanceFunction(GeometryValue<PointFunction> point1, GeometryValue<PointFunction> point2) throws NullPointerException{ super(); if (point1 == null || point2 == null) throw new NullPointerException("All parameters of the DISTANCE function must be different from null !"); @@ -69,30 +68,30 @@ public class DistanceFunction extends GeometryFunction { * @throws Exception If there is an error during the copy. */ @SuppressWarnings("unchecked") - public DistanceFunction(DistanceFunction toCopy) throws Exception { + public DistanceFunction(DistanceFunction toCopy) throws Exception{ super(toCopy); p1 = (GeometryValue<PointFunction>)(toCopy.p1.getCopy()); p2 = (GeometryValue<PointFunction>)(toCopy.p2.getCopy()); } @Override - public void setCoordinateSystem(ADQLOperand coordSys) throws UnsupportedOperationException { + public void setCoordinateSystem(ADQLOperand coordSys) throws UnsupportedOperationException{ throw new UnsupportedOperationException("A DISTANCE function is not associated to a coordinate system !"); } - public ADQLObject getCopy() throws Exception { + public ADQLObject getCopy() throws Exception{ return new DistanceFunction(this); } - public String getName() { + public String getName(){ return "DISTANCE"; } - public boolean isNumeric() { + public boolean isNumeric(){ return true; } - public boolean isString() { + public boolean isString(){ return false; } @@ -101,7 +100,7 @@ public class DistanceFunction extends GeometryFunction { * * @return A point. */ - public final GeometryValue<PointFunction> getP1() { + public final GeometryValue<PointFunction> getP1(){ return p1; } @@ -110,7 +109,7 @@ public class DistanceFunction extends GeometryFunction { * * @param p1 A point. */ - public final void setP1(GeometryValue<PointFunction> p1) { + public final void setP1(GeometryValue<PointFunction> p1){ this.p1 = p1; } @@ -119,7 +118,7 @@ public class DistanceFunction extends GeometryFunction { * * @return A point. */ - public final GeometryValue<PointFunction> getP2() { + public final GeometryValue<PointFunction> getP2(){ return p2; } @@ -128,59 +127,59 @@ public class DistanceFunction extends GeometryFunction { * * @param p2 A point. */ - public final void setP2(GeometryValue<PointFunction> p2) { + public final void setP2(GeometryValue<PointFunction> p2){ this.p2 = p2; } @Override - public ADQLOperand[] getParameters() { - return new ADQLOperand[]{p1.getValue(), p2.getValue()}; + public ADQLOperand[] getParameters(){ + return new ADQLOperand[]{p1.getValue(),p2.getValue()}; } @Override - public int getNbParameters() { + public int getNbParameters(){ return 2; } @Override - public ADQLOperand getParameter(int index) throws ArrayIndexOutOfBoundsException { + public ADQLOperand getParameter(int index) throws ArrayIndexOutOfBoundsException{ switch(index){ - case 0: - return p1.getValue(); - case 1: - return p2.getValue(); - default: - throw new ArrayIndexOutOfBoundsException("No "+index+"-th parameter for the function \""+getName()+"\" !"); + case 0: + return p1.getValue(); + case 1: + return p2.getValue(); + default: + throw new ArrayIndexOutOfBoundsException("No " + index + "-th parameter for the function \"" + getName() + "\" !"); } } @SuppressWarnings("unchecked") @Override - public ADQLOperand setParameter(int index, ADQLOperand replacer) throws ArrayIndexOutOfBoundsException, NullPointerException, Exception { + public ADQLOperand setParameter(int index, ADQLOperand replacer) throws ArrayIndexOutOfBoundsException, NullPointerException, Exception{ if (replacer == null) - throw new NullPointerException("Impossible to remove a parameter from the function "+getName()+" !"); + throw new NullPointerException("Impossible to remove a parameter from the function " + getName() + " !"); else if (!(replacer instanceof GeometryValue || replacer instanceof ADQLColumn || replacer instanceof PointFunction)) - throw new Exception("Impossible to replace a GeometryValue/Column/PointFunction by "+replacer.getClass().getName()+" ("+replacer.toADQL()+") !"); + throw new Exception("Impossible to replace a GeometryValue/Column/PointFunction by " + replacer.getClass().getName() + " (" + replacer.toADQL() + ") !"); ADQLOperand replaced = null; GeometryValue<PointFunction> toUpdate = null; switch(index){ - case 0: - replaced = p1.getValue(); - if (replacer instanceof GeometryValue) - p1 = (GeometryValue<PointFunction>)replacer; - else - toUpdate = p1; - break; - case 1: - replaced = p2.getValue(); - if (replacer instanceof GeometryValue) - p2 = (GeometryValue<PointFunction>)replacer; - else - toUpdate = p2; - break; - default: - throw new ArrayIndexOutOfBoundsException("No "+index+"-th parameter for the function \""+getName()+"\" !"); + case 0: + replaced = p1.getValue(); + if (replacer instanceof GeometryValue) + p1 = (GeometryValue<PointFunction>)replacer; + else + toUpdate = p1; + break; + case 1: + replaced = p2.getValue(); + if (replacer instanceof GeometryValue) + p2 = (GeometryValue<PointFunction>)replacer; + else + toUpdate = p2; + break; + default: + throw new ArrayIndexOutOfBoundsException("No " + index + "-th parameter for the function \"" + getName() + "\" !"); } if (toUpdate != null){ diff --git a/src/adql/query/operand/function/geometry/ExtractCoord.java b/src/adql/query/operand/function/geometry/ExtractCoord.java index 529bfdd2da5871945c76d569fe21c6629e33894f..6f016c9c0ca356d495587262df438eb758ba4116 100644 --- a/src/adql/query/operand/function/geometry/ExtractCoord.java +++ b/src/adql/query/operand/function/geometry/ExtractCoord.java @@ -46,7 +46,6 @@ public class ExtractCoord extends GeometryFunction { /** The point from which the coordinate must be extracted. */ protected GeometryValue<PointFunction> point; - /** * Builds a COORD1 or a COORD2 function with the given point (a POINT function or a column which contains a POINT function). * @@ -55,14 +54,14 @@ public class ExtractCoord extends GeometryFunction { * @throws ArrayIndexOutOfBoundsException If the given index is different from 1 and 2. * @throws NullPointerException If the given geometry is <i>null</i>. */ - public ExtractCoord(int indiceCoord, GeometryValue<PointFunction> p) throws ArrayIndexOutOfBoundsException, NullPointerException { + public ExtractCoord(int indiceCoord, GeometryValue<PointFunction> p) throws ArrayIndexOutOfBoundsException, NullPointerException{ super(); if (indiceCoord <= 0 || indiceCoord > 2) throw new ArrayIndexOutOfBoundsException("Impossible to extract another coordinate that the two first: only COORD1 and COORD2 exists in ADQL !"); indCoord = indiceCoord; - if (p==null) - throw new NullPointerException("Impossible to build a COORD"+indCoord+" function without a point (a POINT function or a column which contains a POINT function) !"); + if (p == null) + throw new NullPointerException("Impossible to build a COORD" + indCoord + " function without a point (a POINT function or a column which contains a POINT function) !"); point = p; } @@ -73,52 +72,52 @@ public class ExtractCoord extends GeometryFunction { * @throws Exception If there is an error during the copy. */ @SuppressWarnings("unchecked") - public ExtractCoord(ExtractCoord toCopy) throws Exception { + public ExtractCoord(ExtractCoord toCopy) throws Exception{ super(); indCoord = toCopy.indCoord; point = (GeometryValue<PointFunction>)(toCopy.point.getCopy()); } - public String getName() { - return "COORD"+indCoord; + public String getName(){ + return "COORD" + indCoord; } - public ADQLObject getCopy() throws Exception { + public ADQLObject getCopy() throws Exception{ return new ExtractCoord(this); } - public boolean isNumeric() { + public boolean isNumeric(){ return true; } - public boolean isString() { + public boolean isString(){ return false; } @Override - public ADQLOperand[] getParameters() { + public ADQLOperand[] getParameters(){ return new ADQLOperand[]{point.getValue()}; } @Override - public int getNbParameters() { + public int getNbParameters(){ return 1; } @Override - public ADQLOperand getParameter(int index) throws ArrayIndexOutOfBoundsException { + public ADQLOperand getParameter(int index) throws ArrayIndexOutOfBoundsException{ if (index == 0) return point.getValue(); else - throw new ArrayIndexOutOfBoundsException("No "+index+"-th parameter for the function \""+getName()+"\" !"); + throw new ArrayIndexOutOfBoundsException("No " + index + "-th parameter for the function \"" + getName() + "\" !"); } @Override @SuppressWarnings("unchecked") - public ADQLOperand setParameter(int index, ADQLOperand replacer) throws ArrayIndexOutOfBoundsException, NullPointerException, Exception { + public ADQLOperand setParameter(int index, ADQLOperand replacer) throws ArrayIndexOutOfBoundsException, NullPointerException, Exception{ if (index == 0){ if (replacer == null) - throw new NullPointerException("Impossible to remove the only required parameter of the function "+getName()+" !"); + throw new NullPointerException("Impossible to remove the only required parameter of the function " + getName() + " !"); ADQLOperand replaced = point.getValue(); if (replacer instanceof GeometryValue) point = (GeometryValue<PointFunction>)replacer; @@ -127,10 +126,10 @@ public class ExtractCoord extends GeometryFunction { else if (replacer instanceof PointFunction) point.setGeometry((PointFunction)replacer); else - throw new Exception("Impossible to replace GeometryValue/Column/PointFunction by a "+replacer.getClass().getName()+" ("+replacer.toADQL()+") !"); + throw new Exception("Impossible to replace GeometryValue/Column/PointFunction by a " + replacer.getClass().getName() + " (" + replacer.toADQL() + ") !"); return replaced; }else - throw new ArrayIndexOutOfBoundsException("No "+index+"-th parameter for the function \""+getName()+"\" !"); + throw new ArrayIndexOutOfBoundsException("No " + index + "-th parameter for the function \"" + getName() + "\" !"); } } \ No newline at end of file diff --git a/src/adql/query/operand/function/geometry/ExtractCoordSys.java b/src/adql/query/operand/function/geometry/ExtractCoordSys.java index 6c2d20325ce1515d42d008b30edd30a9089d61a5..5337f494b43151115804d82f0139fa3c1bd4083c 100644 --- a/src/adql/query/operand/function/geometry/ExtractCoordSys.java +++ b/src/adql/query/operand/function/geometry/ExtractCoordSys.java @@ -43,7 +43,6 @@ public class ExtractCoordSys extends GeometryFunction { /** The geometry from which the coordinate system string must be extracted. */ protected GeometryValue<GeometryFunction> geomExpr; - /** * Builds a COORDSYS function. * @@ -61,52 +60,52 @@ public class ExtractCoordSys extends GeometryFunction { * @throws Exception If there is an error during the copy. */ @SuppressWarnings("unchecked") - public ExtractCoordSys(ExtractCoordSys toCopy) throws Exception { + public ExtractCoordSys(ExtractCoordSys toCopy) throws Exception{ super(); geomExpr = (GeometryValue<GeometryFunction>)(toCopy.geomExpr.getCopy()); } - public ADQLObject getCopy() throws Exception { + public ADQLObject getCopy() throws Exception{ return new ExtractCoordSys(this); } - public String getName() { + public String getName(){ return "COORDSYS"; } - public boolean isNumeric() { + public boolean isNumeric(){ return false; } - public boolean isString() { + public boolean isString(){ return true; } @Override - public ADQLOperand[] getParameters() { + public ADQLOperand[] getParameters(){ return new ADQLOperand[]{geomExpr.getValue()}; } @Override - public int getNbParameters() { + public int getNbParameters(){ return 1; } @Override - public ADQLOperand getParameter(int index) throws ArrayIndexOutOfBoundsException { + public ADQLOperand getParameter(int index) throws ArrayIndexOutOfBoundsException{ if (index == 0) return geomExpr.getValue(); else - throw new ArrayIndexOutOfBoundsException("No "+index+"-th parameter for the function "+getName()+" !"); + throw new ArrayIndexOutOfBoundsException("No " + index + "-th parameter for the function " + getName() + " !"); } @SuppressWarnings("unchecked") @Override - public ADQLOperand setParameter(int index, ADQLOperand replacer) throws ArrayIndexOutOfBoundsException, NullPointerException, Exception { + public ADQLOperand setParameter(int index, ADQLOperand replacer) throws ArrayIndexOutOfBoundsException, NullPointerException, Exception{ if (index == 0){ ADQLOperand replaced = geomExpr.getValue(); if (replacer == null) - throw new NullPointerException("Impossible to remove the only required parameter of the "+getName()+" function !"); + throw new NullPointerException("Impossible to remove the only required parameter of the " + getName() + " function !"); else if (replacer instanceof GeometryValue) geomExpr = (GeometryValue<GeometryFunction>)replacer; else if (replacer instanceof ADQLColumn) @@ -114,10 +113,10 @@ public class ExtractCoordSys extends GeometryFunction { else if (replacer instanceof GeometryFunction) geomExpr.setGeometry((GeometryFunction)replacer); else - throw new Exception("Impossible to replace GeometryValue/Column/GeometryFunction by a "+replacer.getClass().getName()+" ("+replacer.toADQL()+") !"); + throw new Exception("Impossible to replace GeometryValue/Column/GeometryFunction by a " + replacer.getClass().getName() + " (" + replacer.toADQL() + ") !"); return replaced; }else - throw new ArrayIndexOutOfBoundsException("No "+index+"-th parameter for the function "+getName()+" !"); + throw new ArrayIndexOutOfBoundsException("No " + index + "-th parameter for the function " + getName() + " !"); } } \ No newline at end of file diff --git a/src/adql/query/operand/function/geometry/GeometryFunction.java b/src/adql/query/operand/function/geometry/GeometryFunction.java index 9eba7d3add1beaff1ef1d5ef6765f079639f5bfe..4270eb183e469f6c6f144d7202a57766b9e64b19 100644 --- a/src/adql/query/operand/function/geometry/GeometryFunction.java +++ b/src/adql/query/operand/function/geometry/GeometryFunction.java @@ -36,7 +36,6 @@ public abstract class GeometryFunction extends ADQLFunction { /** The coordinate system used to express the coordinates. */ protected ADQLOperand coordSys = null; - /** * Builds a geometry function with no coordinate system. */ @@ -52,7 +51,7 @@ public abstract class GeometryFunction extends ADQLFunction { * @throws NullPointerException If the given operand is <i>null</i>. * @throws Exception If the given operand is not a string. */ - protected GeometryFunction(ADQLOperand coordSys) throws UnsupportedOperationException, NullPointerException, Exception { + protected GeometryFunction(ADQLOperand coordSys) throws UnsupportedOperationException, NullPointerException, Exception{ setCoordinateSystem(coordSys); } @@ -62,7 +61,7 @@ public abstract class GeometryFunction extends ADQLFunction { * @param toCopy The geometry function to copy. * @throws Exception If there is an error during the copy. */ - protected GeometryFunction(GeometryFunction toCopy) throws Exception { + protected GeometryFunction(GeometryFunction toCopy) throws Exception{ coordSys = (ADQLOperand)(toCopy.coordSys.getCopy()); } @@ -83,16 +82,15 @@ public abstract class GeometryFunction extends ADQLFunction { * @throws NullPointerException If the given operand is <i>null</i>. * @throws Exception If the given operand is not a string. */ - public void setCoordinateSystem(ADQLOperand coordSys) throws UnsupportedOperationException, NullPointerException, Exception { + public void setCoordinateSystem(ADQLOperand coordSys) throws UnsupportedOperationException, NullPointerException, Exception{ if (coordSys == null) throw new NullPointerException(""); else if (!coordSys.isString()) - throw new Exception("A coordinate system must be a string literal: \""+coordSys.toADQL()+"\" is not a string operand !"); + throw new Exception("A coordinate system must be a string literal: \"" + coordSys.toADQL() + "\" is not a string operand !"); else this.coordSys = coordSys; } - /** * This class represents a parameter of a geometry function * which, in general, is either a GeometryFunction or a Column. @@ -100,26 +98,26 @@ public abstract class GeometryFunction extends ADQLFunction { * @author Grégory Mantelet (CDS) * @version 06/2011 */ - public static final class GeometryValue<F extends GeometryFunction> implements ADQLOperand { + public static final class GeometryValue< F extends GeometryFunction > implements ADQLOperand { private ADQLColumn column; private F geomFunct; - public GeometryValue(ADQLColumn col) throws NullPointerException { + public GeometryValue(ADQLColumn col) throws NullPointerException{ if (col == null) throw new NullPointerException("Impossible to build a GeometryValue without a column or a geometry function !"); setColumn(col); } - public GeometryValue(F geometry) throws NullPointerException { + public GeometryValue(F geometry) throws NullPointerException{ if (geometry == null) throw new NullPointerException("Impossible to build a GeometryValue without a column or a geometry function !"); setGeometry(geometry); } @SuppressWarnings("unchecked") - public GeometryValue(GeometryValue<F> toCopy) throws Exception { - column = (toCopy.column == null)?null:((ADQLColumn)(toCopy.column.getCopy())); - geomFunct = (toCopy.geomFunct == null)?null:((F)(toCopy.geomFunct.getCopy())); + public GeometryValue(GeometryValue<F> toCopy) throws Exception{ + column = (toCopy.column == null) ? null : ((ADQLColumn)(toCopy.column.getCopy())); + geomFunct = (toCopy.geomFunct == null) ? null : ((F)(toCopy.geomFunct.getCopy())); } public void setColumn(ADQLColumn col){ @@ -137,26 +135,26 @@ public abstract class GeometryFunction extends ADQLFunction { } public ADQLOperand getValue(){ - return (column != null)?column:geomFunct; + return (column != null) ? column : geomFunct; } public boolean isColumn(){ return column != null; } - public boolean isNumeric() { + public boolean isNumeric(){ return getValue().isNumeric(); } - public boolean isString() { + public boolean isString(){ return getValue().isString(); } - public ADQLObject getCopy() throws Exception { + public ADQLObject getCopy() throws Exception{ return new GeometryValue<F>(this); } - public String getName() { + public String getName(){ return getValue().getName(); } @@ -164,7 +162,7 @@ public abstract class GeometryFunction extends ADQLFunction { return getValue().adqlIterator(); } - public String toADQL() { + public String toADQL(){ return getValue().toADQL(); } } diff --git a/src/adql/query/operand/function/geometry/IntersectsFunction.java b/src/adql/query/operand/function/geometry/IntersectsFunction.java index a07d71beb1ea6b9987f0a18025edac84838bde12..0a37597eadac5b751740c327abb68402f33be157 100644 --- a/src/adql/query/operand/function/geometry/IntersectsFunction.java +++ b/src/adql/query/operand/function/geometry/IntersectsFunction.java @@ -53,7 +53,6 @@ public class IntersectsFunction extends GeometryFunction { /** The second geometry. */ private GeometryValue<GeometryFunction> rightParam; - /** * Builds an INTERSECTS function. * @@ -61,7 +60,7 @@ public class IntersectsFunction extends GeometryFunction { * @param param2 The second geometry. * @throws NullPointerException If there is an error with at least one of the parameters. */ - public IntersectsFunction(GeometryValue<GeometryFunction> param1, GeometryValue<GeometryFunction> param2) throws NullPointerException { + public IntersectsFunction(GeometryValue<GeometryFunction> param1, GeometryValue<GeometryFunction> param2) throws NullPointerException{ super(); if (param1 == null || param2 == null) throw new NullPointerException("An INTERSECTS function must have two parameters different from NULL !"); @@ -77,39 +76,39 @@ public class IntersectsFunction extends GeometryFunction { * @throws Exception If there is an error during the copy. */ @SuppressWarnings("unchecked") - public IntersectsFunction(IntersectsFunction toCopy) throws Exception { + public IntersectsFunction(IntersectsFunction toCopy) throws Exception{ super(); leftParam = (GeometryValue<GeometryFunction>)(toCopy.leftParam.getCopy()); rightParam = (GeometryValue<GeometryFunction>)(toCopy.rightParam.getCopy()); } - public ADQLObject getCopy() throws Exception { + public ADQLObject getCopy() throws Exception{ return new IntersectsFunction(this); } - public String getName() { + public String getName(){ return "INTERSECTS"; } - public boolean isNumeric() { + public boolean isNumeric(){ return true; } - public boolean isString() { + public boolean isString(){ return false; } /** * @return The leftParam. */ - public final GeometryValue<GeometryFunction> getLeftParam() { + public final GeometryValue<GeometryFunction> getLeftParam(){ return leftParam; } /** * @param leftParam The leftParam to set. */ - public final void setLeftParam(GeometryValue<GeometryFunction> leftParam) { + public final void setLeftParam(GeometryValue<GeometryFunction> leftParam){ if (leftParam != null) this.leftParam = leftParam; } @@ -117,45 +116,45 @@ public class IntersectsFunction extends GeometryFunction { /** * @return The rightParam. */ - public final GeometryValue<GeometryFunction> getRightParam() { + public final GeometryValue<GeometryFunction> getRightParam(){ return rightParam; } /** * @param rightParam The rightParam to set. */ - public final void setRightParam(GeometryValue<GeometryFunction> rightParam) { + public final void setRightParam(GeometryValue<GeometryFunction> rightParam){ if (rightParam != null) this.rightParam = rightParam; } @Override - public ADQLOperand[] getParameters() { - return new ADQLOperand[]{leftParam, rightParam}; + public ADQLOperand[] getParameters(){ + return new ADQLOperand[]{leftParam,rightParam}; } @Override - public int getNbParameters() { + public int getNbParameters(){ return 2; } @Override - public ADQLOperand getParameter(int index) throws ArrayIndexOutOfBoundsException { + public ADQLOperand getParameter(int index) throws ArrayIndexOutOfBoundsException{ if (index == 0) return leftParam.getValue(); else if (index == 1) return rightParam.getValue(); else - throw new ArrayIndexOutOfBoundsException("No "+index+"-th parameter for the function \""+getName()+"\" !"); + throw new ArrayIndexOutOfBoundsException("No " + index + "-th parameter for the function \"" + getName() + "\" !"); } @Override @SuppressWarnings("unchecked") - public ADQLOperand setParameter(int index, ADQLOperand replacer) throws ArrayIndexOutOfBoundsException, NullPointerException, Exception { + public ADQLOperand setParameter(int index, ADQLOperand replacer) throws ArrayIndexOutOfBoundsException, NullPointerException, Exception{ if (replacer == null) - throw new NullPointerException("Impossible to remove one parameter from a "+getName()+" function !"); + throw new NullPointerException("Impossible to remove one parameter from a " + getName() + " function !"); else if (!(replacer instanceof GeometryValue || replacer instanceof ADQLColumn || replacer instanceof GeometryFunction)) - throw new Exception("Impossible to replace a GeometryValue/Column/GeometryFunction by a "+replacer.getClass().getName()+" ("+replacer.toADQL()+") !"); + throw new Exception("Impossible to replace a GeometryValue/Column/GeometryFunction by a " + replacer.getClass().getName() + " (" + replacer.toADQL() + ") !"); ADQLOperand replaced = null; if (index == 0){ @@ -175,7 +174,7 @@ public class IntersectsFunction extends GeometryFunction { else if (replacer instanceof GeometryFunction) rightParam.setGeometry((GeometryFunction)replacer); }else - throw new ArrayIndexOutOfBoundsException("No "+index+"-th parameter for the function \""+getName()+"\" !"); + throw new ArrayIndexOutOfBoundsException("No " + index + "-th parameter for the function \"" + getName() + "\" !"); return replaced; } diff --git a/src/adql/query/operand/function/geometry/PointFunction.java b/src/adql/query/operand/function/geometry/PointFunction.java index aa9fb5f0bb7209f5d325915c798c444f764c521f..626e34f22a0cbd7ed93ec71ea5f228cc87643f6a 100644 --- a/src/adql/query/operand/function/geometry/PointFunction.java +++ b/src/adql/query/operand/function/geometry/PointFunction.java @@ -45,7 +45,6 @@ public class PointFunction extends GeometryFunction { /** The second coordinate for this position. */ private ADQLOperand coord2; - /** * Builds a POINT function. * @@ -56,7 +55,7 @@ public class PointFunction extends GeometryFunction { * @throws NullPointerException If the given operand is <i>null</i>. * @throws ParseException If at least one of the given parameters is incorrect. */ - public PointFunction(ADQLOperand coordinateSystem, ADQLOperand firstCoord, ADQLOperand secondCoord) throws UnsupportedOperationException, NullPointerException, Exception { + public PointFunction(ADQLOperand coordinateSystem, ADQLOperand firstCoord, ADQLOperand secondCoord) throws UnsupportedOperationException, NullPointerException, Exception{ super(coordinateSystem); if (firstCoord == null || secondCoord == null) @@ -72,7 +71,7 @@ public class PointFunction extends GeometryFunction { * @param toCopy The POINT function to copy. * @throws Exception If there is an error during the copy. */ - public PointFunction(PointFunction toCopy) throws Exception { + public PointFunction(PointFunction toCopy) throws Exception{ super(toCopy); coord1 = (ADQLOperand)toCopy.coord1.getCopy(); coord2 = (ADQLOperand)toCopy.coord2.getCopy(); @@ -83,7 +82,7 @@ public class PointFunction extends GeometryFunction { * * @return Its first coordinate. */ - public final ADQLOperand getCoord1() { + public final ADQLOperand getCoord1(){ return coord1; } @@ -94,7 +93,7 @@ public class PointFunction extends GeometryFunction { * @throws NullPointerException If the given operand is <i>null</i>. * @throws Exception If the given operand is not numeric. */ - public void setCoord1(ADQLOperand coord1) throws NullPointerException, Exception { + public void setCoord1(ADQLOperand coord1) throws NullPointerException, Exception{ if (coord1 == null) throw new NullPointerException("The first coordinate of a POINT function must be different from NULL !"); else if (!coord1.isNumeric()) @@ -108,7 +107,7 @@ public class PointFunction extends GeometryFunction { * * @return Its second coordinate. */ - public final ADQLOperand getCoord2() { + public final ADQLOperand getCoord2(){ return coord2; } @@ -119,7 +118,7 @@ public class PointFunction extends GeometryFunction { * @throws NullPointerException If the given operand is <i>null</i>. * @throws Exception If the given operand is not numeric. */ - public void setCoord2(ADQLOperand coord2) throws NullPointerException, Exception { + public void setCoord2(ADQLOperand coord2) throws NullPointerException, Exception{ if (coord2 == null) throw new NullPointerException("The second coordinate of a POINT function must be different from NULL !"); else if (!coord2.isNumeric()) @@ -128,67 +127,67 @@ public class PointFunction extends GeometryFunction { this.coord2 = coord2; } - public ADQLObject getCopy() throws Exception { + public ADQLObject getCopy() throws Exception{ return new PointFunction(this); } - public String getName() { + public String getName(){ return "POINT"; } - public boolean isNumeric() { + public boolean isNumeric(){ return false; } - public boolean isString() { + public boolean isString(){ return true; } @Override - public ADQLOperand[] getParameters() { - return new ADQLOperand[]{coordSys, coord1, coord2}; + public ADQLOperand[] getParameters(){ + return new ADQLOperand[]{coordSys,coord1,coord2}; } @Override - public int getNbParameters() { + public int getNbParameters(){ return 3; } @Override - public ADQLOperand getParameter(int index) throws ArrayIndexOutOfBoundsException { + public ADQLOperand getParameter(int index) throws ArrayIndexOutOfBoundsException{ switch(index){ - case 0: - return getCoordinateSystem(); - case 1: - return getCoord1(); - case 2: - return getCoord2(); - default: - throw new ArrayIndexOutOfBoundsException("No "+index+"-th parameter for the function \""+getName()+" !"); + case 0: + return getCoordinateSystem(); + case 1: + return getCoord1(); + case 2: + return getCoord2(); + default: + throw new ArrayIndexOutOfBoundsException("No " + index + "-th parameter for the function \"" + getName() + " !"); } } @Override - public ADQLOperand setParameter(int index, ADQLOperand replacer) throws ArrayIndexOutOfBoundsException, NullPointerException, Exception { + public ADQLOperand setParameter(int index, ADQLOperand replacer) throws ArrayIndexOutOfBoundsException, NullPointerException, Exception{ if (replacer == null) - throw new NullPointerException("Impossible to remove a parameter from the function "+getName()+" !"); + throw new NullPointerException("Impossible to remove a parameter from the function " + getName() + " !"); ADQLOperand replaced = null; switch(index){ - case 0: - replaced = getCoordinateSystem(); - setCoordinateSystem(replacer); - break; - case 1: - replaced = getCoord1(); - setCoord1(replacer); - break; - case 2: - replaced = getCoord2(); - setCoord2(replacer); - break; - default: - throw new ArrayIndexOutOfBoundsException("No "+index+"-th parameter for the function \""+getName()+"\" !"); + case 0: + replaced = getCoordinateSystem(); + setCoordinateSystem(replacer); + break; + case 1: + replaced = getCoord1(); + setCoord1(replacer); + break; + case 2: + replaced = getCoord2(); + setCoord2(replacer); + break; + default: + throw new ArrayIndexOutOfBoundsException("No " + index + "-th parameter for the function \"" + getName() + "\" !"); } return replaced; diff --git a/src/adql/query/operand/function/geometry/PolygonFunction.java b/src/adql/query/operand/function/geometry/PolygonFunction.java index 29d71578148e1bd49c3fca6be912e8a7379b8636..07e47ba629e47d979dae71d4db2c36f33819f866 100644 --- a/src/adql/query/operand/function/geometry/PolygonFunction.java +++ b/src/adql/query/operand/function/geometry/PolygonFunction.java @@ -48,7 +48,6 @@ public class PolygonFunction extends GeometryFunction { /** The coordinates of vertices. */ protected Vector<ADQLOperand> coordinates; - /** * Builds a polygon function with at least 3 2-D coordinates (that is to say, the array must contain at least 6 operands). * @@ -59,13 +58,13 @@ public class PolygonFunction extends GeometryFunction { * @throws NullPointerException If one of the parameters is <i>null</i>. * @throws Exception If there is another error. */ - public PolygonFunction(ADQLOperand coordSystem, ADQLOperand[] coords) throws UnsupportedOperationException, NullPointerException, Exception { + public PolygonFunction(ADQLOperand coordSystem, ADQLOperand[] coords) throws UnsupportedOperationException, NullPointerException, Exception{ super(coordSystem); if (coords == null || coords.length < 6) throw new NullPointerException("A POLYGON function must have at least 3 2-D coordinates !"); else{ coordinates = new Vector<ADQLOperand>(coords.length); - for(int i=0; i<coords.length; i++) + for(int i = 0; i < coords.length; i++) coordinates.add(coords[i]); } } @@ -80,7 +79,7 @@ public class PolygonFunction extends GeometryFunction { * @throws NullPointerException If one of the parameters is <i>null</i>. * @throws Exception If there is another error. */ - public PolygonFunction(ADQLOperand coordSystem, Vector<ADQLOperand> coords) throws UnsupportedOperationException, NullPointerException, Exception { + public PolygonFunction(ADQLOperand coordSystem, Vector<ADQLOperand> coords) throws UnsupportedOperationException, NullPointerException, Exception{ super(coordSystem); if (coords == null || coords.size() < 6) throw new NullPointerException("A POLYGON function must have at least 3 2-D coordinates !"); @@ -96,57 +95,57 @@ public class PolygonFunction extends GeometryFunction { * @param toCopy The POLYGON function to copy. * @throws Exception If there is an error during the copy. */ - public PolygonFunction(PolygonFunction toCopy) throws Exception { + public PolygonFunction(PolygonFunction toCopy) throws Exception{ super(toCopy); coordinates = new Vector<ADQLOperand>(toCopy.coordinates.size()); for(ADQLOperand item : toCopy.coordinates) coordinates.add((ADQLOperand)(item.getCopy())); } - public ADQLObject getCopy() throws Exception { + public ADQLObject getCopy() throws Exception{ return new PolygonFunction(this); } - public String getName() { + public String getName(){ return "POLYGON"; } - public boolean isNumeric() { + public boolean isNumeric(){ return false; } - public boolean isString() { + public boolean isString(){ return true; } @Override - public ADQLOperand[] getParameters() { - ADQLOperand[] params = new ADQLOperand[coordinates.size()+1]; + public ADQLOperand[] getParameters(){ + ADQLOperand[] params = new ADQLOperand[coordinates.size() + 1]; params[0] = coordSys; - for(int i=0; i<coordinates.size(); i++) - params[i+1] = coordinates.get(i); + for(int i = 0; i < coordinates.size(); i++) + params[i + 1] = coordinates.get(i); return params; } @Override - public int getNbParameters() { - return coordinates.size()+1; + public int getNbParameters(){ + return coordinates.size() + 1; } @Override - public ADQLOperand getParameter(int index) throws ArrayIndexOutOfBoundsException { + public ADQLOperand getParameter(int index) throws ArrayIndexOutOfBoundsException{ if (index == 0) return coordSys; else if (index >= 1 && index <= coordinates.size()) - return coordinates.get(index-1); + return coordinates.get(index - 1); else - throw new ArrayIndexOutOfBoundsException("No "+index+"-th parameter for the function \""+getName()+"\" ("+toADQL()+") !"); + throw new ArrayIndexOutOfBoundsException("No " + index + "-th parameter for the function \"" + getName() + "\" (" + toADQL() + ") !"); } @Override - public ADQLOperand setParameter(int index, ADQLOperand replacer) throws ArrayIndexOutOfBoundsException, NullPointerException, Exception { + public ADQLOperand setParameter(int index, ADQLOperand replacer) throws ArrayIndexOutOfBoundsException, NullPointerException, Exception{ if (replacer == null) throw new NullPointerException("Impossible to remove only one parameter from the function POLYGON !"); @@ -155,10 +154,10 @@ public class PolygonFunction extends GeometryFunction { replaced = coordSys; setCoordinateSystem(replacer); }else if (index >= 1 && index <= coordinates.size()){ - replaced = coordinates.get(index-1); - coordinates.set(index-1, replacer); + replaced = coordinates.get(index - 1); + coordinates.set(index - 1, replacer); }else - throw new ArrayIndexOutOfBoundsException("No "+index+"-th parameter for the function \""+getName()+"\" ("+toADQL()+") !"); + throw new ArrayIndexOutOfBoundsException("No " + index + "-th parameter for the function \"" + getName() + "\" (" + toADQL() + ") !"); return replaced; } diff --git a/src/adql/query/operand/function/geometry/RegionFunction.java b/src/adql/query/operand/function/geometry/RegionFunction.java index 3d5edb0d66b0b511e90d512ed71b3602ad44cd8f..04422da22f5ec191fa70ecae4ab5069676843136 100644 --- a/src/adql/query/operand/function/geometry/RegionFunction.java +++ b/src/adql/query/operand/function/geometry/RegionFunction.java @@ -45,14 +45,13 @@ public class RegionFunction extends GeometryFunction { /** The only parameter of this function. */ protected ADQLOperand parameter; - /** * Builds a REGION function. * * @param param The parameter (a string or a column reference or a concatenation or a user function). * @throws ParseException If the given parameter is <i>null</i>. */ - public RegionFunction(ADQLOperand param) throws NullPointerException, Exception { + public RegionFunction(ADQLOperand param) throws NullPointerException, Exception{ super(); if (param == null) throw new NullPointerException("The ADQL function REGION must have exactly one parameter !"); @@ -67,58 +66,58 @@ public class RegionFunction extends GeometryFunction { * @param toCopy The REGION function to copy. * @throws Exception If there is an error during the copy. */ - public RegionFunction(RegionFunction toCopy) throws Exception { + public RegionFunction(RegionFunction toCopy) throws Exception{ super(); parameter = (ADQLOperand)(toCopy.parameter.getCopy()); } - public ADQLObject getCopy() throws Exception { + public ADQLObject getCopy() throws Exception{ return new RegionFunction(this); } - public String getName() { + public String getName(){ return "REGION"; } - public boolean isNumeric() { + public boolean isNumeric(){ return false; } - public boolean isString() { + public boolean isString(){ return true; } @Override - public ADQLOperand[] getParameters() { + public ADQLOperand[] getParameters(){ return new ADQLOperand[]{parameter}; } @Override - public int getNbParameters() { + public int getNbParameters(){ return 1; } @Override - public ADQLOperand getParameter(int index) throws ArrayIndexOutOfBoundsException { + public ADQLOperand getParameter(int index) throws ArrayIndexOutOfBoundsException{ if (index == 0) return parameter; else - throw new ArrayIndexOutOfBoundsException("No "+index+"-th parameter for the function \""+getName()+"\" !"); + throw new ArrayIndexOutOfBoundsException("No " + index + "-th parameter for the function \"" + getName() + "\" !"); } @Override - public ADQLOperand setParameter(int index, ADQLOperand replacer) throws ArrayIndexOutOfBoundsException, NullPointerException, Exception { + public ADQLOperand setParameter(int index, ADQLOperand replacer) throws ArrayIndexOutOfBoundsException, NullPointerException, Exception{ if (index == 0){ if (replacer == null) - throw new NullPointerException("Impossible to remove the only required parameter of a "+getName()+" function !"); + throw new NullPointerException("Impossible to remove the only required parameter of a " + getName() + " function !"); else if (replacer instanceof ADQLOperand){ ADQLOperand replaced = parameter; parameter = replaced; return replaced; }else - throw new Exception("Impossible to replace an ADQLOperand by a "+replacer.getClass().getName()+" ("+replacer.toADQL()+") !"); + throw new Exception("Impossible to replace an ADQLOperand by a " + replacer.getClass().getName() + " (" + replacer.toADQL() + ") !"); }else - throw new ArrayIndexOutOfBoundsException("No "+index+"-th parameter for the function \""+getName()+"\" !"); + throw new ArrayIndexOutOfBoundsException("No " + index + "-th parameter for the function \"" + getName() + "\" !"); } } diff --git a/src/adql/search/RemoveHandler.java b/src/adql/search/RemoveHandler.java index 913b3633b71a2f29d6eb400e3d3d9398b4f37d7f..19b50efb325fd0e4075ab8925001b7ea6a8eb1fd 100644 --- a/src/adql/search/RemoveHandler.java +++ b/src/adql/search/RemoveHandler.java @@ -32,15 +32,15 @@ import adql.query.ADQLObject; */ public abstract class RemoveHandler extends SimpleReplaceHandler { - public RemoveHandler() { + public RemoveHandler(){ super(); } - public RemoveHandler(boolean recursive, boolean onlyFirstMatch) { + public RemoveHandler(boolean recursive, boolean onlyFirstMatch){ super(recursive, onlyFirstMatch); } - public RemoveHandler(boolean recursive) { + public RemoveHandler(boolean recursive){ super(recursive); } @@ -52,6 +52,8 @@ public abstract class RemoveHandler extends SimpleReplaceHandler { * @see adql.search.SimpleReplaceHandler#getReplacer(adql.query.ADQLObject) */ @Override - public ADQLObject getReplacer(ADQLObject objToReplace) { return null; } + public ADQLObject getReplacer(ADQLObject objToReplace){ + return null; + } } diff --git a/src/adql/search/SearchColumnHandler.java b/src/adql/search/SearchColumnHandler.java index acfe1110a41550f81d8106b91b0e808cc7bcb96b..5c9667c2d21bee65621f69edf42350b8e403a8b7 100644 --- a/src/adql/search/SearchColumnHandler.java +++ b/src/adql/search/SearchColumnHandler.java @@ -30,20 +30,20 @@ import adql.query.operand.ADQLColumn; */ public class SearchColumnHandler extends SimpleSearchHandler { - public SearchColumnHandler() { + public SearchColumnHandler(){ super(); } - public SearchColumnHandler(boolean recursive, boolean onlyFirstMatch) { + public SearchColumnHandler(boolean recursive, boolean onlyFirstMatch){ super(recursive, onlyFirstMatch); } - public SearchColumnHandler(boolean recursive) { + public SearchColumnHandler(boolean recursive){ super(recursive); } @Override - public boolean match(ADQLObject obj) { + public boolean match(ADQLObject obj){ return (obj instanceof ADQLColumn); } diff --git a/src/adql/search/SimpleReplaceHandler.java b/src/adql/search/SimpleReplaceHandler.java index bf8a71f719f0803f952f191a07426a8bbbee3633..7f144843bc113f5d6e825f53e7f089c6472873b3 100644 --- a/src/adql/search/SimpleReplaceHandler.java +++ b/src/adql/search/SimpleReplaceHandler.java @@ -44,7 +44,6 @@ public abstract class SimpleReplaceHandler extends SimpleSearchHandler implement /** Count matching objects which have been replaced successfully. */ protected int nbReplacement = 0; - /** * <p>Builds a SimpleReplaceHandler:</p> * <ul> @@ -75,8 +74,7 @@ public abstract class SimpleReplaceHandler extends SimpleSearchHandler implement super(recursive, onlyFirstMatch); } - - public int getNbReplacement() { + public int getNbReplacement(){ return nbReplacement; } @@ -87,7 +85,7 @@ public abstract class SimpleReplaceHandler extends SimpleSearchHandler implement } @Override - protected void addMatch(ADQLObject matchObj, ADQLIterator it) { + protected void addMatch(ADQLObject matchObj, ADQLIterator it){ super.addMatch(matchObj, it); if (replaceActive && it != null){ diff --git a/src/adql/search/SimpleSearchHandler.java b/src/adql/search/SimpleSearchHandler.java index a382e37c143636e818332575e20bae6e5cfaa1aa..d7305e68471b926aadcdf1f9187012f4d5e11934 100644 --- a/src/adql/search/SimpleSearchHandler.java +++ b/src/adql/search/SimpleSearchHandler.java @@ -51,7 +51,6 @@ public abstract class SimpleSearchHandler implements ISearchHandler { /** List of all matching ADQL objects. */ protected final ArrayList<ADQLObject> results; - /** * <p>Builds a SimpleSearchHandler:</p> * <ul> @@ -89,7 +88,7 @@ public abstract class SimpleSearchHandler implements ISearchHandler { * * @return <i>true</i> if recursive, <i>false</i> otherwise. */ - public final boolean isRecursive() { + public final boolean isRecursive(){ return recursive; } @@ -107,7 +106,7 @@ public abstract class SimpleSearchHandler implements ISearchHandler { * * @return <i>true</i> if it stops at the first match, <i>false</i> otherwise. */ - public final boolean onlyFirstMatch() { + public final boolean onlyFirstMatch(){ return firstMatch; } @@ -116,15 +115,15 @@ public abstract class SimpleSearchHandler implements ISearchHandler { * * @param firstMatch <i>true</i> if it must stop at the first match, <i>false</i> otherwise. */ - public final void setOnlyFirstMatch(boolean firstMatch) { + public final void setOnlyFirstMatch(boolean firstMatch){ this.firstMatch = firstMatch; } - public final Iterator<ADQLObject> iterator() { + public final Iterator<ADQLObject> iterator(){ return results.iterator(); } - public final int getNbMatch() { + public final int getNbMatch(){ return results.size(); } diff --git a/src/adql/translator/PgSphereTranslator.java b/src/adql/translator/PgSphereTranslator.java index ca21f748f77b749d9f4341f9322ab26444f8722d..efe38074322b8e850227a9f5169d2346b23958de 100644 --- a/src/adql/translator/PgSphereTranslator.java +++ b/src/adql/translator/PgSphereTranslator.java @@ -53,7 +53,7 @@ public class PgSphereTranslator extends PostgreSQLTranslator { * * @see PostgreSQLTranslator#PostgreSQLTranslator() */ - public PgSphereTranslator() { + public PgSphereTranslator(){ super(); } @@ -64,7 +64,7 @@ public class PgSphereTranslator extends PostgreSQLTranslator { * * @see PostgreSQLTranslator#PostgreSQLTranslator(boolean) */ - public PgSphereTranslator(boolean column) { + public PgSphereTranslator(boolean column){ super(column); } @@ -78,12 +78,12 @@ public class PgSphereTranslator extends PostgreSQLTranslator { * * @see PostgreSQLTranslator#PostgreSQLTranslator(boolean, boolean, boolean, boolean) */ - public PgSphereTranslator(boolean catalog, boolean schema, boolean table, boolean column) { + public PgSphereTranslator(boolean catalog, boolean schema, boolean table, boolean column){ super(catalog, schema, table, column); } @Override - public String translate(PointFunction point) throws TranslationException { + public String translate(PointFunction point) throws TranslationException{ StringBuffer str = new StringBuffer("spoint("); str.append("radians(").append(translate(point.getCoord1())).append("),"); str.append("radians(").append(translate(point.getCoord2())).append("))"); @@ -91,7 +91,7 @@ public class PgSphereTranslator extends PostgreSQLTranslator { } @Override - public String translate(CircleFunction circle) throws TranslationException { + public String translate(CircleFunction circle) throws TranslationException{ StringBuffer str = new StringBuffer("scircle("); str.append("spoint(radians(").append(translate(circle.getCoord1())).append("),"); str.append("radians(").append(translate(circle.getCoord2())).append(")),"); @@ -100,7 +100,7 @@ public class PgSphereTranslator extends PostgreSQLTranslator { } @Override - public String translate(BoxFunction box) throws TranslationException { + public String translate(BoxFunction box) throws TranslationException{ StringBuffer str = new StringBuffer("sbox("); str.append("spoint(").append("radians(").append(translate(box.getCoord1())).append("+(").append(translate(box.getWidth())).append("/2.0)),"); @@ -112,17 +112,17 @@ public class PgSphereTranslator extends PostgreSQLTranslator { } @Override - public String translate(PolygonFunction polygon) throws TranslationException { - try { + public String translate(PolygonFunction polygon) throws TranslationException{ + try{ StringBuffer str = new StringBuffer("spoly('{'"); if (polygon.getNbParameters() > 2){ PointFunction point = new PointFunction(polygon.getCoordinateSystem(), polygon.getParameter(1), polygon.getParameter(2)); str.append(" || ").append(translate(point)); - for(int i=3; i<polygon.getNbParameters() && i+1<polygon.getNbParameters(); i+=2){ + for(int i = 3; i < polygon.getNbParameters() && i + 1 < polygon.getNbParameters(); i += 2){ point.setCoord1(polygon.getParameter(i)); - point.setCoord2(polygon.getParameter(i+1)); + point.setCoord2(polygon.getParameter(i + 1)); str.append(" || ',' || ").append(translate(point)); } } @@ -130,14 +130,14 @@ public class PgSphereTranslator extends PostgreSQLTranslator { str.append(" || '}')"); return str.toString(); - } catch (Exception e) { + }catch(Exception e){ e.printStackTrace(); throw new TranslationException(e); } } @Override - public String translate(ExtractCoord extractCoord) throws TranslationException { + public String translate(ExtractCoord extractCoord) throws TranslationException{ StringBuffer str = new StringBuffer("degrees("); if (extractCoord.getName().equalsIgnoreCase("COORD1")) str.append("long("); @@ -148,43 +148,41 @@ public class PgSphereTranslator extends PostgreSQLTranslator { } @Override - public String translate(DistanceFunction fct) throws TranslationException { + public String translate(DistanceFunction fct) throws TranslationException{ StringBuffer str = new StringBuffer("degrees("); str.append(translate(fct.getP1())).append(" <-> ").append(translate(fct.getP2())).append(")"); return str.toString(); } @Override - public String translate(AreaFunction areaFunction) throws TranslationException { + public String translate(AreaFunction areaFunction) throws TranslationException{ StringBuffer str = new StringBuffer("degrees(area("); str.append(translate(areaFunction.getParameter())).append("))"); return str.toString(); } @Override - public String translate(ContainsFunction fct) throws TranslationException { + public String translate(ContainsFunction fct) throws TranslationException{ StringBuffer str = new StringBuffer("("); str.append(translate(fct.getLeftParam())).append(" @ ").append(translate(fct.getRightParam())).append(")"); return str.toString(); } @Override - public String translate(IntersectsFunction fct) throws TranslationException { + public String translate(IntersectsFunction fct) throws TranslationException{ StringBuffer str = new StringBuffer("("); str.append(translate(fct.getLeftParam())).append(" && ").append(translate(fct.getRightParam())).append(")"); return str.toString(); } @Override - public String translate(Comparison comp) throws TranslationException { + public String translate(Comparison comp) throws TranslationException{ if ((comp.getLeftOperand() instanceof ContainsFunction || comp.getLeftOperand() instanceof IntersectsFunction) && (comp.getOperator() == ComparisonOperator.EQUAL || comp.getOperator() == ComparisonOperator.NOT_EQUAL) && comp.getRightOperand().isNumeric()) - return translate(comp.getLeftOperand())+" "+comp.getOperator().toADQL()+" '"+translate(comp.getRightOperand())+"'"; + return translate(comp.getLeftOperand()) + " " + comp.getOperator().toADQL() + " '" + translate(comp.getRightOperand()) + "'"; else if ((comp.getRightOperand() instanceof ContainsFunction || comp.getRightOperand() instanceof IntersectsFunction) && (comp.getOperator() == ComparisonOperator.EQUAL || comp.getOperator() == ComparisonOperator.NOT_EQUAL) && comp.getLeftOperand().isNumeric()) - return "'"+translate(comp.getLeftOperand())+"' "+comp.getOperator().toADQL()+" "+translate(comp.getRightOperand()); + return "'" + translate(comp.getLeftOperand()) + "' " + comp.getOperator().toADQL() + " " + translate(comp.getRightOperand()); else return super.translate(comp); } - - } diff --git a/src/adql/translator/PostgreSQLTranslator.java b/src/adql/translator/PostgreSQLTranslator.java index 0c94c0119e9be8fe698ada6c929adba870934402..e49348089a44a6ee2cf38821ce0131df49215c90 100644 --- a/src/adql/translator/PostgreSQLTranslator.java +++ b/src/adql/translator/PostgreSQLTranslator.java @@ -179,7 +179,7 @@ public class PostgreSQLTranslator implements ADQLTranslator { } @SuppressWarnings("unchecked") - public String translate(ADQLObject obj) throws TranslationException { + public String translate(ADQLObject obj) throws TranslationException{ if (obj instanceof ADQLQuery) return translate((ADQLQuery)obj); else if (obj instanceof ADQLList) @@ -200,7 +200,7 @@ public class PostgreSQLTranslator implements ADQLTranslator { return obj.toADQL(); } - public String translate(ADQLQuery query) throws TranslationException { + public String translate(ADQLQuery query) throws TranslationException{ StringBuffer sql = new StringBuffer(translate(query.getSelect())); sql.append("\nFROM ").append(translate(query.getFrom())); @@ -226,7 +226,7 @@ public class PostgreSQLTranslator implements ADQLTranslator { /* *************************** */ /* ****** LIST & CLAUSE ****** */ /* *************************** */ - public String translate(ADQLList<? extends ADQLObject> list) throws TranslationException { + public String translate(ADQLList<? extends ADQLObject> list) throws TranslationException{ if (list instanceof ClauseSelect) return translate((ClauseSelect)list); else if (list instanceof ClauseConstraints) @@ -244,15 +244,15 @@ public class PostgreSQLTranslator implements ADQLTranslator { * * @throws TranslationException If there is an error during the translation. */ - protected String getDefaultADQLList(ADQLList<? extends ADQLObject> list) throws TranslationException { - String sql = (list.getName()==null)?"":(list.getName()+" "); + protected String getDefaultADQLList(ADQLList<? extends ADQLObject> list) throws TranslationException{ + String sql = (list.getName() == null) ? "" : (list.getName() + " "); boolean oldInSelect = inSelect; inSelect = (list.getName() != null) && list.getName().equalsIgnoreCase("select"); try{ - for(int i=0; i<list.size(); i++) - sql += ((i == 0)?"":(" "+list.getSeparator(i)+" ")) + translate(list.get(i)); + for(int i = 0; i < list.size(); i++) + sql += ((i == 0) ? "" : (" " + list.getSeparator(i) + " ")) + translate(list.get(i)); }finally{ inSelect = oldInSelect; } @@ -260,26 +260,26 @@ public class PostgreSQLTranslator implements ADQLTranslator { return sql; } - public String translate(ClauseSelect clause) throws TranslationException { + public String translate(ClauseSelect clause) throws TranslationException{ String sql = null; - for(int i=0; i<clause.size(); i++){ + for(int i = 0; i < clause.size(); i++){ if (i == 0){ - sql = clause.getName()+(clause.distinctColumns()?" DISTINCT":""); + sql = clause.getName() + (clause.distinctColumns() ? " DISTINCT" : ""); }else - sql += " "+clause.getSeparator(i); + sql += " " + clause.getSeparator(i); - sql += " "+translate(clause.get(i)); + sql += " " + translate(clause.get(i)); } return sql; } - public String translate(ClauseConstraints clause) throws TranslationException { + public String translate(ClauseConstraints clause) throws TranslationException{ return getDefaultADQLList(clause); } - public String translate(SelectItem item) throws TranslationException { + public String translate(SelectItem item) throws TranslationException{ if (item instanceof SelectAllColumns) return translate((SelectAllColumns)item); @@ -293,8 +293,8 @@ public class PostgreSQLTranslator implements ADQLTranslator { return translation.toString(); } - public String translate(SelectAllColumns item) throws TranslationException { - HashMap<String, String> mapAlias = new HashMap<String, String>(); + public String translate(SelectAllColumns item) throws TranslationException{ + HashMap<String,String> mapAlias = new HashMap<String,String>(); // Fetch the full list of columns to display: Iterable<DBColumn> dbCols = null; @@ -303,7 +303,7 @@ public class PostgreSQLTranslator implements ADQLTranslator { dbCols = table.getDBLink(); if (table.hasAlias()){ String key = appendFullDBName(new StringBuffer(), table.getDBLink()).toString(); - mapAlias.put(key, table.isCaseSensitive(IdentifierField.ALIAS) ? ("\""+table.getAlias()+"\"") : table.getAlias()); + mapAlias.put(key, table.isCaseSensitive(IdentifierField.ALIAS) ? ("\"" + table.getAlias() + "\"") : table.getAlias()); } }else if (item.getQuery() != null){ dbCols = item.getQuery().getFrom().getDBColumns(); @@ -311,7 +311,7 @@ public class PostgreSQLTranslator implements ADQLTranslator { for(ADQLTable table : tables){ if (table.hasAlias()){ String key = appendFullDBName(new StringBuffer(), table.getDBLink()).toString(); - mapAlias.put(key, table.isCaseSensitive(IdentifierField.ALIAS) ? ("\""+table.getAlias()+"\"") : table.getAlias()); + mapAlias.put(key, table.isCaseSensitive(IdentifierField.ALIAS) ? ("\"" + table.getAlias() + "\"") : table.getAlias()); } } } @@ -338,7 +338,7 @@ public class PostgreSQLTranslator implements ADQLTranslator { } } - public String translate(ColumnReference ref) throws TranslationException { + public String translate(ColumnReference ref) throws TranslationException{ if (ref instanceof ADQLOrder) return translate((ADQLOrder)ref); else @@ -354,12 +354,12 @@ public class PostgreSQLTranslator implements ADQLTranslator { * * @throws TranslationException If there is an error during the translation. */ - protected String getDefaultColumnReference(ColumnReference ref) throws TranslationException { + protected String getDefaultColumnReference(ColumnReference ref) throws TranslationException{ if (ref.isIndex()){ - return ""+ref.getColumnIndex(); + return "" + ref.getColumnIndex(); }else{ if (ref.getDBLink() == null){ - return (ref.isCaseSensitive()?("\""+ref.getColumnName()+"\""):ref.getColumnName()); + return (ref.isCaseSensitive() ? ("\"" + ref.getColumnName() + "\"") : ref.getColumnName()); }else{ DBColumn dbCol = ref.getDBLink(); StringBuffer colName = new StringBuffer(); @@ -378,14 +378,14 @@ public class PostgreSQLTranslator implements ADQLTranslator { } } - public String translate(ADQLOrder order) throws TranslationException { - return getDefaultColumnReference(order)+(order.isDescSorting()?" DESC":" ASC"); + public String translate(ADQLOrder order) throws TranslationException{ + return getDefaultColumnReference(order) + (order.isDescSorting() ? " DESC" : " ASC"); } /* ************************** */ /* ****** TABLE & JOIN ****** */ /* ************************** */ - public String translate(FromContent content) throws TranslationException { + public String translate(FromContent content) throws TranslationException{ if (content instanceof ADQLTable) return translate((ADQLTable)content); else if (content instanceof ADQLJoin) @@ -394,7 +394,7 @@ public class PostgreSQLTranslator implements ADQLTranslator { return content.toADQL(); } - public String translate(ADQLTable table) throws TranslationException { + public String translate(ADQLTable table) throws TranslationException{ StringBuffer sql = new StringBuffer(); // CASE: SUB-QUERY: @@ -420,7 +420,7 @@ public class PostgreSQLTranslator implements ADQLTranslator { return sql.toString(); } - public String translate(ADQLJoin join) throws TranslationException { + public String translate(ADQLJoin join) throws TranslationException{ StringBuffer sql = new StringBuffer(translate(join.getLeftTable())); if (join.isNatural()) @@ -431,7 +431,7 @@ public class PostgreSQLTranslator implements ADQLTranslator { if (!join.isNatural()){ if (join.getJoinCondition() != null) sql.append(translate(join.getJoinCondition())); - else if (join.hasJoinedColumns()) { + else if (join.hasJoinedColumns()){ StringBuffer cols = new StringBuffer(); Iterator<ADQLColumn> it = join.getJoinedColumns(); while(it.hasNext()){ @@ -453,7 +453,7 @@ public class PostgreSQLTranslator implements ADQLTranslator { /* ********************* */ /* ****** OPERAND ****** */ /* ********************* */ - public String translate(ADQLOperand op) throws TranslationException { + public String translate(ADQLOperand op) throws TranslationException{ if (op instanceof ADQLColumn) return translate((ADQLColumn)op); else if (op instanceof Concatenation) @@ -474,7 +474,7 @@ public class PostgreSQLTranslator implements ADQLTranslator { return op.toADQL(); } - public String translate(ADQLColumn column) throws TranslationException { + public String translate(ADQLColumn column) throws TranslationException{ // Use its DB name if known: if (column.getDBLink() != null){ DBColumn dbCol = column.getDBLink(); @@ -500,34 +500,34 @@ public class PostgreSQLTranslator implements ADQLTranslator { return column.getFullColumnName(); } - public String translate(Concatenation concat) throws TranslationException { + public String translate(Concatenation concat) throws TranslationException{ return translate((ADQLList<ADQLOperand>)concat); } - public String translate(NegativeOperand negOp) throws TranslationException { - return "-"+translate(negOp.getOperand()); + public String translate(NegativeOperand negOp) throws TranslationException{ + return "-" + translate(negOp.getOperand()); } - public String translate(NumericConstant numConst) throws TranslationException { + public String translate(NumericConstant numConst) throws TranslationException{ return numConst.getValue(); } - public String translate(StringConstant strConst) throws TranslationException { - return "'"+strConst.getValue()+"'"; + public String translate(StringConstant strConst) throws TranslationException{ + return "'" + strConst.getValue() + "'"; } - public String translate(WrappedOperand op) throws TranslationException { - return "("+translate(op.getOperand())+")"; + public String translate(WrappedOperand op) throws TranslationException{ + return "(" + translate(op.getOperand()) + ")"; } - public String translate(Operation op) throws TranslationException { - return translate(op.getLeftOperand())+op.getOperation().toADQL()+translate(op.getRightOperand()); + public String translate(Operation op) throws TranslationException{ + return translate(op.getLeftOperand()) + op.getOperation().toADQL() + translate(op.getRightOperand()); } /* ************************ */ /* ****** CONSTRAINT ****** */ /* ************************ */ - public String translate(ADQLConstraint cons) throws TranslationException { + public String translate(ADQLConstraint cons) throws TranslationException{ if (cons instanceof Comparison) return translate((Comparison)cons); else if (cons instanceof Between) @@ -544,34 +544,34 @@ public class PostgreSQLTranslator implements ADQLTranslator { return cons.toADQL(); } - public String translate(Comparison comp) throws TranslationException { - return translate(comp.getLeftOperand())+" "+comp.getOperator().toADQL()+" "+translate(comp.getRightOperand()); + public String translate(Comparison comp) throws TranslationException{ + return translate(comp.getLeftOperand()) + " " + comp.getOperator().toADQL() + " " + translate(comp.getRightOperand()); } - public String translate(Between comp) throws TranslationException { - return translate(comp.getLeftOperand())+" BETWEEN "+translate(comp.getMinOperand())+" AND "+translate(comp.getMaxOperand()); + public String translate(Between comp) throws TranslationException{ + return translate(comp.getLeftOperand()) + " BETWEEN " + translate(comp.getMinOperand()) + " AND " + translate(comp.getMaxOperand()); } - public String translate(Exists exists) throws TranslationException { - return "EXISTS("+translate(exists.getSubQuery())+")"; + public String translate(Exists exists) throws TranslationException{ + return "EXISTS(" + translate(exists.getSubQuery()) + ")"; } - public String translate(In in) throws TranslationException { - return translate(in.getOperand())+" "+in.getName()+" ("+(in.hasSubQuery()?translate(in.getSubQuery()):translate(in.getValuesList()))+")"; + public String translate(In in) throws TranslationException{ + return translate(in.getOperand()) + " " + in.getName() + " (" + (in.hasSubQuery() ? translate(in.getSubQuery()) : translate(in.getValuesList())) + ")"; } - public String translate(IsNull isNull) throws TranslationException { - return translate(isNull.getColumn())+" IS "+(isNull.isNotNull()?"NOT ":"")+"NULL"; + public String translate(IsNull isNull) throws TranslationException{ + return translate(isNull.getColumn()) + " IS " + (isNull.isNotNull() ? "NOT " : "") + "NULL"; } - public String translate(NotConstraint notCons) throws TranslationException { - return "NOT "+translate(notCons.getConstraint()); + public String translate(NotConstraint notCons) throws TranslationException{ + return "NOT " + translate(notCons.getConstraint()); } /* *********************** */ /* ****** FUNCTIONS ****** */ /* *********************** */ - public String translate(ADQLFunction fct) throws TranslationException { + public String translate(ADQLFunction fct) throws TranslationException{ if (fct instanceof GeometryFunction) return translate((GeometryFunction)fct); else if (fct instanceof MathFunction) @@ -593,45 +593,45 @@ public class PostgreSQLTranslator implements ADQLTranslator { * * @throws TranslationException If there is an error during the translation. */ - protected String getDefaultADQLFunction(ADQLFunction fct) throws TranslationException { - String sql = fct.getName()+"("; + protected String getDefaultADQLFunction(ADQLFunction fct) throws TranslationException{ + String sql = fct.getName() + "("; - for(int i=0; i<fct.getNbParameters(); i++) - sql += ((i==0)?"":", ")+translate(fct.getParameter(i)); + for(int i = 0; i < fct.getNbParameters(); i++) + sql += ((i == 0) ? "" : ", ") + translate(fct.getParameter(i)); - return sql+")"; + return sql + ")"; } public String translate(SQLFunction fct) throws TranslationException{ if (fct.getType() == SQLFunctionType.COUNT_ALL) - return "COUNT("+(fct.isDistinct()?"DISTINCT ":"")+"*)"; + return "COUNT(" + (fct.isDistinct() ? "DISTINCT " : "") + "*)"; else - return fct.getName()+"("+(fct.isDistinct()?"DISTINCT ":"")+translate(fct.getParameter(0))+")"; + return fct.getName() + "(" + (fct.isDistinct() ? "DISTINCT " : "") + translate(fct.getParameter(0)) + ")"; } - public String translate(MathFunction fct) throws TranslationException { + public String translate(MathFunction fct) throws TranslationException{ switch(fct.getType()){ - case LOG: - return "ln("+((fct.getNbParameters()>=1)?translate(fct.getParameter(0)):"")+")"; - case LOG10: - return "log(10, "+((fct.getNbParameters()>=1)?translate(fct.getParameter(0)):"")+")"; - case RAND: - return "random()"; - case TRUNCATE: - return "trunc("+((fct.getNbParameters()>=2)?(translate(fct.getParameter(0))+", "+translate(fct.getParameter(1))):"")+")"; - default: - return getDefaultADQLFunction(fct); + case LOG: + return "ln(" + ((fct.getNbParameters() >= 1) ? translate(fct.getParameter(0)) : "") + ")"; + case LOG10: + return "log(10, " + ((fct.getNbParameters() >= 1) ? translate(fct.getParameter(0)) : "") + ")"; + case RAND: + return "random()"; + case TRUNCATE: + return "trunc(" + ((fct.getNbParameters() >= 2) ? (translate(fct.getParameter(0)) + ", " + translate(fct.getParameter(1))) : "") + ")"; + default: + return getDefaultADQLFunction(fct); } } - public String translate(UserDefinedFunction fct) throws TranslationException { + public String translate(UserDefinedFunction fct) throws TranslationException{ return getDefaultADQLFunction(fct); } /* *********************************** */ /* ****** GEOMETRICAL FUNCTIONS ****** */ /* *********************************** */ - public String translate(GeometryFunction fct) throws TranslationException { + public String translate(GeometryFunction fct) throws TranslationException{ if (fct instanceof AreaFunction) return translate((AreaFunction)fct); else if (fct instanceof BoxFunction) @@ -671,62 +671,62 @@ public class PostgreSQLTranslator implements ADQLTranslator { * * @throws TranslationException If there is an error during the translation. */ - protected String getDefaultGeometryFunction(GeometryFunction fct) throws TranslationException { + protected String getDefaultGeometryFunction(GeometryFunction fct) throws TranslationException{ if (inSelect) - return "'"+fct.toADQL().replaceAll("'", "''")+"'"; + return "'" + fct.toADQL().replaceAll("'", "''") + "'"; else return getDefaultADQLFunction(fct); } - public String translate(GeometryValue<? extends GeometryFunction> geomValue) throws TranslationException { + public String translate(GeometryValue<? extends GeometryFunction> geomValue) throws TranslationException{ return translate(geomValue.getValue()); } - public String translate(ExtractCoord extractCoord) throws TranslationException { + public String translate(ExtractCoord extractCoord) throws TranslationException{ return getDefaultGeometryFunction(extractCoord); } - public String translate(ExtractCoordSys extractCoordSys) throws TranslationException { + public String translate(ExtractCoordSys extractCoordSys) throws TranslationException{ return getDefaultGeometryFunction(extractCoordSys); } - public String translate(AreaFunction areaFunction) throws TranslationException { + public String translate(AreaFunction areaFunction) throws TranslationException{ return getDefaultGeometryFunction(areaFunction); } - public String translate(CentroidFunction centroidFunction) throws TranslationException { + public String translate(CentroidFunction centroidFunction) throws TranslationException{ return getDefaultGeometryFunction(centroidFunction); } - public String translate(DistanceFunction fct) throws TranslationException { + public String translate(DistanceFunction fct) throws TranslationException{ return getDefaultGeometryFunction(fct); } - public String translate(ContainsFunction fct) throws TranslationException { + public String translate(ContainsFunction fct) throws TranslationException{ return getDefaultGeometryFunction(fct); } - public String translate(IntersectsFunction fct) throws TranslationException { + public String translate(IntersectsFunction fct) throws TranslationException{ return getDefaultGeometryFunction(fct); } - public String translate(BoxFunction box) throws TranslationException { + public String translate(BoxFunction box) throws TranslationException{ return getDefaultGeometryFunction(box); } - public String translate(CircleFunction circle) throws TranslationException { + public String translate(CircleFunction circle) throws TranslationException{ return getDefaultGeometryFunction(circle); } - public String translate(PointFunction point) throws TranslationException { + public String translate(PointFunction point) throws TranslationException{ return getDefaultGeometryFunction(point); } - public String translate(PolygonFunction polygon) throws TranslationException { + public String translate(PolygonFunction polygon) throws TranslationException{ return getDefaultGeometryFunction(polygon); } - public String translate(RegionFunction region) throws TranslationException { + public String translate(RegionFunction region) throws TranslationException{ return getDefaultGeometryFunction(region); } diff --git a/src/adql/translator/TranslationException.java b/src/adql/translator/TranslationException.java index 329d91ae5ac74cd3c6a4c931ee147a0560517075..20ef933a464a88c1097c10c60d9b5a1c3f33ad9b 100644 --- a/src/adql/translator/TranslationException.java +++ b/src/adql/translator/TranslationException.java @@ -29,17 +29,19 @@ public class TranslationException extends Exception { private static final long serialVersionUID = 1L; - public TranslationException() { ; } + public TranslationException(){ + ; + } - public TranslationException(String msg) { + public TranslationException(String msg){ super(msg); } - public TranslationException(Throwable cause) { + public TranslationException(Throwable cause){ super(cause); } - public TranslationException(String msg, Throwable cause) { + public TranslationException(String msg, Throwable cause){ super(msg, cause); } diff --git a/src/cds/util/AsciiTable.java b/src/cds/util/AsciiTable.java index d25f55b24a8c5e839f938e3602bdd059f534936b..9f3c495704a093d1a2325de70f10c5a44669ead7 100644 --- a/src/cds/util/AsciiTable.java +++ b/src/cds/util/AsciiTable.java @@ -50,7 +50,7 @@ public class AsciiTable { * Constructor * @param separ character defining the column separator in the input lines */ - public AsciiTable(char separ) { + public AsciiTable(char separ){ csep = separ; sep = String.valueOf(csep); } @@ -59,7 +59,7 @@ public class AsciiTable { * Add a header line. Several lines of header can be defined. * @param headerline header string */ - public void addHeaderLine(String headerline) { + public void addHeaderLine(String headerline){ header = true; addLine(headerline); } @@ -69,7 +69,7 @@ public class AsciiTable { * @param postfix String to append after the header lines (i.e. "\n") * @see #endHeaderLine() */ - public void endHeaderLine(String postfix) { + public void endHeaderLine(String postfix){ lines.add(null); headerPostfix = postfix; } @@ -78,7 +78,7 @@ public class AsciiTable { * Specifies that the header lines are finished. This call is mandatory * @see #endHeaderLine(String) */ - public void endHeaderLine() { + public void endHeaderLine(){ lines.add(null); headerPostfix = null; } @@ -89,20 +89,23 @@ public class AsciiTable { * The line should not end up with a newline char. If it is the case, alignement errors can be experienced * depending on the alignement type of the last column. */ - public void addLine(String line) { + public void addLine(String line){ // compute the number of columns, if we add the first line - if (empty) { - int p=0; + if (empty){ + int p = 0; int nbcol = 1; // at least one column (also: there is one separator less than columns) boolean done = false; - while (! done) { + while(!done){ p = line.indexOf(sep, p); - if (p >= 0) nbcol++; else done = true; + if (p >= 0) + nbcol++; + else + done = true; p++; } // initialize the result sizes = new int[nbcol]; - for (int i=0; i<sizes.length; i++) { + for(int i = 0; i < sizes.length; i++){ sizes[i] = 0; } empty = false; @@ -110,14 +113,15 @@ public class AsciiTable { // get the max size for each column int p0, p1, col, colsize; - p0=0; + p0 = 0; col = 0; - while (p0 < line.length()) { + while(p0 < line.length()){ p1 = line.indexOf(sep, p0); - if (p1 < 0) p1 = line.length(); - colsize = p1-p0; - sizes[col] = Math.max(sizes[col],colsize); - p0 = p1+1; + if (p1 < 0) + p1 = line.length(); + colsize = p1 - p0; + sizes[col] = Math.max(sizes[col], colsize); + p0 = p1 + 1; col++; } @@ -128,7 +132,7 @@ public class AsciiTable { * Get all the lines without alignement, as they were entered * @return the array of the lines in the table */ - public String[] displayRaw() { + public String[] displayRaw(){ return lines.toArray(new String[0]); } @@ -137,11 +141,12 @@ public class AsciiTable { * @param newsep separator to use, replacing the original one * @return the array of the lines in the table */ - public String[] displayRaw(char newsep) { - if (newsep == csep) return displayRaw(); - else { + public String[] displayRaw(char newsep){ + if (newsep == csep) + return displayRaw(); + else{ String[] resu = new String[lines.size()]; - for (int i=0; i<resu.length; i++) { + for(int i = 0; i < resu.length; i++){ resu[i] = (lines.get(i)).replace(csep, newsep); } return resu; @@ -157,7 +162,7 @@ public class AsciiTable { * if the array contains ONE item, it will be used for every column. * @return an array of the table lines, aligned and justified */ - public String[] displayAligned(int[] pos) { + public String[] displayAligned(int[] pos){ return align(pos, '\0'); } @@ -170,12 +175,12 @@ public class AsciiTable { * @param newsep separator to use, replacing the original one * @return an array of the table lines, aligned and justified */ - public String[] displayAligned(int[] pos, char newsep) { - if (newsep == csep) newsep = '\0'; + public String[] displayAligned(int[] pos, char newsep){ + if (newsep == csep) + newsep = '\0'; return align(pos, newsep); } - /** * Get the array of lines in which all the columns are aligned * @param pos array of flags, indicating how each column should be justified. @@ -185,7 +190,7 @@ public class AsciiTable { * @param newsep separator to use, replacing the original one (no replacement if '\0') * @return an array of the table lines, aligned and justified */ - private String[] align(int[] pos, char newsep) { + private String[] align(int[] pos, char newsep){ int nblines = lines.size(); String[] result = new String[nblines]; StringBuffer buf = new StringBuffer(); @@ -193,49 +198,55 @@ public class AsciiTable { boolean inHeader = header; // A header can contain several lines. The end is detected by a line // beginning by the separator char int uniqueJustif = pos.length == 1 ? pos[0] : -1; - for (int i=0; i<nblines; i++) { + for(int i = 0; i < nblines; i++){ buf.delete(0, buf.length()); String line = lines.get(i); - p0=0; + p0 = 0; col = 0; - if (inHeader && line == null) { + if (inHeader && line == null){ // end of the header: create the separator line - for (int k=0; k<sizes.length; k++) { - if (k > 0) buf.append(csep); + for(int k = 0; k < sizes.length; k++){ + if (k > 0) + buf.append(csep); addHsep(buf, sizes[k]); } - if (headerPostfix != null) buf.append(headerPostfix); + if (headerPostfix != null) + buf.append(headerPostfix); inHeader = false; - } else { - for (col=0; col<sizes.length; col++) { - if (col > 0) buf.append(sep); + }else{ + for(col = 0; col < sizes.length; col++){ + if (col > 0) + buf.append(sep); p1 = line.indexOf(sep, p0); - if (p1 < 0) p1 = line.length(); - fldsize = p1-p0; - if (fldsize < 0) break; + if (p1 < 0) + p1 = line.length(); + fldsize = p1 - p0; + if (fldsize < 0) + break; colsize = sizes[col]; - inserted = colsize-fldsize; - if (inserted < 0) inserted = 0; + inserted = colsize - fldsize; + if (inserted < 0) + inserted = 0; int justif = inHeader ? CENTER : (uniqueJustif >= 0 ? uniqueJustif : pos[col]); - switch (justif) { - case LEFT: - default: - buf.append(line.substring(p0, p1)); - addspaces(buf, inserted); - break; - case CENTER: - n1 = (inserted)/2; - addspaces(buf, n1); - buf.append(line.substring(p0, p1)); - addspaces(buf, inserted-n1); - break; - case RIGHT: - addspaces(buf, inserted); - buf.append(line.substring(p0, p1)); - break; + switch(justif){ + case LEFT: + default: + buf.append(line.substring(p0, p1)); + addspaces(buf, inserted); + break; + case CENTER: + n1 = (inserted) / 2; + addspaces(buf, n1); + buf.append(line.substring(p0, p1)); + addspaces(buf, inserted - n1); + break; + case RIGHT: + addspaces(buf, inserted); + buf.append(line.substring(p0, p1)); + break; } - p0 = p1+1; + p0 = p1 + 1; } } result[i] = newsep != '\0' ? buf.toString().replace(csep, newsep) : buf.toString(); @@ -248,10 +259,10 @@ public class AsciiTable { * @param buf StringBuffer to modify * @param nb number of spaces to add */ - private void addspaces(StringBuffer buf, int nb) { - while (nb > SPACES.length()) - SPACES = SPACES+SPACES; - buf.append(SPACES.substring(0,nb)); + private void addspaces(StringBuffer buf, int nb){ + while(nb > SPACES.length()) + SPACES = SPACES + SPACES; + buf.append(SPACES.substring(0, nb)); } /** @@ -259,10 +270,10 @@ public class AsciiTable { * @param buf StringBuffer to modify * @param nb number of chars to add */ - private void addHsep(StringBuffer buf, int nb) { - while (nb > HSEP.length()) - HSEP = HSEP+HSEP; - buf.append(HSEP.substring(0,nb)); + private void addHsep(StringBuffer buf, int nb){ + while(nb > HSEP.length()) + HSEP = HSEP + HSEP; + buf.append(HSEP.substring(0, nb)); } /** @@ -270,12 +281,13 @@ public class AsciiTable { * @return the table as a unique string */ @Override - public String toString() { + public String toString(){ StringBuffer buf = new StringBuffer(); - String[] ids = displayAligned(new int[] {AsciiTable.LEFT}); + String[] ids = displayAligned(new int[]{AsciiTable.LEFT}); - for (int i=0; i<ids.length; i++) { - if (i > 0) buf.append("\n"); + for(int i = 0; i < ids.length; i++){ + if (i > 0) + buf.append("\n"); buf.append(ids[i]); } diff --git a/src/cds/utils/TextualSearchList.java b/src/cds/utils/TextualSearchList.java index 68ac459bb24e6012ff788eacb1dd10429ff89dc2..8a354e5c9ab1fd8445f3ad1ab4b65ded8dcf5944 100644 --- a/src/cds/utils/TextualSearchList.java +++ b/src/cds/utils/TextualSearchList.java @@ -40,18 +40,17 @@ import java.util.HashMap; * @author Grégory Mantelet (CDS) * @version 09/2011 */ -public class TextualSearchList<E> extends ArrayList<E> { +public class TextualSearchList< E > extends ArrayList<E> { private static final long serialVersionUID = 1L; /** Object to use to extract an unique textual string. */ public final KeyExtractor<E> keyExtractor; /** Map which associates objects of type E with its textual string (case-sensitive). */ - protected final HashMap<String, ArrayList<E>> csMap; + protected final HashMap<String,ArrayList<E>> csMap; /** Map which associates objects of type E with their lower-case textual string. */ - protected final HashMap<String, ArrayList<E>> ncsMap; - + protected final HashMap<String,ArrayList<E>> ncsMap; /* ************ */ /* CONSTRUCTORS */ @@ -65,7 +64,7 @@ public class TextualSearchList<E> extends ArrayList<E> { * * @see #TextualSearchList(KeyExtractor) */ - public TextualSearchList() { + public TextualSearchList(){ this(new DefaultKeyExtractor<E>()); } @@ -76,11 +75,11 @@ public class TextualSearchList<E> extends ArrayList<E> { * * @see ArrayList#ArrayList() */ - public TextualSearchList(final KeyExtractor<E> keyExtractor) { + public TextualSearchList(final KeyExtractor<E> keyExtractor){ super(); this.keyExtractor = keyExtractor; - csMap = new HashMap<String, ArrayList<E>>(); - ncsMap = new HashMap<String, ArrayList<E>>(); + csMap = new HashMap<String,ArrayList<E>>(); + ncsMap = new HashMap<String,ArrayList<E>>(); } /** @@ -94,7 +93,7 @@ public class TextualSearchList<E> extends ArrayList<E> { * * @see #TextualSearchList(int, KeyExtractor) */ - public TextualSearchList(int initialCapacity) { + public TextualSearchList(int initialCapacity){ this(initialCapacity, new DefaultKeyExtractor<E>()); } @@ -106,11 +105,11 @@ public class TextualSearchList<E> extends ArrayList<E> { * * @see ArrayList#ArrayList(int) */ - public TextualSearchList(final int initialCapacity, final KeyExtractor<E> keyExtractor) { + public TextualSearchList(final int initialCapacity, final KeyExtractor<E> keyExtractor){ super(initialCapacity); this.keyExtractor = keyExtractor; - csMap = new HashMap<String, ArrayList<E>>(initialCapacity); - ncsMap = new HashMap<String, ArrayList<E>>(initialCapacity); + csMap = new HashMap<String,ArrayList<E>>(initialCapacity); + ncsMap = new HashMap<String,ArrayList<E>>(initialCapacity); } /** @@ -122,7 +121,7 @@ public class TextualSearchList<E> extends ArrayList<E> { * * @param c Collection to copy into this list. */ - public TextualSearchList(Collection<? extends E> c) { + public TextualSearchList(Collection<? extends E> c){ this(c, new DefaultKeyExtractor<E>()); } @@ -134,10 +133,10 @@ public class TextualSearchList<E> extends ArrayList<E> { * * @see #addAll(Collection) */ - public TextualSearchList(Collection<? extends E> c, final KeyExtractor<E> keyExtractor) { + public TextualSearchList(Collection<? extends E> c, final KeyExtractor<E> keyExtractor){ this.keyExtractor = keyExtractor; - csMap = new HashMap<String, ArrayList<E>>(c.size()); - ncsMap = new HashMap<String, ArrayList<E>>(c.size()); + csMap = new HashMap<String,ArrayList<E>>(c.size()); + ncsMap = new HashMap<String,ArrayList<E>>(c.size()); addAll(c); } @@ -181,7 +180,7 @@ public class TextualSearchList<E> extends ArrayList<E> { * @throws NullPointerException If the given object or its extracted key is <code>null</code>. * @throws IllegalArgumentException If the extracted key is already used by another object in this list. */ - private final String getKey(final E value) throws NullPointerException, IllegalArgumentException { + private final String getKey(final E value) throws NullPointerException, IllegalArgumentException{ String key = keyExtractor.getKey(value); if (key == null) throw new NullPointerException("Null keys are not allowed in a TextualSearchList !"); @@ -210,7 +209,7 @@ public class TextualSearchList<E> extends ArrayList<E> { * * @param <E> The type of objects managed in the given map. */ - private static final <E> void putIntoMap(final HashMap<String, ArrayList<E>> map, final String key, final E value){ + private static final < E > void putIntoMap(final HashMap<String,ArrayList<E>> map, final String key, final E value){ ArrayList<E> lst = map.get(key); if (lst == null){ lst = new ArrayList<E>(); @@ -231,7 +230,7 @@ public class TextualSearchList<E> extends ArrayList<E> { * @see java.util.ArrayList#add(java.lang.Object) */ @Override - public boolean add(E obj) throws NullPointerException, IllegalArgumentException { + public boolean add(E obj) throws NullPointerException, IllegalArgumentException{ if (obj == null) throw new NullPointerException("Null objects are not allowed in a TextualSearchList !"); @@ -259,7 +258,7 @@ public class TextualSearchList<E> extends ArrayList<E> { * @see java.util.ArrayList#add(int, java.lang.Object) */ @Override - public void add(int index, E obj) throws NullPointerException, IllegalArgumentException, IndexOutOfBoundsException { + public void add(int index, E obj) throws NullPointerException, IllegalArgumentException, IndexOutOfBoundsException{ if (obj == null) throw new NullPointerException("Null objects are not allowed in a TextualSearchList !"); @@ -286,7 +285,7 @@ public class TextualSearchList<E> extends ArrayList<E> { * @see #add(Object) */ @Override - public boolean addAll(Collection<? extends E> c) throws NullPointerException, IllegalArgumentException { + public boolean addAll(Collection<? extends E> c) throws NullPointerException, IllegalArgumentException{ if (c == null) return false; @@ -313,7 +312,7 @@ public class TextualSearchList<E> extends ArrayList<E> { * @see #add(int, Object) */ @Override - public boolean addAll(int index, Collection<? extends E> c) throws NullPointerException, IllegalArgumentException, IndexOutOfBoundsException { + public boolean addAll(int index, Collection<? extends E> c) throws NullPointerException, IllegalArgumentException, IndexOutOfBoundsException{ if (c == null) return false; @@ -342,7 +341,7 @@ public class TextualSearchList<E> extends ArrayList<E> { * @see java.util.ArrayList#set(int, java.lang.Object) */ @Override - public E set(int index, E obj) throws NullPointerException, IllegalArgumentException { + public E set(int index, E obj) throws NullPointerException, IllegalArgumentException{ if (obj == null) throw new NullPointerException("Null objects are not allowed in a TextualSearchList !"); @@ -364,7 +363,7 @@ public class TextualSearchList<E> extends ArrayList<E> { } @Override - public void clear() { + public void clear(){ super.clear(); csMap.clear(); ncsMap.clear(); @@ -392,7 +391,7 @@ public class TextualSearchList<E> extends ArrayList<E> { * * @param <E> The type of objects managed in the given map. */ - private static final <E> void removeFromMap(final HashMap<String, ArrayList<E>> map, final String key, final E value){ + private static final < E > void removeFromMap(final HashMap<String,ArrayList<E>> map, final String key, final E value){ ArrayList<E> lst = map.get(key); if (lst != null){ lst.remove(value); @@ -402,7 +401,7 @@ public class TextualSearchList<E> extends ArrayList<E> { } @Override - public E remove(int index) { + public E remove(int index){ E removed = super.remove(index); if (removed != null){ String key = keyExtractor.getKey(removed); @@ -413,7 +412,7 @@ public class TextualSearchList<E> extends ArrayList<E> { @SuppressWarnings("unchecked") @Override - public boolean remove(Object obj) { + public boolean remove(Object obj){ boolean removed = super.remove(obj); if (removed){ String key = keyExtractor.getKey((E)obj); @@ -423,18 +422,14 @@ public class TextualSearchList<E> extends ArrayList<E> { } @Override - protected void removeRange(int fromIndex, int toIndex) throws IndexOutOfBoundsException { + protected void removeRange(int fromIndex, int toIndex) throws IndexOutOfBoundsException{ if (fromIndex < 0 || fromIndex >= size() || toIndex < 0 || toIndex >= size() || fromIndex > toIndex) - throw new IndexOutOfBoundsException("Incorrect range indexes: from "+fromIndex+" to "+toIndex+" !"); + throw new IndexOutOfBoundsException("Incorrect range indexes: from " + fromIndex + " to " + toIndex + " !"); - for(int i=fromIndex; i<toIndex; i++) + for(int i = fromIndex; i < toIndex; i++) remove(i); } - - - - /* ************************************************ */ /* KEY_EXTRACTOR INTERFACE & DEFAULT IMPLEMENTATION */ /* ************************************************ */ @@ -445,7 +440,7 @@ public class TextualSearchList<E> extends ArrayList<E> { * @param <E> Type of object from which a textual key must be extracted. * @see TextualSearchList */ - public static interface KeyExtractor<E> { + public static interface KeyExtractor< E > { /** * Extracts an UNIQUE textual key (case-sensitive) from the given object. * @param obj Object from which a textual key must be extracted. @@ -461,7 +456,7 @@ public class TextualSearchList<E> extends ArrayList<E> { * @author Grégory Mantelet (CDS) * @param <E> Type of object from which a textual key must be extracted. */ - protected static class DefaultKeyExtractor<E> implements KeyExtractor<E> { + protected static class DefaultKeyExtractor< E > implements KeyExtractor<E> { public String getKey(final E obj){ return obj.toString(); } diff --git a/src/org/json/CDL.java b/src/org/json/CDL.java index fd5d476cabb05c7ca2c1a3a83010f33df7534430..5589a392e5c568b30255b6ff2250dba63219cb3a 100644 --- a/src/org/json/CDL.java +++ b/src/org/json/CDL.java @@ -45,235 +45,226 @@ SOFTWARE. */ public class CDL { - /** - * Get the next value. The value can be wrapped in quotes. The value can - * be empty. - * @param x A JSONTokener of the source text. - * @return The value string, or null if empty. - * @throws JSONException if the quoted string is badly formed. - */ - private static String getValue(JSONTokener x) throws JSONException { - char c; - char q; - StringBuffer sb; - do { - c = x.next(); - } while (c == ' ' || c == '\t'); - switch (c) { - case 0: - return null; - case '"': - case '\'': - q = c; - sb = new StringBuffer(); - for (;;) { - c = x.next(); - if (c == q) { - break; - } - if (c == 0 || c == '\n' || c == '\r') { - throw x.syntaxError("Missing close quote '" + q + "'."); - } - sb.append(c); - } - return sb.toString(); - case ',': - x.back(); - return ""; - default: - x.back(); - return x.nextTo(','); - } - } + /** + * Get the next value. The value can be wrapped in quotes. The value can + * be empty. + * @param x A JSONTokener of the source text. + * @return The value string, or null if empty. + * @throws JSONException if the quoted string is badly formed. + */ + private static String getValue(JSONTokener x) throws JSONException{ + char c; + char q; + StringBuffer sb; + do{ + c = x.next(); + }while(c == ' ' || c == '\t'); + switch(c){ + case 0: + return null; + case '"': + case '\'': + q = c; + sb = new StringBuffer(); + for(;;){ + c = x.next(); + if (c == q){ + break; + } + if (c == 0 || c == '\n' || c == '\r'){ + throw x.syntaxError("Missing close quote '" + q + "'."); + } + sb.append(c); + } + return sb.toString(); + case ',': + x.back(); + return ""; + default: + x.back(); + return x.nextTo(','); + } + } - /** - * Produce a JSONArray of strings from a row of comma delimited values. - * @param x A JSONTokener of the source text. - * @return A JSONArray of strings. - * @throws JSONException - */ - public static JSONArray rowToJSONArray(JSONTokener x) throws JSONException { - JSONArray ja = new JSONArray(); - for (;;) { - String value = getValue(x); - char c = x.next(); - if (value == null || - (ja.length() == 0 && value.length() == 0 && c != ',')) { - return null; - } - ja.put(value); - for (;;) { - if (c == ',') { - break; - } - if (c != ' ') { - if (c == '\n' || c == '\r' || c == 0) { - return ja; - } - throw x.syntaxError("Bad character '" + c + "' (" + - (int)c + ")."); - } - c = x.next(); - } - } - } + /** + * Produce a JSONArray of strings from a row of comma delimited values. + * @param x A JSONTokener of the source text. + * @return A JSONArray of strings. + * @throws JSONException + */ + public static JSONArray rowToJSONArray(JSONTokener x) throws JSONException{ + JSONArray ja = new JSONArray(); + for(;;){ + String value = getValue(x); + char c = x.next(); + if (value == null || (ja.length() == 0 && value.length() == 0 && c != ',')){ + return null; + } + ja.put(value); + for(;;){ + if (c == ','){ + break; + } + if (c != ' '){ + if (c == '\n' || c == '\r' || c == 0){ + return ja; + } + throw x.syntaxError("Bad character '" + c + "' (" + (int)c + ")."); + } + c = x.next(); + } + } + } - /** - * Produce a JSONObject from a row of comma delimited text, using a - * parallel JSONArray of strings to provides the names of the elements. - * @param names A JSONArray of names. This is commonly obtained from the - * first row of a comma delimited text file using the rowToJSONArray - * method. - * @param x A JSONTokener of the source text. - * @return A JSONObject combining the names and values. - * @throws JSONException - */ - public static JSONObject rowToJSONObject(JSONArray names, JSONTokener x) - throws JSONException { - JSONArray ja = rowToJSONArray(x); - return ja != null ? ja.toJSONObject(names) : null; - } + /** + * Produce a JSONObject from a row of comma delimited text, using a + * parallel JSONArray of strings to provides the names of the elements. + * @param names A JSONArray of names. This is commonly obtained from the + * first row of a comma delimited text file using the rowToJSONArray + * method. + * @param x A JSONTokener of the source text. + * @return A JSONObject combining the names and values. + * @throws JSONException + */ + public static JSONObject rowToJSONObject(JSONArray names, JSONTokener x) throws JSONException{ + JSONArray ja = rowToJSONArray(x); + return ja != null ? ja.toJSONObject(names) : null; + } - /** - * Produce a comma delimited text row from a JSONArray. Values containing - * the comma character will be quoted. Troublesome characters may be - * removed. - * @param ja A JSONArray of strings. - * @return A string ending in NEWLINE. - */ - public static String rowToString(JSONArray ja) { - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < ja.length(); i += 1) { - if (i > 0) { - sb.append(','); - } - Object object = ja.opt(i); - if (object != null) { - String string = object.toString(); - if (string.length() > 0 && (string.indexOf(',') >= 0 || - string.indexOf('\n') >= 0 || string.indexOf('\r') >= 0 || - string.indexOf(0) >= 0 || string.charAt(0) == '"')) { - sb.append('"'); - int length = string.length(); - for (int j = 0; j < length; j += 1) { - char c = string.charAt(j); - if (c >= ' ' && c != '"') { - sb.append(c); - } - } - sb.append('"'); - } else { - sb.append(string); - } - } - } - sb.append('\n'); - return sb.toString(); - } + /** + * Produce a comma delimited text row from a JSONArray. Values containing + * the comma character will be quoted. Troublesome characters may be + * removed. + * @param ja A JSONArray of strings. + * @return A string ending in NEWLINE. + */ + public static String rowToString(JSONArray ja){ + StringBuffer sb = new StringBuffer(); + for(int i = 0; i < ja.length(); i += 1){ + if (i > 0){ + sb.append(','); + } + Object object = ja.opt(i); + if (object != null){ + String string = object.toString(); + if (string.length() > 0 && (string.indexOf(',') >= 0 || string.indexOf('\n') >= 0 || string.indexOf('\r') >= 0 || string.indexOf(0) >= 0 || string.charAt(0) == '"')){ + sb.append('"'); + int length = string.length(); + for(int j = 0; j < length; j += 1){ + char c = string.charAt(j); + if (c >= ' ' && c != '"'){ + sb.append(c); + } + } + sb.append('"'); + }else{ + sb.append(string); + } + } + } + sb.append('\n'); + return sb.toString(); + } - /** - * Produce a JSONArray of JSONObjects from a comma delimited text string, - * using the first row as a source of names. - * @param string The comma delimited text. - * @return A JSONArray of JSONObjects. - * @throws JSONException - */ - public static JSONArray toJSONArray(String string) throws JSONException { - return toJSONArray(new JSONTokener(string)); - } + /** + * Produce a JSONArray of JSONObjects from a comma delimited text string, + * using the first row as a source of names. + * @param string The comma delimited text. + * @return A JSONArray of JSONObjects. + * @throws JSONException + */ + public static JSONArray toJSONArray(String string) throws JSONException{ + return toJSONArray(new JSONTokener(string)); + } - /** - * Produce a JSONArray of JSONObjects from a comma delimited text string, - * using the first row as a source of names. - * @param x The JSONTokener containing the comma delimited text. - * @return A JSONArray of JSONObjects. - * @throws JSONException - */ - public static JSONArray toJSONArray(JSONTokener x) throws JSONException { - return toJSONArray(rowToJSONArray(x), x); - } + /** + * Produce a JSONArray of JSONObjects from a comma delimited text string, + * using the first row as a source of names. + * @param x The JSONTokener containing the comma delimited text. + * @return A JSONArray of JSONObjects. + * @throws JSONException + */ + public static JSONArray toJSONArray(JSONTokener x) throws JSONException{ + return toJSONArray(rowToJSONArray(x), x); + } - /** - * Produce a JSONArray of JSONObjects from a comma delimited text string - * using a supplied JSONArray as the source of element names. - * @param names A JSONArray of strings. - * @param string The comma delimited text. - * @return A JSONArray of JSONObjects. - * @throws JSONException - */ - public static JSONArray toJSONArray(JSONArray names, String string) - throws JSONException { - return toJSONArray(names, new JSONTokener(string)); - } + /** + * Produce a JSONArray of JSONObjects from a comma delimited text string + * using a supplied JSONArray as the source of element names. + * @param names A JSONArray of strings. + * @param string The comma delimited text. + * @return A JSONArray of JSONObjects. + * @throws JSONException + */ + public static JSONArray toJSONArray(JSONArray names, String string) throws JSONException{ + return toJSONArray(names, new JSONTokener(string)); + } - /** - * Produce a JSONArray of JSONObjects from a comma delimited text string - * using a supplied JSONArray as the source of element names. - * @param names A JSONArray of strings. - * @param x A JSONTokener of the source text. - * @return A JSONArray of JSONObjects. - * @throws JSONException - */ - public static JSONArray toJSONArray(JSONArray names, JSONTokener x) - throws JSONException { - if (names == null || names.length() == 0) { - return null; - } - JSONArray ja = new JSONArray(); - for (;;) { - JSONObject jo = rowToJSONObject(names, x); - if (jo == null) { - break; - } - ja.put(jo); - } - if (ja.length() == 0) { - return null; - } - return ja; - } + /** + * Produce a JSONArray of JSONObjects from a comma delimited text string + * using a supplied JSONArray as the source of element names. + * @param names A JSONArray of strings. + * @param x A JSONTokener of the source text. + * @return A JSONArray of JSONObjects. + * @throws JSONException + */ + public static JSONArray toJSONArray(JSONArray names, JSONTokener x) throws JSONException{ + if (names == null || names.length() == 0){ + return null; + } + JSONArray ja = new JSONArray(); + for(;;){ + JSONObject jo = rowToJSONObject(names, x); + if (jo == null){ + break; + } + ja.put(jo); + } + if (ja.length() == 0){ + return null; + } + return ja; + } + /** + * Produce a comma delimited text from a JSONArray of JSONObjects. The + * first row will be a list of names obtained by inspecting the first + * JSONObject. + * @param ja A JSONArray of JSONObjects. + * @return A comma delimited text. + * @throws JSONException + */ + public static String toString(JSONArray ja) throws JSONException{ + JSONObject jo = ja.optJSONObject(0); + if (jo != null){ + JSONArray names = jo.names(); + if (names != null){ + return rowToString(names) + toString(names, ja); + } + } + return null; + } - /** - * Produce a comma delimited text from a JSONArray of JSONObjects. The - * first row will be a list of names obtained by inspecting the first - * JSONObject. - * @param ja A JSONArray of JSONObjects. - * @return A comma delimited text. - * @throws JSONException - */ - public static String toString(JSONArray ja) throws JSONException { - JSONObject jo = ja.optJSONObject(0); - if (jo != null) { - JSONArray names = jo.names(); - if (names != null) { - return rowToString(names) + toString(names, ja); - } - } - return null; - } - - /** - * Produce a comma delimited text from a JSONArray of JSONObjects using - * a provided list of names. The list of names is not included in the - * output. - * @param names A JSONArray of strings. - * @param ja A JSONArray of JSONObjects. - * @return A comma delimited text. - * @throws JSONException - */ - public static String toString(JSONArray names, JSONArray ja) - throws JSONException { - if (names == null || names.length() == 0) { - return null; - } - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < ja.length(); i += 1) { - JSONObject jo = ja.optJSONObject(i); - if (jo != null) { - sb.append(rowToString(jo.toJSONArray(names))); - } - } - return sb.toString(); - } + /** + * Produce a comma delimited text from a JSONArray of JSONObjects using + * a provided list of names. The list of names is not included in the + * output. + * @param names A JSONArray of strings. + * @param ja A JSONArray of JSONObjects. + * @return A comma delimited text. + * @throws JSONException + */ + public static String toString(JSONArray names, JSONArray ja) throws JSONException{ + if (names == null || names.length() == 0){ + return null; + } + StringBuffer sb = new StringBuffer(); + for(int i = 0; i < ja.length(); i += 1){ + JSONObject jo = ja.optJSONObject(i); + if (jo != null){ + sb.append(rowToString(jo.toJSONArray(names))); + } + } + return sb.toString(); + } } diff --git a/src/org/json/Cookie.java b/src/org/json/Cookie.java index 9cf5ce2c55b2cfd123c4821ba6054c5a9780bbbf..e10e5417b08f9a6afb84da784b60be0bf99bafc9 100644 --- a/src/org/json/Cookie.java +++ b/src/org/json/Cookie.java @@ -32,138 +32,136 @@ SOFTWARE. */ public class Cookie { - /** - * Produce a copy of a string in which the characters '+', '%', '=', ';' - * and control characters are replaced with "%hh". This is a gentle form - * of URL encoding, attempting to cause as little distortion to the - * string as possible. The characters '=' and ';' are meta characters in - * cookies. By convention, they are escaped using the URL-encoding. This is - * only a convention, not a standard. Often, cookies are expected to have - * encoded values. We encode '=' and ';' because we must. We encode '%' and - * '+' because they are meta characters in URL encoding. - * @param string The source string. - * @return The escaped result. - */ - public static String escape(String string) { - char c; - String s = string.trim(); - StringBuffer sb = new StringBuffer(); - int length = s.length(); - for (int i = 0; i < length; i += 1) { - c = s.charAt(i); - if (c < ' ' || c == '+' || c == '%' || c == '=' || c == ';') { - sb.append('%'); - sb.append(Character.forDigit((char)((c >>> 4) & 0x0f), 16)); - sb.append(Character.forDigit((char)(c & 0x0f), 16)); - } else { - sb.append(c); - } - } - return sb.toString(); - } + /** + * Produce a copy of a string in which the characters '+', '%', '=', ';' + * and control characters are replaced with "%hh". This is a gentle form + * of URL encoding, attempting to cause as little distortion to the + * string as possible. The characters '=' and ';' are meta characters in + * cookies. By convention, they are escaped using the URL-encoding. This is + * only a convention, not a standard. Often, cookies are expected to have + * encoded values. We encode '=' and ';' because we must. We encode '%' and + * '+' because they are meta characters in URL encoding. + * @param string The source string. + * @return The escaped result. + */ + public static String escape(String string){ + char c; + String s = string.trim(); + StringBuffer sb = new StringBuffer(); + int length = s.length(); + for(int i = 0; i < length; i += 1){ + c = s.charAt(i); + if (c < ' ' || c == '+' || c == '%' || c == '=' || c == ';'){ + sb.append('%'); + sb.append(Character.forDigit((char)((c >>> 4) & 0x0f), 16)); + sb.append(Character.forDigit((char)(c & 0x0f), 16)); + }else{ + sb.append(c); + } + } + return sb.toString(); + } + /** + * Convert a cookie specification string into a JSONObject. The string + * will contain a name value pair separated by '='. The name and the value + * will be unescaped, possibly converting '+' and '%' sequences. The + * cookie properties may follow, separated by ';', also represented as + * name=value (except the secure property, which does not have a value). + * The name will be stored under the key "name", and the value will be + * stored under the key "value". This method does not do checking or + * validation of the parameters. It only converts the cookie string into + * a JSONObject. + * @param string The cookie specification string. + * @return A JSONObject containing "name", "value", and possibly other + * members. + * @throws JSONException + */ + public static JSONObject toJSONObject(String string) throws JSONException{ + String name; + JSONObject jo = new JSONObject(); + Object value; + JSONTokener x = new JSONTokener(string); + jo.put("name", x.nextTo('=')); + x.next('='); + jo.put("value", x.nextTo(';')); + x.next(); + while(x.more()){ + name = unescape(x.nextTo("=;")); + if (x.next() != '='){ + if (name.equals("secure")){ + value = Boolean.TRUE; + }else{ + throw x.syntaxError("Missing '=' in cookie parameter."); + } + }else{ + value = unescape(x.nextTo(';')); + x.next(); + } + jo.put(name, value); + } + return jo; + } - /** - * Convert a cookie specification string into a JSONObject. The string - * will contain a name value pair separated by '='. The name and the value - * will be unescaped, possibly converting '+' and '%' sequences. The - * cookie properties may follow, separated by ';', also represented as - * name=value (except the secure property, which does not have a value). - * The name will be stored under the key "name", and the value will be - * stored under the key "value". This method does not do checking or - * validation of the parameters. It only converts the cookie string into - * a JSONObject. - * @param string The cookie specification string. - * @return A JSONObject containing "name", "value", and possibly other - * members. - * @throws JSONException - */ - public static JSONObject toJSONObject(String string) throws JSONException { - String name; - JSONObject jo = new JSONObject(); - Object value; - JSONTokener x = new JSONTokener(string); - jo.put("name", x.nextTo('=')); - x.next('='); - jo.put("value", x.nextTo(';')); - x.next(); - while (x.more()) { - name = unescape(x.nextTo("=;")); - if (x.next() != '=') { - if (name.equals("secure")) { - value = Boolean.TRUE; - } else { - throw x.syntaxError("Missing '=' in cookie parameter."); - } - } else { - value = unescape(x.nextTo(';')); - x.next(); - } - jo.put(name, value); - } - return jo; - } + /** + * Convert a JSONObject into a cookie specification string. The JSONObject + * must contain "name" and "value" members. + * If the JSONObject contains "expires", "domain", "path", or "secure" + * members, they will be appended to the cookie specification string. + * All other members are ignored. + * @param jo A JSONObject + * @return A cookie specification string + * @throws JSONException + */ + public static String toString(JSONObject jo) throws JSONException{ + StringBuffer sb = new StringBuffer(); + sb.append(escape(jo.getString("name"))); + sb.append("="); + sb.append(escape(jo.getString("value"))); + if (jo.has("expires")){ + sb.append(";expires="); + sb.append(jo.getString("expires")); + } + if (jo.has("domain")){ + sb.append(";domain="); + sb.append(escape(jo.getString("domain"))); + } + if (jo.has("path")){ + sb.append(";path="); + sb.append(escape(jo.getString("path"))); + } + if (jo.optBoolean("secure")){ + sb.append(";secure"); + } + return sb.toString(); + } - /** - * Convert a JSONObject into a cookie specification string. The JSONObject - * must contain "name" and "value" members. - * If the JSONObject contains "expires", "domain", "path", or "secure" - * members, they will be appended to the cookie specification string. - * All other members are ignored. - * @param jo A JSONObject - * @return A cookie specification string - * @throws JSONException - */ - public static String toString(JSONObject jo) throws JSONException { - StringBuffer sb = new StringBuffer(); - - sb.append(escape(jo.getString("name"))); - sb.append("="); - sb.append(escape(jo.getString("value"))); - if (jo.has("expires")) { - sb.append(";expires="); - sb.append(jo.getString("expires")); - } - if (jo.has("domain")) { - sb.append(";domain="); - sb.append(escape(jo.getString("domain"))); - } - if (jo.has("path")) { - sb.append(";path="); - sb.append(escape(jo.getString("path"))); - } - if (jo.optBoolean("secure")) { - sb.append(";secure"); - } - return sb.toString(); - } - - /** - * Convert <code>%</code><i>hh</i> sequences to single characters, and - * convert plus to space. - * @param string A string that may contain - * <code>+</code> <small>(plus)</small> and - * <code>%</code><i>hh</i> sequences. - * @return The unescaped string. - */ - public static String unescape(String string) { - int length = string.length(); - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < length; ++i) { - char c = string.charAt(i); - if (c == '+') { - c = ' '; - } else if (c == '%' && i + 2 < length) { - int d = JSONTokener.dehexchar(string.charAt(i + 1)); - int e = JSONTokener.dehexchar(string.charAt(i + 2)); - if (d >= 0 && e >= 0) { - c = (char)(d * 16 + e); - i += 2; - } - } - sb.append(c); - } - return sb.toString(); - } + /** + * Convert <code>%</code><i>hh</i> sequences to single characters, and + * convert plus to space. + * @param string A string that may contain + * <code>+</code> <small>(plus)</small> and + * <code>%</code><i>hh</i> sequences. + * @return The unescaped string. + */ + public static String unescape(String string){ + int length = string.length(); + StringBuffer sb = new StringBuffer(); + for(int i = 0; i < length; ++i){ + char c = string.charAt(i); + if (c == '+'){ + c = ' '; + }else if (c == '%' && i + 2 < length){ + int d = JSONTokener.dehexchar(string.charAt(i + 1)); + int e = JSONTokener.dehexchar(string.charAt(i + 2)); + if (d >= 0 && e >= 0){ + c = (char)(d * 16 + e); + i += 2; + } + } + sb.append(c); + } + return sb.toString(); + } } diff --git a/src/org/json/CookieList.java b/src/org/json/CookieList.java index 7f4fe075174b7533f5df016694a9b85998b26cdf..fc0b98b85f602b98bb05352efcc91270891a47d1 100644 --- a/src/org/json/CookieList.java +++ b/src/org/json/CookieList.java @@ -33,58 +33,57 @@ import java.util.Iterator; */ public class CookieList { - /** - * Convert a cookie list into a JSONObject. A cookie list is a sequence - * of name/value pairs. The names are separated from the values by '='. - * The pairs are separated by ';'. The names and the values - * will be unescaped, possibly converting '+' and '%' sequences. - * - * To add a cookie to a cooklist, - * cookielistJSONObject.put(cookieJSONObject.getString("name"), - * cookieJSONObject.getString("value")); - * @param string A cookie list string - * @return A JSONObject - * @throws JSONException - */ - public static JSONObject toJSONObject(String string) throws JSONException { - JSONObject jo = new JSONObject(); - JSONTokener x = new JSONTokener(string); - while (x.more()) { - String name = Cookie.unescape(x.nextTo('=')); - x.next('='); - jo.put(name, Cookie.unescape(x.nextTo(';'))); - x.next(); - } - return jo; - } + /** + * Convert a cookie list into a JSONObject. A cookie list is a sequence + * of name/value pairs. The names are separated from the values by '='. + * The pairs are separated by ';'. The names and the values + * will be unescaped, possibly converting '+' and '%' sequences. + * + * To add a cookie to a cooklist, + * cookielistJSONObject.put(cookieJSONObject.getString("name"), + * cookieJSONObject.getString("value")); + * @param string A cookie list string + * @return A JSONObject + * @throws JSONException + */ + public static JSONObject toJSONObject(String string) throws JSONException{ + JSONObject jo = new JSONObject(); + JSONTokener x = new JSONTokener(string); + while(x.more()){ + String name = Cookie.unescape(x.nextTo('=')); + x.next('='); + jo.put(name, Cookie.unescape(x.nextTo(';'))); + x.next(); + } + return jo; + } - - /** - * Convert a JSONObject into a cookie list. A cookie list is a sequence - * of name/value pairs. The names are separated from the values by '='. - * The pairs are separated by ';'. The characters '%', '+', '=', and ';' - * in the names and values are replaced by "%hh". - * @param jo A JSONObject - * @return A cookie list string - * @throws JSONException - */ - public static String toString(JSONObject jo) throws JSONException { - boolean b = false; - Iterator keys = jo.keys(); - String string; - StringBuffer sb = new StringBuffer(); - while (keys.hasNext()) { - string = keys.next().toString(); - if (!jo.isNull(string)) { - if (b) { - sb.append(';'); - } - sb.append(Cookie.escape(string)); - sb.append("="); - sb.append(Cookie.escape(jo.getString(string))); - b = true; - } - } - return sb.toString(); - } + /** + * Convert a JSONObject into a cookie list. A cookie list is a sequence + * of name/value pairs. The names are separated from the values by '='. + * The pairs are separated by ';'. The characters '%', '+', '=', and ';' + * in the names and values are replaced by "%hh". + * @param jo A JSONObject + * @return A cookie list string + * @throws JSONException + */ + public static String toString(JSONObject jo) throws JSONException{ + boolean b = false; + Iterator keys = jo.keys(); + String string; + StringBuffer sb = new StringBuffer(); + while(keys.hasNext()){ + string = keys.next().toString(); + if (!jo.isNull(string)){ + if (b){ + sb.append(';'); + } + sb.append(Cookie.escape(string)); + sb.append("="); + sb.append(Cookie.escape(jo.getString(string))); + b = true; + } + } + return sb.toString(); + } } diff --git a/src/org/json/HTTP.java b/src/org/json/HTTP.java index 43d04a80458fa2cfadc90af2bff91735404f7ead..45816a579d5d427cb15e9f906812743e4f271fec 100644 --- a/src/org/json/HTTP.java +++ b/src/org/json/HTTP.java @@ -33,131 +33,128 @@ import java.util.Iterator; */ public class HTTP { - /** Carriage return/line feed. */ - public static final String CRLF = "\r\n"; - - /** - * Convert an HTTP header string into a JSONObject. It can be a request - * header or a response header. A request header will contain - * <pre>{ - * Method: "POST" (for example), - * "Request-URI": "/" (for example), - * "HTTP-Version": "HTTP/1.1" (for example) - * }</pre> - * A response header will contain - * <pre>{ - * "HTTP-Version": "HTTP/1.1" (for example), - * "Status-Code": "200" (for example), - * "Reason-Phrase": "OK" (for example) - * }</pre> - * In addition, the other parameters in the header will be captured, using - * the HTTP field names as JSON names, so that <pre> - * Date: Sun, 26 May 2002 18:06:04 GMT - * Cookie: Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s - * Cache-Control: no-cache</pre> - * become - * <pre>{... - * Date: "Sun, 26 May 2002 18:06:04 GMT", - * Cookie: "Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s", - * "Cache-Control": "no-cache", - * ...}</pre> - * It does no further checking or conversion. It does not parse dates. - * It does not do '%' transforms on URLs. - * @param string An HTTP header string. - * @return A JSONObject containing the elements and attributes - * of the XML string. - * @throws JSONException - */ - public static JSONObject toJSONObject(String string) throws JSONException { - JSONObject jo = new JSONObject(); - HTTPTokener x = new HTTPTokener(string); - String token; - - token = x.nextToken(); - if (token.toUpperCase().startsWith("HTTP")) { - -// Response - - jo.put("HTTP-Version", token); - jo.put("Status-Code", x.nextToken()); - jo.put("Reason-Phrase", x.nextTo('\0')); - x.next(); - - } else { - -// Request - - jo.put("Method", token); - jo.put("Request-URI", x.nextToken()); - jo.put("HTTP-Version", x.nextToken()); - } - -// Fields - - while (x.more()) { - String name = x.nextTo(':'); - x.next(':'); - jo.put(name, x.nextTo('\0')); - x.next(); - } - return jo; - } - - - /** - * Convert a JSONObject into an HTTP header. A request header must contain - * <pre>{ - * Method: "POST" (for example), - * "Request-URI": "/" (for example), - * "HTTP-Version": "HTTP/1.1" (for example) - * }</pre> - * A response header must contain - * <pre>{ - * "HTTP-Version": "HTTP/1.1" (for example), - * "Status-Code": "200" (for example), - * "Reason-Phrase": "OK" (for example) - * }</pre> - * Any other members of the JSONObject will be output as HTTP fields. - * The result will end with two CRLF pairs. - * @param jo A JSONObject - * @return An HTTP header string. - * @throws JSONException if the object does not contain enough - * information. - */ - public static String toString(JSONObject jo) throws JSONException { - Iterator keys = jo.keys(); - String string; - StringBuffer sb = new StringBuffer(); - if (jo.has("Status-Code") && jo.has("Reason-Phrase")) { - sb.append(jo.getString("HTTP-Version")); - sb.append(' '); - sb.append(jo.getString("Status-Code")); - sb.append(' '); - sb.append(jo.getString("Reason-Phrase")); - } else if (jo.has("Method") && jo.has("Request-URI")) { - sb.append(jo.getString("Method")); - sb.append(' '); - sb.append('"'); - sb.append(jo.getString("Request-URI")); - sb.append('"'); - sb.append(' '); - sb.append(jo.getString("HTTP-Version")); - } else { - throw new JSONException("Not enough material for an HTTP header."); - } - sb.append(CRLF); - while (keys.hasNext()) { - string = keys.next().toString(); - if (!"HTTP-Version".equals(string) && !"Status-Code".equals(string) && - !"Reason-Phrase".equals(string) && !"Method".equals(string) && - !"Request-URI".equals(string) && !jo.isNull(string)) { - sb.append(string); - sb.append(": "); - sb.append(jo.getString(string)); - sb.append(CRLF); - } - } - sb.append(CRLF); - return sb.toString(); - } + /** Carriage return/line feed. */ + public static final String CRLF = "\r\n"; + + /** + * Convert an HTTP header string into a JSONObject. It can be a request + * header or a response header. A request header will contain + * <pre>{ + * Method: "POST" (for example), + * "Request-URI": "/" (for example), + * "HTTP-Version": "HTTP/1.1" (for example) + * }</pre> + * A response header will contain + * <pre>{ + * "HTTP-Version": "HTTP/1.1" (for example), + * "Status-Code": "200" (for example), + * "Reason-Phrase": "OK" (for example) + * }</pre> + * In addition, the other parameters in the header will be captured, using + * the HTTP field names as JSON names, so that <pre> + * Date: Sun, 26 May 2002 18:06:04 GMT + * Cookie: Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s + * Cache-Control: no-cache</pre> + * become + * <pre>{... + * Date: "Sun, 26 May 2002 18:06:04 GMT", + * Cookie: "Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s", + * "Cache-Control": "no-cache", + * ...}</pre> + * It does no further checking or conversion. It does not parse dates. + * It does not do '%' transforms on URLs. + * @param string An HTTP header string. + * @return A JSONObject containing the elements and attributes + * of the XML string. + * @throws JSONException + */ + public static JSONObject toJSONObject(String string) throws JSONException{ + JSONObject jo = new JSONObject(); + HTTPTokener x = new HTTPTokener(string); + String token; + + token = x.nextToken(); + if (token.toUpperCase().startsWith("HTTP")){ + + // Response + + jo.put("HTTP-Version", token); + jo.put("Status-Code", x.nextToken()); + jo.put("Reason-Phrase", x.nextTo('\0')); + x.next(); + + }else{ + + // Request + + jo.put("Method", token); + jo.put("Request-URI", x.nextToken()); + jo.put("HTTP-Version", x.nextToken()); + } + + // Fields + + while(x.more()){ + String name = x.nextTo(':'); + x.next(':'); + jo.put(name, x.nextTo('\0')); + x.next(); + } + return jo; + } + + /** + * Convert a JSONObject into an HTTP header. A request header must contain + * <pre>{ + * Method: "POST" (for example), + * "Request-URI": "/" (for example), + * "HTTP-Version": "HTTP/1.1" (for example) + * }</pre> + * A response header must contain + * <pre>{ + * "HTTP-Version": "HTTP/1.1" (for example), + * "Status-Code": "200" (for example), + * "Reason-Phrase": "OK" (for example) + * }</pre> + * Any other members of the JSONObject will be output as HTTP fields. + * The result will end with two CRLF pairs. + * @param jo A JSONObject + * @return An HTTP header string. + * @throws JSONException if the object does not contain enough + * information. + */ + public static String toString(JSONObject jo) throws JSONException{ + Iterator keys = jo.keys(); + String string; + StringBuffer sb = new StringBuffer(); + if (jo.has("Status-Code") && jo.has("Reason-Phrase")){ + sb.append(jo.getString("HTTP-Version")); + sb.append(' '); + sb.append(jo.getString("Status-Code")); + sb.append(' '); + sb.append(jo.getString("Reason-Phrase")); + }else if (jo.has("Method") && jo.has("Request-URI")){ + sb.append(jo.getString("Method")); + sb.append(' '); + sb.append('"'); + sb.append(jo.getString("Request-URI")); + sb.append('"'); + sb.append(' '); + sb.append(jo.getString("HTTP-Version")); + }else{ + throw new JSONException("Not enough material for an HTTP header."); + } + sb.append(CRLF); + while(keys.hasNext()){ + string = keys.next().toString(); + if (!"HTTP-Version".equals(string) && !"Status-Code".equals(string) && !"Reason-Phrase".equals(string) && !"Method".equals(string) && !"Request-URI".equals(string) && !jo.isNull(string)){ + sb.append(string); + sb.append(": "); + sb.append(jo.getString(string)); + sb.append(CRLF); + } + } + sb.append(CRLF); + return sb.toString(); + } } diff --git a/src/org/json/HTTPTokener.java b/src/org/json/HTTPTokener.java index f62b3d55846da92ec27074ede60be87aa92bad30..2f35509bc2f39c66d8444dad81283a04e1d62d91 100644 --- a/src/org/json/HTTPTokener.java +++ b/src/org/json/HTTPTokener.java @@ -32,46 +32,45 @@ SOFTWARE. */ public class HTTPTokener extends JSONTokener { - /** - * Construct an HTTPTokener from a string. - * @param string A source string. - */ - public HTTPTokener(String string) { - super(string); - } + /** + * Construct an HTTPTokener from a string. + * @param string A source string. + */ + public HTTPTokener(String string){ + super(string); + } - - /** - * Get the next token or string. This is used in parsing HTTP headers. - * @throws JSONException - * @return A String. - */ - public String nextToken() throws JSONException { - char c; - char q; - StringBuffer sb = new StringBuffer(); - do { - c = next(); - } while (Character.isWhitespace(c)); - if (c == '"' || c == '\'') { - q = c; - for (;;) { - c = next(); - if (c < ' ') { - throw syntaxError("Unterminated string."); - } - if (c == q) { - return sb.toString(); - } - sb.append(c); - } - } - for (;;) { - if (c == 0 || Character.isWhitespace(c)) { - return sb.toString(); - } - sb.append(c); - c = next(); - } - } + /** + * Get the next token or string. This is used in parsing HTTP headers. + * @throws JSONException + * @return A String. + */ + public String nextToken() throws JSONException{ + char c; + char q; + StringBuffer sb = new StringBuffer(); + do{ + c = next(); + }while(Character.isWhitespace(c)); + if (c == '"' || c == '\''){ + q = c; + for(;;){ + c = next(); + if (c < ' '){ + throw syntaxError("Unterminated string."); + } + if (c == q){ + return sb.toString(); + } + sb.append(c); + } + } + for(;;){ + if (c == 0 || Character.isWhitespace(c)){ + return sb.toString(); + } + sb.append(c); + c = next(); + } + } } diff --git a/src/org/json/JSONArray.java b/src/org/json/JSONArray.java index 71c277aea65052848518f3623fd79a3fa87d4c54..e9bca413fd821549823519d5db4f175b733edeab 100644 --- a/src/org/json/JSONArray.java +++ b/src/org/json/JSONArray.java @@ -81,826 +81,756 @@ import java.util.Map; */ public class JSONArray { - - /** - * The arrayList where the JSONArray's properties are kept. - */ - private final ArrayList myArrayList; - - - /** - * Construct an empty JSONArray. - */ - public JSONArray() { - this.myArrayList = new ArrayList(); - } - - /** - * Construct a JSONArray from a JSONTokener. - * @param x A JSONTokener - * @throws JSONException If there is a syntax error. - */ - public JSONArray(JSONTokener x) throws JSONException { - this(); - if (x.nextClean() != '[') { - throw x.syntaxError("A JSONArray text must start with '['"); - } - if (x.nextClean() != ']') { - x.back(); - for (;;) { - if (x.nextClean() == ',') { - x.back(); - this.myArrayList.add(JSONObject.NULL); - } else { - x.back(); - this.myArrayList.add(x.nextValue()); - } - switch (x.nextClean()) { - case ';': - case ',': - if (x.nextClean() == ']') { - return; - } - x.back(); - break; - case ']': - return; - default: - throw x.syntaxError("Expected a ',' or ']'"); - } - } - } - } - - - /** - * Construct a JSONArray from a source JSON text. - * @param source A string that begins with - * <code>[</code> <small>(left bracket)</small> - * and ends with <code>]</code> <small>(right bracket)</small>. - * @throws JSONException If there is a syntax error. - */ - public JSONArray(String source) throws JSONException { - this(new JSONTokener(source)); - } - - - /** - * Construct a JSONArray from a Collection. - * @param collection A Collection. - */ - public JSONArray(Collection collection) { - this.myArrayList = new ArrayList(); - if (collection != null) { - Iterator iter = collection.iterator(); - while (iter.hasNext()) { - this.myArrayList.add(JSONObject.wrap(iter.next())); - } - } - } - - - /** - * Construct a JSONArray from an array - * @throws JSONException If not an array. - */ - public JSONArray(Object array) throws JSONException { - this(); - if (array.getClass().isArray()) { - int length = Array.getLength(array); - for (int i = 0; i < length; i += 1) { - this.put(JSONObject.wrap(Array.get(array, i))); - } - } else { - throw new JSONException( -"JSONArray initial value should be a string or collection or array."); - } - } - - - /** - * Get the object value associated with an index. - * @param index - * The index must be between 0 and length() - 1. - * @return An object value. - * @throws JSONException If there is no value for the index. - */ - public Object get(int index) throws JSONException { - Object object = this.opt(index); - if (object == null) { - throw new JSONException("JSONArray[" + index + "] not found."); - } - return object; - } - - - /** - * Get the boolean value associated with an index. - * The string values "true" and "false" are converted to boolean. - * - * @param index The index must be between 0 and length() - 1. - * @return The truth. - * @throws JSONException If there is no value for the index or if the - * value is not convertible to boolean. - */ - public boolean getBoolean(int index) throws JSONException { - Object object = this.get(index); - if (object.equals(Boolean.FALSE) || - (object instanceof String && - ((String)object).equalsIgnoreCase("false"))) { - return false; - } else if (object.equals(Boolean.TRUE) || - (object instanceof String && - ((String)object).equalsIgnoreCase("true"))) { - return true; - } - throw new JSONException("JSONArray[" + index + "] is not a boolean."); - } - - - /** - * Get the double value associated with an index. - * - * @param index The index must be between 0 and length() - 1. - * @return The value. - * @throws JSONException If the key is not found or if the value cannot - * be converted to a number. - */ - public double getDouble(int index) throws JSONException { - Object object = this.get(index); - try { - return object instanceof Number - ? ((Number)object).doubleValue() - : Double.parseDouble((String)object); - } catch (Exception e) { - throw new JSONException("JSONArray[" + index + - "] is not a number."); - } - } - - - /** - * Get the int value associated with an index. - * - * @param index The index must be between 0 and length() - 1. - * @return The value. - * @throws JSONException If the key is not found or if the value is not a number. - */ - public int getInt(int index) throws JSONException { - Object object = this.get(index); - try { - return object instanceof Number - ? ((Number)object).intValue() - : Integer.parseInt((String)object); - } catch (Exception e) { - throw new JSONException("JSONArray[" + index + - "] is not a number."); - } - } - - - /** - * Get the JSONArray associated with an index. - * @param index The index must be between 0 and length() - 1. - * @return A JSONArray value. - * @throws JSONException If there is no value for the index. or if the - * value is not a JSONArray - */ - public JSONArray getJSONArray(int index) throws JSONException { - Object object = this.get(index); - if (object instanceof JSONArray) { - return (JSONArray)object; - } - throw new JSONException("JSONArray[" + index + - "] is not a JSONArray."); - } - - - /** - * Get the JSONObject associated with an index. - * @param index subscript - * @return A JSONObject value. - * @throws JSONException If there is no value for the index or if the - * value is not a JSONObject - */ - public JSONObject getJSONObject(int index) throws JSONException { - Object object = this.get(index); - if (object instanceof JSONObject) { - return (JSONObject)object; - } - throw new JSONException("JSONArray[" + index + - "] is not a JSONObject."); - } - - - /** - * Get the long value associated with an index. - * - * @param index The index must be between 0 and length() - 1. - * @return The value. - * @throws JSONException If the key is not found or if the value cannot - * be converted to a number. - */ - public long getLong(int index) throws JSONException { - Object object = this.get(index); - try { - return object instanceof Number - ? ((Number)object).longValue() - : Long.parseLong((String)object); - } catch (Exception e) { - throw new JSONException("JSONArray[" + index + - "] is not a number."); - } - } - - - /** - * Get the string associated with an index. - * @param index The index must be between 0 and length() - 1. - * @return A string value. - * @throws JSONException If there is no string value for the index. - */ - public String getString(int index) throws JSONException { - Object object = this.get(index); - if (object instanceof String) { - return (String)object; - } - throw new JSONException("JSONArray[" + index + "] not a string."); - } - - - /** - * Determine if the value is null. - * @param index The index must be between 0 and length() - 1. - * @return true if the value at the index is null, or if there is no value. - */ - public boolean isNull(int index) { - return JSONObject.NULL.equals(this.opt(index)); - } - - - /** - * Make a string from the contents of this JSONArray. The - * <code>separator</code> string is inserted between each element. - * Warning: This method assumes that the data structure is acyclical. - * @param separator A string that will be inserted between the elements. - * @return a string. - * @throws JSONException If the array contains an invalid number. - */ - public String join(String separator) throws JSONException { - int len = this.length(); - StringBuffer sb = new StringBuffer(); - - for (int i = 0; i < len; i += 1) { - if (i > 0) { - sb.append(separator); - } - sb.append(JSONObject.valueToString(this.myArrayList.get(i))); - } - return sb.toString(); - } - - - /** - * Get the number of elements in the JSONArray, included nulls. - * - * @return The length (or size). - */ - public int length() { - return this.myArrayList.size(); - } - - - /** - * Get the optional object value associated with an index. - * @param index The index must be between 0 and length() - 1. - * @return An object value, or null if there is no - * object at that index. - */ - public Object opt(int index) { - return (index < 0 || index >= this.length()) - ? null - : this.myArrayList.get(index); - } - - - /** - * Get the optional boolean value associated with an index. - * It returns false if there is no value at that index, - * or if the value is not Boolean.TRUE or the String "true". - * - * @param index The index must be between 0 and length() - 1. - * @return The truth. - */ - public boolean optBoolean(int index) { - return this.optBoolean(index, false); - } - - - /** - * Get the optional boolean value associated with an index. - * It returns the defaultValue if there is no value at that index or if - * it is not a Boolean or the String "true" or "false" (case insensitive). - * - * @param index The index must be between 0 and length() - 1. - * @param defaultValue A boolean default. - * @return The truth. - */ - public boolean optBoolean(int index, boolean defaultValue) { - try { - return this.getBoolean(index); - } catch (Exception e) { - return defaultValue; - } - } - - - /** - * Get the optional double value associated with an index. - * NaN is returned if there is no value for the index, - * or if the value is not a number and cannot be converted to a number. - * - * @param index The index must be between 0 and length() - 1. - * @return The value. - */ - public double optDouble(int index) { - return this.optDouble(index, Double.NaN); - } - - - /** - * Get the optional double value associated with an index. - * The defaultValue is returned if there is no value for the index, - * or if the value is not a number and cannot be converted to a number. - * - * @param index subscript - * @param defaultValue The default value. - * @return The value. - */ - public double optDouble(int index, double defaultValue) { - try { - return this.getDouble(index); - } catch (Exception e) { - return defaultValue; - } - } - - - /** - * Get the optional int value associated with an index. - * Zero is returned if there is no value for the index, - * or if the value is not a number and cannot be converted to a number. - * - * @param index The index must be between 0 and length() - 1. - * @return The value. - */ - public int optInt(int index) { - return this.optInt(index, 0); - } - - - /** - * Get the optional int value associated with an index. - * The defaultValue is returned if there is no value for the index, - * or if the value is not a number and cannot be converted to a number. - * @param index The index must be between 0 and length() - 1. - * @param defaultValue The default value. - * @return The value. - */ - public int optInt(int index, int defaultValue) { - try { - return this.getInt(index); - } catch (Exception e) { - return defaultValue; - } - } - - - /** - * Get the optional JSONArray associated with an index. - * @param index subscript - * @return A JSONArray value, or null if the index has no value, - * or if the value is not a JSONArray. - */ - public JSONArray optJSONArray(int index) { - Object o = this.opt(index); - return o instanceof JSONArray ? (JSONArray)o : null; - } - - - /** - * Get the optional JSONObject associated with an index. - * Null is returned if the key is not found, or null if the index has - * no value, or if the value is not a JSONObject. - * - * @param index The index must be between 0 and length() - 1. - * @return A JSONObject value. - */ - public JSONObject optJSONObject(int index) { - Object o = this.opt(index); - return o instanceof JSONObject ? (JSONObject)o : null; - } - - - /** - * Get the optional long value associated with an index. - * Zero is returned if there is no value for the index, - * or if the value is not a number and cannot be converted to a number. - * - * @param index The index must be between 0 and length() - 1. - * @return The value. - */ - public long optLong(int index) { - return this.optLong(index, 0); - } - - - /** - * Get the optional long value associated with an index. - * The defaultValue is returned if there is no value for the index, - * or if the value is not a number and cannot be converted to a number. - * @param index The index must be between 0 and length() - 1. - * @param defaultValue The default value. - * @return The value. - */ - public long optLong(int index, long defaultValue) { - try { - return this.getLong(index); - } catch (Exception e) { - return defaultValue; - } - } - - - /** - * Get the optional string value associated with an index. It returns an - * empty string if there is no value at that index. If the value - * is not a string and is not null, then it is coverted to a string. - * - * @param index The index must be between 0 and length() - 1. - * @return A String value. - */ - public String optString(int index) { - return this.optString(index, ""); - } - - - /** - * Get the optional string associated with an index. - * The defaultValue is returned if the key is not found. - * - * @param index The index must be between 0 and length() - 1. - * @param defaultValue The default value. - * @return A String value. - */ - public String optString(int index, String defaultValue) { - Object object = this.opt(index); - return JSONObject.NULL.equals(object) - ? defaultValue : object - .toString(); - } - - - /** - * Append a boolean value. This increases the array's length by one. - * - * @param value A boolean value. - * @return this. - */ - public JSONArray put(boolean value) { - this.put(value ? Boolean.TRUE : Boolean.FALSE); - return this; - } - - - /** - * Put a value in the JSONArray, where the value will be a - * JSONArray which is produced from a Collection. - * @param value A Collection value. - * @return this. - */ - public JSONArray put(Collection value) { - this.put(new JSONArray(value)); - return this; - } - - - /** - * Append a double value. This increases the array's length by one. - * - * @param value A double value. - * @throws JSONException if the value is not finite. - * @return this. - */ - public JSONArray put(double value) throws JSONException { - Double d = new Double(value); - JSONObject.testValidity(d); - this.put(d); - return this; - } - - - /** - * Append an int value. This increases the array's length by one. - * - * @param value An int value. - * @return this. - */ - public JSONArray put(int value) { - this.put(new Integer(value)); - return this; - } - - - /** - * Append an long value. This increases the array's length by one. - * - * @param value A long value. - * @return this. - */ - public JSONArray put(long value) { - this.put(new Long(value)); - return this; - } - - - /** - * Put a value in the JSONArray, where the value will be a - * JSONObject which is produced from a Map. - * @param value A Map value. - * @return this. - */ - public JSONArray put(Map value) { - this.put(new JSONObject(value)); - return this; - } - - - /** - * Append an object value. This increases the array's length by one. - * @param value An object value. The value should be a - * Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the - * JSONObject.NULL object. - * @return this. - */ - public JSONArray put(Object value) { - this.myArrayList.add(value); - return this; - } - - - /** - * Put or replace a boolean value in the JSONArray. If the index is greater - * than the length of the JSONArray, then null elements will be added as - * necessary to pad it out. - * @param index The subscript. - * @param value A boolean value. - * @return this. - * @throws JSONException If the index is negative. - */ - public JSONArray put(int index, boolean value) throws JSONException { - this.put(index, value ? Boolean.TRUE : Boolean.FALSE); - return this; - } - - - /** - * Put a value in the JSONArray, where the value will be a - * JSONArray which is produced from a Collection. - * @param index The subscript. - * @param value A Collection value. - * @return this. - * @throws JSONException If the index is negative or if the value is - * not finite. - */ - public JSONArray put(int index, Collection value) throws JSONException { - this.put(index, new JSONArray(value)); - return this; - } - - - /** - * Put or replace a double value. If the index is greater than the length of - * the JSONArray, then null elements will be added as necessary to pad - * it out. - * @param index The subscript. - * @param value A double value. - * @return this. - * @throws JSONException If the index is negative or if the value is - * not finite. - */ - public JSONArray put(int index, double value) throws JSONException { - this.put(index, new Double(value)); - return this; - } - - - /** - * Put or replace an int value. If the index is greater than the length of - * the JSONArray, then null elements will be added as necessary to pad - * it out. - * @param index The subscript. - * @param value An int value. - * @return this. - * @throws JSONException If the index is negative. - */ - public JSONArray put(int index, int value) throws JSONException { - this.put(index, new Integer(value)); - return this; - } - - - /** - * Put or replace a long value. If the index is greater than the length of - * the JSONArray, then null elements will be added as necessary to pad - * it out. - * @param index The subscript. - * @param value A long value. - * @return this. - * @throws JSONException If the index is negative. - */ - public JSONArray put(int index, long value) throws JSONException { - this.put(index, new Long(value)); - return this; - } - - - /** - * Put a value in the JSONArray, where the value will be a - * JSONObject that is produced from a Map. - * @param index The subscript. - * @param value The Map value. - * @return this. - * @throws JSONException If the index is negative or if the the value is - * an invalid number. - */ - public JSONArray put(int index, Map value) throws JSONException { - this.put(index, new JSONObject(value)); - return this; - } - - - /** - * Put or replace an object value in the JSONArray. If the index is greater - * than the length of the JSONArray, then null elements will be added as - * necessary to pad it out. - * @param index The subscript. - * @param value The value to put into the array. The value should be a - * Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the - * JSONObject.NULL object. - * @return this. - * @throws JSONException If the index is negative or if the the value is - * an invalid number. - */ - public JSONArray put(int index, Object value) throws JSONException { - JSONObject.testValidity(value); - if (index < 0) { - throw new JSONException("JSONArray[" + index + "] not found."); - } - if (index < this.length()) { - this.myArrayList.set(index, value); - } else { - while (index != this.length()) { - this.put(JSONObject.NULL); - } - this.put(value); - } - return this; - } - - - /** - * Remove an index and close the hole. - * @param index The index of the element to be removed. - * @return The value that was associated with the index, - * or null if there was no value. - */ - public Object remove(int index) { - Object o = this.opt(index); - this.myArrayList.remove(index); - return o; - } - - - /** - * Produce a JSONObject by combining a JSONArray of names with the values - * of this JSONArray. - * @param names A JSONArray containing a list of key strings. These will be - * paired with the values. - * @return A JSONObject, or null if there are no names or if this JSONArray - * has no values. - * @throws JSONException If any of the names are null. - */ - public JSONObject toJSONObject(JSONArray names) throws JSONException { - if (names == null || names.length() == 0 || this.length() == 0) { - return null; - } - JSONObject jo = new JSONObject(); - for (int i = 0; i < names.length(); i += 1) { - jo.put(names.getString(i), this.opt(i)); - } - return jo; - } - - - /** - * Make a JSON text of this JSONArray. For compactness, no - * unnecessary whitespace is added. If it is not possible to produce a - * syntactically correct JSON text then null will be returned instead. This - * could occur if the array contains an invalid number. - * <p> - * Warning: This method assumes that the data structure is acyclical. - * - * @return a printable, displayable, transmittable - * representation of the array. - */ - public String toString() { - try { - return '[' + this.join(",") + ']'; - } catch (Exception e) { - return null; - } - } - - - /** - * Make a prettyprinted JSON text of this JSONArray. - * Warning: This method assumes that the data structure is acyclical. - * @param indentFactor The number of spaces to add to each level of - * indentation. - * @return a printable, displayable, transmittable - * representation of the object, beginning - * with <code>[</code> <small>(left bracket)</small> and ending - * with <code>]</code> <small>(right bracket)</small>. - * @throws JSONException - */ - public String toString(int indentFactor) throws JSONException { - StringWriter sw = new StringWriter(); - synchronized (sw.getBuffer()) { - return this.write(sw, indentFactor, 0).toString(); - } - } - - /** - * Write the contents of the JSONArray as JSON text to a writer. For - * compactness, no whitespace is added. - * <p> - * Warning: This method assumes that the data structure is acyclical. - * - * @return The writer. - * @throws JSONException - */ - public Writer write(Writer writer) throws JSONException { - return this.write(writer, 0, 0); - } - - /** - * Write the contents of the JSONArray as JSON text to a writer. For - * compactness, no whitespace is added. - * <p> - * Warning: This method assumes that the data structure is acyclical. - * - * @param indentFactor - * The number of spaces to add to each level of indentation. - * @param indent - * The indention of the top level. - * @return The writer. - * @throws JSONException - */ - Writer write(Writer writer, int indentFactor, int indent) - throws JSONException { - try { - boolean commanate = false; - int length = this.length(); - writer.write('['); - - if (length == 1) { - JSONObject.writeValue(writer, this.myArrayList.get(0), - indentFactor, indent); - } else if (length != 0) { - final int newindent = indent + indentFactor; - - for (int i = 0; i < length; i += 1) { - if (commanate) { - writer.write(','); - } - if (indentFactor > 0) { - writer.write('\n'); - } - JSONObject.indent(writer, newindent); - JSONObject.writeValue(writer, this.myArrayList.get(i), - indentFactor, newindent); - commanate = true; - } - if (indentFactor > 0) { - writer.write('\n'); - } - JSONObject.indent(writer, indent); - } - writer.write(']'); - return writer; - } catch (IOException e) { - throw new JSONException(e); - } - } + /** + * The arrayList where the JSONArray's properties are kept. + */ + private final ArrayList myArrayList; + + /** + * Construct an empty JSONArray. + */ + public JSONArray(){ + this.myArrayList = new ArrayList(); + } + + /** + * Construct a JSONArray from a JSONTokener. + * @param x A JSONTokener + * @throws JSONException If there is a syntax error. + */ + public JSONArray(JSONTokener x) throws JSONException{ + this(); + if (x.nextClean() != '['){ + throw x.syntaxError("A JSONArray text must start with '['"); + } + if (x.nextClean() != ']'){ + x.back(); + for(;;){ + if (x.nextClean() == ','){ + x.back(); + this.myArrayList.add(JSONObject.NULL); + }else{ + x.back(); + this.myArrayList.add(x.nextValue()); + } + switch(x.nextClean()){ + case ';': + case ',': + if (x.nextClean() == ']'){ + return; + } + x.back(); + break; + case ']': + return; + default: + throw x.syntaxError("Expected a ',' or ']'"); + } + } + } + } + + /** + * Construct a JSONArray from a source JSON text. + * @param source A string that begins with + * <code>[</code> <small>(left bracket)</small> + * and ends with <code>]</code> <small>(right bracket)</small>. + * @throws JSONException If there is a syntax error. + */ + public JSONArray(String source) throws JSONException{ + this(new JSONTokener(source)); + } + + /** + * Construct a JSONArray from a Collection. + * @param collection A Collection. + */ + public JSONArray(Collection collection){ + this.myArrayList = new ArrayList(); + if (collection != null){ + Iterator iter = collection.iterator(); + while(iter.hasNext()){ + this.myArrayList.add(JSONObject.wrap(iter.next())); + } + } + } + + /** + * Construct a JSONArray from an array + * @throws JSONException If not an array. + */ + public JSONArray(Object array) throws JSONException{ + this(); + if (array.getClass().isArray()){ + int length = Array.getLength(array); + for(int i = 0; i < length; i += 1){ + this.put(JSONObject.wrap(Array.get(array, i))); + } + }else{ + throw new JSONException("JSONArray initial value should be a string or collection or array."); + } + } + + /** + * Get the object value associated with an index. + * @param index + * The index must be between 0 and length() - 1. + * @return An object value. + * @throws JSONException If there is no value for the index. + */ + public Object get(int index) throws JSONException{ + Object object = this.opt(index); + if (object == null){ + throw new JSONException("JSONArray[" + index + "] not found."); + } + return object; + } + + /** + * Get the boolean value associated with an index. + * The string values "true" and "false" are converted to boolean. + * + * @param index The index must be between 0 and length() - 1. + * @return The truth. + * @throws JSONException If there is no value for the index or if the + * value is not convertible to boolean. + */ + public boolean getBoolean(int index) throws JSONException{ + Object object = this.get(index); + if (object.equals(Boolean.FALSE) || (object instanceof String && ((String)object).equalsIgnoreCase("false"))){ + return false; + }else if (object.equals(Boolean.TRUE) || (object instanceof String && ((String)object).equalsIgnoreCase("true"))){ + return true; + } + throw new JSONException("JSONArray[" + index + "] is not a boolean."); + } + + /** + * Get the double value associated with an index. + * + * @param index The index must be between 0 and length() - 1. + * @return The value. + * @throws JSONException If the key is not found or if the value cannot + * be converted to a number. + */ + public double getDouble(int index) throws JSONException{ + Object object = this.get(index); + try{ + return object instanceof Number ? ((Number)object).doubleValue() : Double.parseDouble((String)object); + }catch(Exception e){ + throw new JSONException("JSONArray[" + index + "] is not a number."); + } + } + + /** + * Get the int value associated with an index. + * + * @param index The index must be between 0 and length() - 1. + * @return The value. + * @throws JSONException If the key is not found or if the value is not a number. + */ + public int getInt(int index) throws JSONException{ + Object object = this.get(index); + try{ + return object instanceof Number ? ((Number)object).intValue() : Integer.parseInt((String)object); + }catch(Exception e){ + throw new JSONException("JSONArray[" + index + "] is not a number."); + } + } + + /** + * Get the JSONArray associated with an index. + * @param index The index must be between 0 and length() - 1. + * @return A JSONArray value. + * @throws JSONException If there is no value for the index. or if the + * value is not a JSONArray + */ + public JSONArray getJSONArray(int index) throws JSONException{ + Object object = this.get(index); + if (object instanceof JSONArray){ + return (JSONArray)object; + } + throw new JSONException("JSONArray[" + index + "] is not a JSONArray."); + } + + /** + * Get the JSONObject associated with an index. + * @param index subscript + * @return A JSONObject value. + * @throws JSONException If there is no value for the index or if the + * value is not a JSONObject + */ + public JSONObject getJSONObject(int index) throws JSONException{ + Object object = this.get(index); + if (object instanceof JSONObject){ + return (JSONObject)object; + } + throw new JSONException("JSONArray[" + index + "] is not a JSONObject."); + } + + /** + * Get the long value associated with an index. + * + * @param index The index must be between 0 and length() - 1. + * @return The value. + * @throws JSONException If the key is not found or if the value cannot + * be converted to a number. + */ + public long getLong(int index) throws JSONException{ + Object object = this.get(index); + try{ + return object instanceof Number ? ((Number)object).longValue() : Long.parseLong((String)object); + }catch(Exception e){ + throw new JSONException("JSONArray[" + index + "] is not a number."); + } + } + + /** + * Get the string associated with an index. + * @param index The index must be between 0 and length() - 1. + * @return A string value. + * @throws JSONException If there is no string value for the index. + */ + public String getString(int index) throws JSONException{ + Object object = this.get(index); + if (object instanceof String){ + return (String)object; + } + throw new JSONException("JSONArray[" + index + "] not a string."); + } + + /** + * Determine if the value is null. + * @param index The index must be between 0 and length() - 1. + * @return true if the value at the index is null, or if there is no value. + */ + public boolean isNull(int index){ + return JSONObject.NULL.equals(this.opt(index)); + } + + /** + * Make a string from the contents of this JSONArray. The + * <code>separator</code> string is inserted between each element. + * Warning: This method assumes that the data structure is acyclical. + * @param separator A string that will be inserted between the elements. + * @return a string. + * @throws JSONException If the array contains an invalid number. + */ + public String join(String separator) throws JSONException{ + int len = this.length(); + StringBuffer sb = new StringBuffer(); + + for(int i = 0; i < len; i += 1){ + if (i > 0){ + sb.append(separator); + } + sb.append(JSONObject.valueToString(this.myArrayList.get(i))); + } + return sb.toString(); + } + + /** + * Get the number of elements in the JSONArray, included nulls. + * + * @return The length (or size). + */ + public int length(){ + return this.myArrayList.size(); + } + + /** + * Get the optional object value associated with an index. + * @param index The index must be between 0 and length() - 1. + * @return An object value, or null if there is no + * object at that index. + */ + public Object opt(int index){ + return (index < 0 || index >= this.length()) ? null : this.myArrayList.get(index); + } + + /** + * Get the optional boolean value associated with an index. + * It returns false if there is no value at that index, + * or if the value is not Boolean.TRUE or the String "true". + * + * @param index The index must be between 0 and length() - 1. + * @return The truth. + */ + public boolean optBoolean(int index){ + return this.optBoolean(index, false); + } + + /** + * Get the optional boolean value associated with an index. + * It returns the defaultValue if there is no value at that index or if + * it is not a Boolean or the String "true" or "false" (case insensitive). + * + * @param index The index must be between 0 and length() - 1. + * @param defaultValue A boolean default. + * @return The truth. + */ + public boolean optBoolean(int index, boolean defaultValue){ + try{ + return this.getBoolean(index); + }catch(Exception e){ + return defaultValue; + } + } + + /** + * Get the optional double value associated with an index. + * NaN is returned if there is no value for the index, + * or if the value is not a number and cannot be converted to a number. + * + * @param index The index must be between 0 and length() - 1. + * @return The value. + */ + public double optDouble(int index){ + return this.optDouble(index, Double.NaN); + } + + /** + * Get the optional double value associated with an index. + * The defaultValue is returned if there is no value for the index, + * or if the value is not a number and cannot be converted to a number. + * + * @param index subscript + * @param defaultValue The default value. + * @return The value. + */ + public double optDouble(int index, double defaultValue){ + try{ + return this.getDouble(index); + }catch(Exception e){ + return defaultValue; + } + } + + /** + * Get the optional int value associated with an index. + * Zero is returned if there is no value for the index, + * or if the value is not a number and cannot be converted to a number. + * + * @param index The index must be between 0 and length() - 1. + * @return The value. + */ + public int optInt(int index){ + return this.optInt(index, 0); + } + + /** + * Get the optional int value associated with an index. + * The defaultValue is returned if there is no value for the index, + * or if the value is not a number and cannot be converted to a number. + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default value. + * @return The value. + */ + public int optInt(int index, int defaultValue){ + try{ + return this.getInt(index); + }catch(Exception e){ + return defaultValue; + } + } + + /** + * Get the optional JSONArray associated with an index. + * @param index subscript + * @return A JSONArray value, or null if the index has no value, + * or if the value is not a JSONArray. + */ + public JSONArray optJSONArray(int index){ + Object o = this.opt(index); + return o instanceof JSONArray ? (JSONArray)o : null; + } + + /** + * Get the optional JSONObject associated with an index. + * Null is returned if the key is not found, or null if the index has + * no value, or if the value is not a JSONObject. + * + * @param index The index must be between 0 and length() - 1. + * @return A JSONObject value. + */ + public JSONObject optJSONObject(int index){ + Object o = this.opt(index); + return o instanceof JSONObject ? (JSONObject)o : null; + } + + /** + * Get the optional long value associated with an index. + * Zero is returned if there is no value for the index, + * or if the value is not a number and cannot be converted to a number. + * + * @param index The index must be between 0 and length() - 1. + * @return The value. + */ + public long optLong(int index){ + return this.optLong(index, 0); + } + + /** + * Get the optional long value associated with an index. + * The defaultValue is returned if there is no value for the index, + * or if the value is not a number and cannot be converted to a number. + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default value. + * @return The value. + */ + public long optLong(int index, long defaultValue){ + try{ + return this.getLong(index); + }catch(Exception e){ + return defaultValue; + } + } + + /** + * Get the optional string value associated with an index. It returns an + * empty string if there is no value at that index. If the value + * is not a string and is not null, then it is coverted to a string. + * + * @param index The index must be between 0 and length() - 1. + * @return A String value. + */ + public String optString(int index){ + return this.optString(index, ""); + } + + /** + * Get the optional string associated with an index. + * The defaultValue is returned if the key is not found. + * + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default value. + * @return A String value. + */ + public String optString(int index, String defaultValue){ + Object object = this.opt(index); + return JSONObject.NULL.equals(object) ? defaultValue : object.toString(); + } + + /** + * Append a boolean value. This increases the array's length by one. + * + * @param value A boolean value. + * @return this. + */ + public JSONArray put(boolean value){ + this.put(value ? Boolean.TRUE : Boolean.FALSE); + return this; + } + + /** + * Put a value in the JSONArray, where the value will be a + * JSONArray which is produced from a Collection. + * @param value A Collection value. + * @return this. + */ + public JSONArray put(Collection value){ + this.put(new JSONArray(value)); + return this; + } + + /** + * Append a double value. This increases the array's length by one. + * + * @param value A double value. + * @throws JSONException if the value is not finite. + * @return this. + */ + public JSONArray put(double value) throws JSONException{ + Double d = new Double(value); + JSONObject.testValidity(d); + this.put(d); + return this; + } + + /** + * Append an int value. This increases the array's length by one. + * + * @param value An int value. + * @return this. + */ + public JSONArray put(int value){ + this.put(new Integer(value)); + return this; + } + + /** + * Append an long value. This increases the array's length by one. + * + * @param value A long value. + * @return this. + */ + public JSONArray put(long value){ + this.put(new Long(value)); + return this; + } + + /** + * Put a value in the JSONArray, where the value will be a + * JSONObject which is produced from a Map. + * @param value A Map value. + * @return this. + */ + public JSONArray put(Map value){ + this.put(new JSONObject(value)); + return this; + } + + /** + * Append an object value. This increases the array's length by one. + * @param value An object value. The value should be a + * Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the + * JSONObject.NULL object. + * @return this. + */ + public JSONArray put(Object value){ + this.myArrayList.add(value); + return this; + } + + /** + * Put or replace a boolean value in the JSONArray. If the index is greater + * than the length of the JSONArray, then null elements will be added as + * necessary to pad it out. + * @param index The subscript. + * @param value A boolean value. + * @return this. + * @throws JSONException If the index is negative. + */ + public JSONArray put(int index, boolean value) throws JSONException{ + this.put(index, value ? Boolean.TRUE : Boolean.FALSE); + return this; + } + + /** + * Put a value in the JSONArray, where the value will be a + * JSONArray which is produced from a Collection. + * @param index The subscript. + * @param value A Collection value. + * @return this. + * @throws JSONException If the index is negative or if the value is + * not finite. + */ + public JSONArray put(int index, Collection value) throws JSONException{ + this.put(index, new JSONArray(value)); + return this; + } + + /** + * Put or replace a double value. If the index is greater than the length of + * the JSONArray, then null elements will be added as necessary to pad + * it out. + * @param index The subscript. + * @param value A double value. + * @return this. + * @throws JSONException If the index is negative or if the value is + * not finite. + */ + public JSONArray put(int index, double value) throws JSONException{ + this.put(index, new Double(value)); + return this; + } + + /** + * Put or replace an int value. If the index is greater than the length of + * the JSONArray, then null elements will be added as necessary to pad + * it out. + * @param index The subscript. + * @param value An int value. + * @return this. + * @throws JSONException If the index is negative. + */ + public JSONArray put(int index, int value) throws JSONException{ + this.put(index, new Integer(value)); + return this; + } + + /** + * Put or replace a long value. If the index is greater than the length of + * the JSONArray, then null elements will be added as necessary to pad + * it out. + * @param index The subscript. + * @param value A long value. + * @return this. + * @throws JSONException If the index is negative. + */ + public JSONArray put(int index, long value) throws JSONException{ + this.put(index, new Long(value)); + return this; + } + + /** + * Put a value in the JSONArray, where the value will be a + * JSONObject that is produced from a Map. + * @param index The subscript. + * @param value The Map value. + * @return this. + * @throws JSONException If the index is negative or if the the value is + * an invalid number. + */ + public JSONArray put(int index, Map value) throws JSONException{ + this.put(index, new JSONObject(value)); + return this; + } + + /** + * Put or replace an object value in the JSONArray. If the index is greater + * than the length of the JSONArray, then null elements will be added as + * necessary to pad it out. + * @param index The subscript. + * @param value The value to put into the array. The value should be a + * Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the + * JSONObject.NULL object. + * @return this. + * @throws JSONException If the index is negative or if the the value is + * an invalid number. + */ + public JSONArray put(int index, Object value) throws JSONException{ + JSONObject.testValidity(value); + if (index < 0){ + throw new JSONException("JSONArray[" + index + "] not found."); + } + if (index < this.length()){ + this.myArrayList.set(index, value); + }else{ + while(index != this.length()){ + this.put(JSONObject.NULL); + } + this.put(value); + } + return this; + } + + /** + * Remove an index and close the hole. + * @param index The index of the element to be removed. + * @return The value that was associated with the index, + * or null if there was no value. + */ + public Object remove(int index){ + Object o = this.opt(index); + this.myArrayList.remove(index); + return o; + } + + /** + * Produce a JSONObject by combining a JSONArray of names with the values + * of this JSONArray. + * @param names A JSONArray containing a list of key strings. These will be + * paired with the values. + * @return A JSONObject, or null if there are no names or if this JSONArray + * has no values. + * @throws JSONException If any of the names are null. + */ + public JSONObject toJSONObject(JSONArray names) throws JSONException{ + if (names == null || names.length() == 0 || this.length() == 0){ + return null; + } + JSONObject jo = new JSONObject(); + for(int i = 0; i < names.length(); i += 1){ + jo.put(names.getString(i), this.opt(i)); + } + return jo; + } + + /** + * Make a JSON text of this JSONArray. For compactness, no + * unnecessary whitespace is added. If it is not possible to produce a + * syntactically correct JSON text then null will be returned instead. This + * could occur if the array contains an invalid number. + * <p> + * Warning: This method assumes that the data structure is acyclical. + * + * @return a printable, displayable, transmittable + * representation of the array. + */ + public String toString(){ + try{ + return '[' + this.join(",") + ']'; + }catch(Exception e){ + return null; + } + } + + /** + * Make a prettyprinted JSON text of this JSONArray. + * Warning: This method assumes that the data structure is acyclical. + * @param indentFactor The number of spaces to add to each level of + * indentation. + * @return a printable, displayable, transmittable + * representation of the object, beginning + * with <code>[</code> <small>(left bracket)</small> and ending + * with <code>]</code> <small>(right bracket)</small>. + * @throws JSONException + */ + public String toString(int indentFactor) throws JSONException{ + StringWriter sw = new StringWriter(); + synchronized(sw.getBuffer()){ + return this.write(sw, indentFactor, 0).toString(); + } + } + + /** + * Write the contents of the JSONArray as JSON text to a writer. For + * compactness, no whitespace is added. + * <p> + * Warning: This method assumes that the data structure is acyclical. + * + * @return The writer. + * @throws JSONException + */ + public Writer write(Writer writer) throws JSONException{ + return this.write(writer, 0, 0); + } + + /** + * Write the contents of the JSONArray as JSON text to a writer. For + * compactness, no whitespace is added. + * <p> + * Warning: This method assumes that the data structure is acyclical. + * + * @param indentFactor + * The number of spaces to add to each level of indentation. + * @param indent + * The indention of the top level. + * @return The writer. + * @throws JSONException + */ + Writer write(Writer writer, int indentFactor, int indent) throws JSONException{ + try{ + boolean commanate = false; + int length = this.length(); + writer.write('['); + + if (length == 1){ + JSONObject.writeValue(writer, this.myArrayList.get(0), indentFactor, indent); + }else if (length != 0){ + final int newindent = indent + indentFactor; + + for(int i = 0; i < length; i += 1){ + if (commanate){ + writer.write(','); + } + if (indentFactor > 0){ + writer.write('\n'); + } + JSONObject.indent(writer, newindent); + JSONObject.writeValue(writer, this.myArrayList.get(i), indentFactor, newindent); + commanate = true; + } + if (indentFactor > 0){ + writer.write('\n'); + } + JSONObject.indent(writer, indent); + } + writer.write(']'); + return writer; + }catch(IOException e){ + throw new JSONException(e); + } + } } diff --git a/src/org/json/JSONException.java b/src/org/json/JSONException.java index 289b602e46e3db2fdc73675e67ca5e0112bf57df..be0bddfbd9e002d3e7e659ae3f09f9b2e74960de 100644 --- a/src/org/json/JSONException.java +++ b/src/org/json/JSONException.java @@ -6,23 +6,23 @@ package org.json; * @version 2010-12-24 */ public class JSONException extends Exception { - private static final long serialVersionUID = 0; - private Throwable cause; + private static final long serialVersionUID = 0; + private Throwable cause; - /** - * Constructs a JSONException with an explanatory message. - * @param message Detail about the reason for the exception. - */ - public JSONException(String message) { - super(message); - } + /** + * Constructs a JSONException with an explanatory message. + * @param message Detail about the reason for the exception. + */ + public JSONException(String message){ + super(message); + } - public JSONException(Throwable cause) { - super(cause.getMessage()); - this.cause = cause; - } + public JSONException(Throwable cause){ + super(cause.getMessage()); + this.cause = cause; + } - public Throwable getCause() { - return this.cause; - } + public Throwable getCause(){ + return this.cause; + } } diff --git a/src/org/json/JSONML.java b/src/org/json/JSONML.java index d29be7164455b1e4c899df1948c6813450318956..c4020157de1e188624e75d690857190681bd430c 100644 --- a/src/org/json/JSONML.java +++ b/src/org/json/JSONML.java @@ -26,7 +26,6 @@ SOFTWARE. import java.util.Iterator; - /** * This provides static methods to convert an XML text into a JSONArray or * JSONObject, and to covert a JSONArray or JSONObject into an XML text using @@ -36,430 +35,416 @@ import java.util.Iterator; */ public class JSONML { - /** - * Parse XML values and store them in a JSONArray. - * @param x The XMLTokener containing the source string. - * @param arrayForm true if array form, false if object form. - * @param ja The JSONArray that is containing the current tag or null - * if we are at the outermost level. - * @return A JSONArray if the value is the outermost tag, otherwise null. - * @throws JSONException - */ - private static Object parse( - XMLTokener x, - boolean arrayForm, - JSONArray ja - ) throws JSONException { - String attribute; - char c; - String closeTag = null; - int i; - JSONArray newja = null; - JSONObject newjo = null; - Object token; - String tagName = null; - -// Test for and skip past these forms: -// <!-- ... --> -// <![ ... ]]> -// <! ... > -// <? ... ?> - - while (true) { - if (!x.more()) { - throw x.syntaxError("Bad XML"); - } - token = x.nextContent(); - if (token == XML.LT) { - token = x.nextToken(); - if (token instanceof Character) { - if (token == XML.SLASH) { - -// Close tag </ - - token = x.nextToken(); - if (!(token instanceof String)) { - throw new JSONException( - "Expected a closing name instead of '" + - token + "'."); - } - if (x.nextToken() != XML.GT) { - throw x.syntaxError("Misshaped close tag"); - } - return token; - } else if (token == XML.BANG) { - -// <! - - c = x.next(); - if (c == '-') { - if (x.next() == '-') { - x.skipPast("-->"); - } - x.back(); - } else if (c == '[') { - token = x.nextToken(); - if (token.equals("CDATA") && x.next() == '[') { - if (ja != null) { - ja.put(x.nextCDATA()); - } - } else { - throw x.syntaxError("Expected 'CDATA['"); - } - } else { - i = 1; - do { - token = x.nextMeta(); - if (token == null) { - throw x.syntaxError("Missing '>' after '<!'."); - } else if (token == XML.LT) { - i += 1; - } else if (token == XML.GT) { - i -= 1; - } - } while (i > 0); - } - } else if (token == XML.QUEST) { - -// <? - - x.skipPast("?>"); - } else { - throw x.syntaxError("Misshaped tag"); - } - -// Open tag < - - } else { - if (!(token instanceof String)) { - throw x.syntaxError("Bad tagName '" + token + "'."); - } - tagName = (String)token; - newja = new JSONArray(); - newjo = new JSONObject(); - if (arrayForm) { - newja.put(tagName); - if (ja != null) { - ja.put(newja); - } - } else { - newjo.put("tagName", tagName); - if (ja != null) { - ja.put(newjo); - } - } - token = null; - for (;;) { - if (token == null) { - token = x.nextToken(); - } - if (token == null) { - throw x.syntaxError("Misshaped tag"); - } - if (!(token instanceof String)) { - break; - } - -// attribute = value - - attribute = (String)token; - if (!arrayForm && ("tagName".equals(attribute) || "childNode".equals(attribute))) { - throw x.syntaxError("Reserved attribute."); - } - token = x.nextToken(); - if (token == XML.EQ) { - token = x.nextToken(); - if (!(token instanceof String)) { - throw x.syntaxError("Missing value"); - } - newjo.accumulate(attribute, XML.stringToValue((String)token)); - token = null; - } else { - newjo.accumulate(attribute, ""); - } - } - if (arrayForm && newjo.length() > 0) { - newja.put(newjo); - } - -// Empty tag <.../> - - if (token == XML.SLASH) { - if (x.nextToken() != XML.GT) { - throw x.syntaxError("Misshaped tag"); - } - if (ja == null) { - if (arrayForm) { - return newja; - } else { - return newjo; - } - } - -// Content, between <...> and </...> - - } else { - if (token != XML.GT) { - throw x.syntaxError("Misshaped tag"); - } - closeTag = (String)parse(x, arrayForm, newja); - if (closeTag != null) { - if (!closeTag.equals(tagName)) { - throw x.syntaxError("Mismatched '" + tagName + - "' and '" + closeTag + "'"); - } - tagName = null; - if (!arrayForm && newja.length() > 0) { - newjo.put("childNodes", newja); - } - if (ja == null) { - if (arrayForm) { - return newja; - } else { - return newjo; - } - } - } - } - } - } else { - if (ja != null) { - ja.put(token instanceof String - ? XML.stringToValue((String)token) - : token); - } - } - } - } - - - /** - * Convert a well-formed (but not necessarily valid) XML string into a - * JSONArray using the JsonML transform. Each XML tag is represented as - * a JSONArray in which the first element is the tag name. If the tag has - * attributes, then the second element will be JSONObject containing the - * name/value pairs. If the tag contains children, then strings and - * JSONArrays will represent the child tags. - * Comments, prologs, DTDs, and <code><[ [ ]]></code> are ignored. - * @param string The source string. - * @return A JSONArray containing the structured data from the XML string. - * @throws JSONException - */ - public static JSONArray toJSONArray(String string) throws JSONException { - return toJSONArray(new XMLTokener(string)); - } - - - /** - * Convert a well-formed (but not necessarily valid) XML string into a - * JSONArray using the JsonML transform. Each XML tag is represented as - * a JSONArray in which the first element is the tag name. If the tag has - * attributes, then the second element will be JSONObject containing the - * name/value pairs. If the tag contains children, then strings and - * JSONArrays will represent the child content and tags. - * Comments, prologs, DTDs, and <code><[ [ ]]></code> are ignored. - * @param x An XMLTokener. - * @return A JSONArray containing the structured data from the XML string. - * @throws JSONException - */ - public static JSONArray toJSONArray(XMLTokener x) throws JSONException { - return (JSONArray)parse(x, true, null); - } - - - /** - * Convert a well-formed (but not necessarily valid) XML string into a - * JSONObject using the JsonML transform. Each XML tag is represented as - * a JSONObject with a "tagName" property. If the tag has attributes, then - * the attributes will be in the JSONObject as properties. If the tag - * contains children, the object will have a "childNodes" property which - * will be an array of strings and JsonML JSONObjects. - - * Comments, prologs, DTDs, and <code><[ [ ]]></code> are ignored. - * @param x An XMLTokener of the XML source text. - * @return A JSONObject containing the structured data from the XML string. - * @throws JSONException - */ - public static JSONObject toJSONObject(XMLTokener x) throws JSONException { - return (JSONObject)parse(x, false, null); - } - - - /** - * Convert a well-formed (but not necessarily valid) XML string into a - * JSONObject using the JsonML transform. Each XML tag is represented as - * a JSONObject with a "tagName" property. If the tag has attributes, then - * the attributes will be in the JSONObject as properties. If the tag - * contains children, the object will have a "childNodes" property which - * will be an array of strings and JsonML JSONObjects. - - * Comments, prologs, DTDs, and <code><[ [ ]]></code> are ignored. - * @param string The XML source text. - * @return A JSONObject containing the structured data from the XML string. - * @throws JSONException - */ - public static JSONObject toJSONObject(String string) throws JSONException { - return toJSONObject(new XMLTokener(string)); - } - - - /** - * Reverse the JSONML transformation, making an XML text from a JSONArray. - * @param ja A JSONArray. - * @return An XML string. - * @throws JSONException - */ - public static String toString(JSONArray ja) throws JSONException { - int i; - JSONObject jo; - String key; - Iterator keys; - int length; - Object object; - StringBuffer sb = new StringBuffer(); - String tagName; - String value; - -// Emit <tagName - - tagName = ja.getString(0); - XML.noSpace(tagName); - tagName = XML.escape(tagName); - sb.append('<'); - sb.append(tagName); - - object = ja.opt(1); - if (object instanceof JSONObject) { - i = 2; - jo = (JSONObject)object; - -// Emit the attributes - - keys = jo.keys(); - while (keys.hasNext()) { - key = keys.next().toString(); - XML.noSpace(key); - value = jo.optString(key); - if (value != null) { - sb.append(' '); - sb.append(XML.escape(key)); - sb.append('='); - sb.append('"'); - sb.append(XML.escape(value)); - sb.append('"'); - } - } - } else { - i = 1; - } - -//Emit content in body - - length = ja.length(); - if (i >= length) { - sb.append('/'); - sb.append('>'); - } else { - sb.append('>'); - do { - object = ja.get(i); - i += 1; - if (object != null) { - if (object instanceof String) { - sb.append(XML.escape(object.toString())); - } else if (object instanceof JSONObject) { - sb.append(toString((JSONObject)object)); - } else if (object instanceof JSONArray) { - sb.append(toString((JSONArray)object)); - } - } - } while (i < length); - sb.append('<'); - sb.append('/'); - sb.append(tagName); - sb.append('>'); - } - return sb.toString(); - } - - /** - * Reverse the JSONML transformation, making an XML text from a JSONObject. - * The JSONObject must contain a "tagName" property. If it has children, - * then it must have a "childNodes" property containing an array of objects. - * The other properties are attributes with string values. - * @param jo A JSONObject. - * @return An XML string. - * @throws JSONException - */ - public static String toString(JSONObject jo) throws JSONException { - StringBuffer sb = new StringBuffer(); - int i; - JSONArray ja; - String key; - Iterator keys; - int length; - Object object; - String tagName; - String value; - -//Emit <tagName - - tagName = jo.optString("tagName"); - if (tagName == null) { - return XML.escape(jo.toString()); - } - XML.noSpace(tagName); - tagName = XML.escape(tagName); - sb.append('<'); - sb.append(tagName); - -//Emit the attributes - - keys = jo.keys(); - while (keys.hasNext()) { - key = keys.next().toString(); - if (!"tagName".equals(key) && !"childNodes".equals(key)) { - XML.noSpace(key); - value = jo.optString(key); - if (value != null) { - sb.append(' '); - sb.append(XML.escape(key)); - sb.append('='); - sb.append('"'); - sb.append(XML.escape(value)); - sb.append('"'); - } - } - } - -//Emit content in body - - ja = jo.optJSONArray("childNodes"); - if (ja == null) { - sb.append('/'); - sb.append('>'); - } else { - sb.append('>'); - length = ja.length(); - for (i = 0; i < length; i += 1) { - object = ja.get(i); - if (object != null) { - if (object instanceof String) { - sb.append(XML.escape(object.toString())); - } else if (object instanceof JSONObject) { - sb.append(toString((JSONObject)object)); - } else if (object instanceof JSONArray) { - sb.append(toString((JSONArray)object)); - } else { - sb.append(object.toString()); - } - } - } - sb.append('<'); - sb.append('/'); - sb.append(tagName); - sb.append('>'); - } - return sb.toString(); - } + /** + * Parse XML values and store them in a JSONArray. + * @param x The XMLTokener containing the source string. + * @param arrayForm true if array form, false if object form. + * @param ja The JSONArray that is containing the current tag or null + * if we are at the outermost level. + * @return A JSONArray if the value is the outermost tag, otherwise null. + * @throws JSONException + */ + private static Object parse(XMLTokener x, boolean arrayForm, JSONArray ja) throws JSONException{ + String attribute; + char c; + String closeTag = null; + int i; + JSONArray newja = null; + JSONObject newjo = null; + Object token; + String tagName = null; + + // Test for and skip past these forms: + // <!-- ... --> + // <![ ... ]]> + // <! ... > + // <? ... ?> + + while(true){ + if (!x.more()){ + throw x.syntaxError("Bad XML"); + } + token = x.nextContent(); + if (token == XML.LT){ + token = x.nextToken(); + if (token instanceof Character){ + if (token == XML.SLASH){ + + // Close tag </ + + token = x.nextToken(); + if (!(token instanceof String)){ + throw new JSONException("Expected a closing name instead of '" + token + "'."); + } + if (x.nextToken() != XML.GT){ + throw x.syntaxError("Misshaped close tag"); + } + return token; + }else if (token == XML.BANG){ + + // <! + + c = x.next(); + if (c == '-'){ + if (x.next() == '-'){ + x.skipPast("-->"); + } + x.back(); + }else if (c == '['){ + token = x.nextToken(); + if (token.equals("CDATA") && x.next() == '['){ + if (ja != null){ + ja.put(x.nextCDATA()); + } + }else{ + throw x.syntaxError("Expected 'CDATA['"); + } + }else{ + i = 1; + do{ + token = x.nextMeta(); + if (token == null){ + throw x.syntaxError("Missing '>' after '<!'."); + }else if (token == XML.LT){ + i += 1; + }else if (token == XML.GT){ + i -= 1; + } + }while(i > 0); + } + }else if (token == XML.QUEST){ + + // <? + + x.skipPast("?>"); + }else{ + throw x.syntaxError("Misshaped tag"); + } + + // Open tag < + + }else{ + if (!(token instanceof String)){ + throw x.syntaxError("Bad tagName '" + token + "'."); + } + tagName = (String)token; + newja = new JSONArray(); + newjo = new JSONObject(); + if (arrayForm){ + newja.put(tagName); + if (ja != null){ + ja.put(newja); + } + }else{ + newjo.put("tagName", tagName); + if (ja != null){ + ja.put(newjo); + } + } + token = null; + for(;;){ + if (token == null){ + token = x.nextToken(); + } + if (token == null){ + throw x.syntaxError("Misshaped tag"); + } + if (!(token instanceof String)){ + break; + } + + // attribute = value + + attribute = (String)token; + if (!arrayForm && ("tagName".equals(attribute) || "childNode".equals(attribute))){ + throw x.syntaxError("Reserved attribute."); + } + token = x.nextToken(); + if (token == XML.EQ){ + token = x.nextToken(); + if (!(token instanceof String)){ + throw x.syntaxError("Missing value"); + } + newjo.accumulate(attribute, XML.stringToValue((String)token)); + token = null; + }else{ + newjo.accumulate(attribute, ""); + } + } + if (arrayForm && newjo.length() > 0){ + newja.put(newjo); + } + + // Empty tag <.../> + + if (token == XML.SLASH){ + if (x.nextToken() != XML.GT){ + throw x.syntaxError("Misshaped tag"); + } + if (ja == null){ + if (arrayForm){ + return newja; + }else{ + return newjo; + } + } + + // Content, between <...> and </...> + + }else{ + if (token != XML.GT){ + throw x.syntaxError("Misshaped tag"); + } + closeTag = (String)parse(x, arrayForm, newja); + if (closeTag != null){ + if (!closeTag.equals(tagName)){ + throw x.syntaxError("Mismatched '" + tagName + "' and '" + closeTag + "'"); + } + tagName = null; + if (!arrayForm && newja.length() > 0){ + newjo.put("childNodes", newja); + } + if (ja == null){ + if (arrayForm){ + return newja; + }else{ + return newjo; + } + } + } + } + } + }else{ + if (ja != null){ + ja.put(token instanceof String ? XML.stringToValue((String)token) : token); + } + } + } + } + + /** + * Convert a well-formed (but not necessarily valid) XML string into a + * JSONArray using the JsonML transform. Each XML tag is represented as + * a JSONArray in which the first element is the tag name. If the tag has + * attributes, then the second element will be JSONObject containing the + * name/value pairs. If the tag contains children, then strings and + * JSONArrays will represent the child tags. + * Comments, prologs, DTDs, and <code><[ [ ]]></code> are ignored. + * @param string The source string. + * @return A JSONArray containing the structured data from the XML string. + * @throws JSONException + */ + public static JSONArray toJSONArray(String string) throws JSONException{ + return toJSONArray(new XMLTokener(string)); + } + + /** + * Convert a well-formed (but not necessarily valid) XML string into a + * JSONArray using the JsonML transform. Each XML tag is represented as + * a JSONArray in which the first element is the tag name. If the tag has + * attributes, then the second element will be JSONObject containing the + * name/value pairs. If the tag contains children, then strings and + * JSONArrays will represent the child content and tags. + * Comments, prologs, DTDs, and <code><[ [ ]]></code> are ignored. + * @param x An XMLTokener. + * @return A JSONArray containing the structured data from the XML string. + * @throws JSONException + */ + public static JSONArray toJSONArray(XMLTokener x) throws JSONException{ + return (JSONArray)parse(x, true, null); + } + + /** + * Convert a well-formed (but not necessarily valid) XML string into a + * JSONObject using the JsonML transform. Each XML tag is represented as + * a JSONObject with a "tagName" property. If the tag has attributes, then + * the attributes will be in the JSONObject as properties. If the tag + * contains children, the object will have a "childNodes" property which + * will be an array of strings and JsonML JSONObjects. + + * Comments, prologs, DTDs, and <code><[ [ ]]></code> are ignored. + * @param x An XMLTokener of the XML source text. + * @return A JSONObject containing the structured data from the XML string. + * @throws JSONException + */ + public static JSONObject toJSONObject(XMLTokener x) throws JSONException{ + return (JSONObject)parse(x, false, null); + } + + /** + * Convert a well-formed (but not necessarily valid) XML string into a + * JSONObject using the JsonML transform. Each XML tag is represented as + * a JSONObject with a "tagName" property. If the tag has attributes, then + * the attributes will be in the JSONObject as properties. If the tag + * contains children, the object will have a "childNodes" property which + * will be an array of strings and JsonML JSONObjects. + + * Comments, prologs, DTDs, and <code><[ [ ]]></code> are ignored. + * @param string The XML source text. + * @return A JSONObject containing the structured data from the XML string. + * @throws JSONException + */ + public static JSONObject toJSONObject(String string) throws JSONException{ + return toJSONObject(new XMLTokener(string)); + } + + /** + * Reverse the JSONML transformation, making an XML text from a JSONArray. + * @param ja A JSONArray. + * @return An XML string. + * @throws JSONException + */ + public static String toString(JSONArray ja) throws JSONException{ + int i; + JSONObject jo; + String key; + Iterator keys; + int length; + Object object; + StringBuffer sb = new StringBuffer(); + String tagName; + String value; + + // Emit <tagName + + tagName = ja.getString(0); + XML.noSpace(tagName); + tagName = XML.escape(tagName); + sb.append('<'); + sb.append(tagName); + + object = ja.opt(1); + if (object instanceof JSONObject){ + i = 2; + jo = (JSONObject)object; + + // Emit the attributes + + keys = jo.keys(); + while(keys.hasNext()){ + key = keys.next().toString(); + XML.noSpace(key); + value = jo.optString(key); + if (value != null){ + sb.append(' '); + sb.append(XML.escape(key)); + sb.append('='); + sb.append('"'); + sb.append(XML.escape(value)); + sb.append('"'); + } + } + }else{ + i = 1; + } + + //Emit content in body + + length = ja.length(); + if (i >= length){ + sb.append('/'); + sb.append('>'); + }else{ + sb.append('>'); + do{ + object = ja.get(i); + i += 1; + if (object != null){ + if (object instanceof String){ + sb.append(XML.escape(object.toString())); + }else if (object instanceof JSONObject){ + sb.append(toString((JSONObject)object)); + }else if (object instanceof JSONArray){ + sb.append(toString((JSONArray)object)); + } + } + }while(i < length); + sb.append('<'); + sb.append('/'); + sb.append(tagName); + sb.append('>'); + } + return sb.toString(); + } + + /** + * Reverse the JSONML transformation, making an XML text from a JSONObject. + * The JSONObject must contain a "tagName" property. If it has children, + * then it must have a "childNodes" property containing an array of objects. + * The other properties are attributes with string values. + * @param jo A JSONObject. + * @return An XML string. + * @throws JSONException + */ + public static String toString(JSONObject jo) throws JSONException{ + StringBuffer sb = new StringBuffer(); + int i; + JSONArray ja; + String key; + Iterator keys; + int length; + Object object; + String tagName; + String value; + + //Emit <tagName + + tagName = jo.optString("tagName"); + if (tagName == null){ + return XML.escape(jo.toString()); + } + XML.noSpace(tagName); + tagName = XML.escape(tagName); + sb.append('<'); + sb.append(tagName); + + //Emit the attributes + + keys = jo.keys(); + while(keys.hasNext()){ + key = keys.next().toString(); + if (!"tagName".equals(key) && !"childNodes".equals(key)){ + XML.noSpace(key); + value = jo.optString(key); + if (value != null){ + sb.append(' '); + sb.append(XML.escape(key)); + sb.append('='); + sb.append('"'); + sb.append(XML.escape(value)); + sb.append('"'); + } + } + } + + //Emit content in body + + ja = jo.optJSONArray("childNodes"); + if (ja == null){ + sb.append('/'); + sb.append('>'); + }else{ + sb.append('>'); + length = ja.length(); + for(i = 0; i < length; i += 1){ + object = ja.get(i); + if (object != null){ + if (object instanceof String){ + sb.append(XML.escape(object.toString())); + }else if (object instanceof JSONObject){ + sb.append(toString((JSONObject)object)); + }else if (object instanceof JSONArray){ + sb.append(toString((JSONArray)object)); + }else{ + sb.append(object.toString()); + } + } + } + sb.append('<'); + sb.append('/'); + sb.append(tagName); + sb.append('>'); + } + return sb.toString(); + } } diff --git a/src/org/json/JSONObject.java b/src/org/json/JSONObject.java index 5b05255dc98ef6790ca3bc0fccfc1c3285763166..91028c0cd371abff05e651b81796e52ad00dc065 100644 --- a/src/org/json/JSONObject.java +++ b/src/org/json/JSONObject.java @@ -94,1500 +94,1383 @@ import java.util.ResourceBundle; */ public class JSONObject { - /** - * JSONObject.NULL is equivalent to the value that JavaScript calls null, - * whilst Java's null is equivalent to the value that JavaScript calls - * undefined. - */ - private static final class Null { - - /** - * There is only intended to be a single instance of the NULL object, - * so the clone method returns itself. - * @return NULL. - */ - protected final Object clone() { - return this; - } - - /** - * A Null object is equal to the null value and to itself. - * @param object An object to test for nullness. - * @return true if the object parameter is the JSONObject.NULL object - * or null. - */ - public boolean equals(Object object) { - return object == null || object == this; - } - - /** - * Get the "null" string value. - * @return The string "null". - */ - public String toString() { - return "null"; - } - } - - - /** - * The map where the JSONObject's properties are kept. - */ - private final Map map; - - - /** - * It is sometimes more convenient and less ambiguous to have a - * <code>NULL</code> object than to use Java's <code>null</code> value. - * <code>JSONObject.NULL.equals(null)</code> returns <code>true</code>. - * <code>JSONObject.NULL.toString()</code> returns <code>"null"</code>. - */ - public static final Object NULL = new Null(); - - - /** - * Construct an empty JSONObject. - */ - public JSONObject() { - this.map = new HashMap(); - } - - - /** - * Construct a JSONObject from a subset of another JSONObject. - * An array of strings is used to identify the keys that should be copied. - * Missing keys are ignored. - * @param jo A JSONObject. - * @param names An array of strings. - * @throws JSONException - * @exception JSONException If a value is a non-finite number or if a name is duplicated. - */ - public JSONObject(JSONObject jo, String[] names) { - this(); - for (int i = 0; i < names.length; i += 1) { - try { - this.putOnce(names[i], jo.opt(names[i])); - } catch (Exception ignore) { - } - } - } - - - /** - * Construct a JSONObject from a JSONTokener. - * @param x A JSONTokener object containing the source string. - * @throws JSONException If there is a syntax error in the source string - * or a duplicated key. - */ - public JSONObject(JSONTokener x) throws JSONException { - this(); - char c; - String key; - - if (x.nextClean() != '{') { - throw x.syntaxError("A JSONObject text must begin with '{'"); - } - for (;;) { - c = x.nextClean(); - switch (c) { - case 0: - throw x.syntaxError("A JSONObject text must end with '}'"); - case '}': - return; - default: - x.back(); - key = x.nextValue().toString(); - } - -// The key is followed by ':'. We will also tolerate '=' or '=>'. - - c = x.nextClean(); - if (c == '=') { - if (x.next() != '>') { - x.back(); - } - } else if (c != ':') { - throw x.syntaxError("Expected a ':' after a key"); - } - this.putOnce(key, x.nextValue()); - -// Pairs are separated by ','. We will also tolerate ';'. - - switch (x.nextClean()) { - case ';': - case ',': - if (x.nextClean() == '}') { - return; - } - x.back(); - break; - case '}': - return; - default: - throw x.syntaxError("Expected a ',' or '}'"); - } - } - } - - - /** - * Construct a JSONObject from a Map. - * - * @param map A map object that can be used to initialize the contents of - * the JSONObject. - * @throws JSONException - */ - public JSONObject(Map map) { - this.map = new HashMap(); - if (map != null) { - Iterator i = map.entrySet().iterator(); - while (i.hasNext()) { - Map.Entry e = (Map.Entry)i.next(); - Object value = e.getValue(); - if (value != null) { - this.map.put(e.getKey(), wrap(value)); - } - } - } - } - - - /** - * Construct a JSONObject from an Object using bean getters. - * It reflects on all of the public methods of the object. - * For each of the methods with no parameters and a name starting - * with <code>"get"</code> or <code>"is"</code> followed by an uppercase letter, - * the method is invoked, and a key and the value returned from the getter method - * are put into the new JSONObject. - * - * The key is formed by removing the <code>"get"</code> or <code>"is"</code> prefix. - * If the second remaining character is not upper case, then the first - * character is converted to lower case. - * - * For example, if an object has a method named <code>"getName"</code>, and - * if the result of calling <code>object.getName()</code> is <code>"Larry Fine"</code>, - * then the JSONObject will contain <code>"name": "Larry Fine"</code>. - * - * @param bean An object that has getter methods that should be used - * to make a JSONObject. - */ - public JSONObject(Object bean) { - this(); - this.populateMap(bean); - } - - - /** - * Construct a JSONObject from an Object, using reflection to find the - * public members. The resulting JSONObject's keys will be the strings - * from the names array, and the values will be the field values associated - * with those keys in the object. If a key is not found or not visible, - * then it will not be copied into the new JSONObject. - * @param object An object that has fields that should be used to make a - * JSONObject. - * @param names An array of strings, the names of the fields to be obtained - * from the object. - */ - public JSONObject(Object object, String names[]) { - this(); - Class c = object.getClass(); - for (int i = 0; i < names.length; i += 1) { - String name = names[i]; - try { - this.putOpt(name, c.getField(name).get(object)); - } catch (Exception ignore) { - } - } - } - - - /** - * Construct a JSONObject from a source JSON text string. - * This is the most commonly used JSONObject constructor. - * @param source A string beginning - * with <code>{</code> <small>(left brace)</small> and ending - * with <code>}</code> <small>(right brace)</small>. - * @exception JSONException If there is a syntax error in the source - * string or a duplicated key. - */ - public JSONObject(String source) throws JSONException { - this(new JSONTokener(source)); - } - - - /** - * Construct a JSONObject from a ResourceBundle. - * @param baseName The ResourceBundle base name. - * @param locale The Locale to load the ResourceBundle for. - * @throws JSONException If any JSONExceptions are detected. - */ - public JSONObject(String baseName, Locale locale) throws JSONException { - this(); - ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, - Thread.currentThread().getContextClassLoader()); - -// Iterate through the keys in the bundle. - - Enumeration keys = bundle.getKeys(); - while (keys.hasMoreElements()) { - Object key = keys.nextElement(); - if (key instanceof String) { - -// Go through the path, ensuring that there is a nested JSONObject for each -// segment except the last. Add the value using the last segment's name into -// the deepest nested JSONObject. - - String[] path = ((String)key).split("\\."); - int last = path.length - 1; - JSONObject target = this; - for (int i = 0; i < last; i += 1) { - String segment = path[i]; - JSONObject nextTarget = target.optJSONObject(segment); - if (nextTarget == null) { - nextTarget = new JSONObject(); - target.put(segment, nextTarget); - } - target = nextTarget; - } - target.put(path[last], bundle.getString((String)key)); - } - } - } - - - /** - * Accumulate values under a key. It is similar to the put method except - * that if there is already an object stored under the key then a - * JSONArray is stored under the key to hold all of the accumulated values. - * If there is already a JSONArray, then the new value is appended to it. - * In contrast, the put method replaces the previous value. - * - * If only one value is accumulated that is not a JSONArray, then the - * result will be the same as using put. But if multiple values are - * accumulated, then the result will be like append. - * @param key A key string. - * @param value An object to be accumulated under the key. - * @return this. - * @throws JSONException If the value is an invalid number - * or if the key is null. - */ - public JSONObject accumulate( - String key, - Object value - ) throws JSONException { - testValidity(value); - Object object = this.opt(key); - if (object == null) { - this.put(key, value instanceof JSONArray - ? new JSONArray().put(value) - : value); - } else if (object instanceof JSONArray) { - ((JSONArray)object).put(value); - } else { - this.put(key, new JSONArray().put(object).put(value)); - } - return this; - } - - - /** - * Append values to the array under a key. If the key does not exist in the - * JSONObject, then the key is put in the JSONObject with its value being a - * JSONArray containing the value parameter. If the key was already - * associated with a JSONArray, then the value parameter is appended to it. - * @param key A key string. - * @param value An object to be accumulated under the key. - * @return this. - * @throws JSONException If the key is null or if the current value - * associated with the key is not a JSONArray. - */ - public JSONObject append(String key, Object value) throws JSONException { - testValidity(value); - Object object = this.opt(key); - if (object == null) { - this.put(key, new JSONArray().put(value)); - } else if (object instanceof JSONArray) { - this.put(key, ((JSONArray)object).put(value)); - } else { - throw new JSONException("JSONObject[" + key + - "] is not a JSONArray."); - } - return this; - } - - - /** - * Produce a string from a double. The string "null" will be returned if - * the number is not finite. - * @param d A double. - * @return A String. - */ - public static String doubleToString(double d) { - if (Double.isInfinite(d) || Double.isNaN(d)) { - return "null"; - } - -// Shave off trailing zeros and decimal point, if possible. - - String string = Double.toString(d); - if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && - string.indexOf('E') < 0) { - while (string.endsWith("0")) { - string = string.substring(0, string.length() - 1); - } - if (string.endsWith(".")) { - string = string.substring(0, string.length() - 1); - } - } - return string; - } - - - /** - * Get the value object associated with a key. - * - * @param key A key string. - * @return The object associated with the key. - * @throws JSONException if the key is not found. - */ - public Object get(String key) throws JSONException { - if (key == null) { - throw new JSONException("Null key."); - } - Object object = this.opt(key); - if (object == null) { - throw new JSONException("JSONObject[" + quote(key) + - "] not found."); - } - return object; - } - - - /** - * Get the boolean value associated with a key. - * - * @param key A key string. - * @return The truth. - * @throws JSONException - * if the value is not a Boolean or the String "true" or "false". - */ - public boolean getBoolean(String key) throws JSONException { - Object object = this.get(key); - if (object.equals(Boolean.FALSE) || - (object instanceof String && - ((String)object).equalsIgnoreCase("false"))) { - return false; - } else if (object.equals(Boolean.TRUE) || - (object instanceof String && - ((String)object).equalsIgnoreCase("true"))) { - return true; - } - throw new JSONException("JSONObject[" + quote(key) + - "] is not a Boolean."); - } - - - /** - * Get the double value associated with a key. - * @param key A key string. - * @return The numeric value. - * @throws JSONException if the key is not found or - * if the value is not a Number object and cannot be converted to a number. - */ - public double getDouble(String key) throws JSONException { - Object object = this.get(key); - try { - return object instanceof Number - ? ((Number)object).doubleValue() - : Double.parseDouble((String)object); - } catch (Exception e) { - throw new JSONException("JSONObject[" + quote(key) + - "] is not a number."); - } - } - - - /** - * Get the int value associated with a key. - * - * @param key A key string. - * @return The integer value. - * @throws JSONException if the key is not found or if the value cannot - * be converted to an integer. - */ - public int getInt(String key) throws JSONException { - Object object = this.get(key); - try { - return object instanceof Number - ? ((Number)object).intValue() - : Integer.parseInt((String)object); - } catch (Exception e) { - throw new JSONException("JSONObject[" + quote(key) + - "] is not an int."); - } - } - - - /** - * Get the JSONArray value associated with a key. - * - * @param key A key string. - * @return A JSONArray which is the value. - * @throws JSONException if the key is not found or - * if the value is not a JSONArray. - */ - public JSONArray getJSONArray(String key) throws JSONException { - Object object = this.get(key); - if (object instanceof JSONArray) { - return (JSONArray)object; - } - throw new JSONException("JSONObject[" + quote(key) + - "] is not a JSONArray."); - } - - - /** - * Get the JSONObject value associated with a key. - * - * @param key A key string. - * @return A JSONObject which is the value. - * @throws JSONException if the key is not found or - * if the value is not a JSONObject. - */ - public JSONObject getJSONObject(String key) throws JSONException { - Object object = this.get(key); - if (object instanceof JSONObject) { - return (JSONObject)object; - } - throw new JSONException("JSONObject[" + quote(key) + - "] is not a JSONObject."); - } - - - /** - * Get the long value associated with a key. - * - * @param key A key string. - * @return The long value. - * @throws JSONException if the key is not found or if the value cannot - * be converted to a long. - */ - public long getLong(String key) throws JSONException { - Object object = this.get(key); - try { - return object instanceof Number - ? ((Number)object).longValue() - : Long.parseLong((String)object); - } catch (Exception e) { - throw new JSONException("JSONObject[" + quote(key) + - "] is not a long."); - } - } - - - /** - * Get an array of field names from a JSONObject. - * - * @return An array of field names, or null if there are no names. - */ - public static String[] getNames(JSONObject jo) { - int length = jo.length(); - if (length == 0) { - return null; - } - Iterator iterator = jo.keys(); - String[] names = new String[length]; - int i = 0; - while (iterator.hasNext()) { - names[i] = (String)iterator.next(); - i += 1; - } - return names; - } - - - /** - * Get an array of field names from an Object. - * - * @return An array of field names, or null if there are no names. - */ - public static String[] getNames(Object object) { - if (object == null) { - return null; - } - Class klass = object.getClass(); - Field[] fields = klass.getFields(); - int length = fields.length; - if (length == 0) { - return null; - } - String[] names = new String[length]; - for (int i = 0; i < length; i += 1) { - names[i] = fields[i].getName(); - } - return names; - } - - - /** - * Get the string associated with a key. - * - * @param key A key string. - * @return A string which is the value. - * @throws JSONException if there is no string value for the key. - */ - public String getString(String key) throws JSONException { - Object object = this.get(key); - if (object instanceof String) { - return (String)object; - } - throw new JSONException("JSONObject[" + quote(key) + - "] not a string."); - } - - - /** - * Determine if the JSONObject contains a specific key. - * @param key A key string. - * @return true if the key exists in the JSONObject. - */ - public boolean has(String key) { - return this.map.containsKey(key); - } - - - /** - * Increment a property of a JSONObject. If there is no such property, - * create one with a value of 1. If there is such a property, and if - * it is an Integer, Long, Double, or Float, then add one to it. - * @param key A key string. - * @return this. - * @throws JSONException If there is already a property with this name - * that is not an Integer, Long, Double, or Float. - */ - public JSONObject increment(String key) throws JSONException { - Object value = this.opt(key); - if (value == null) { - this.put(key, 1); - } else if (value instanceof Integer) { - this.put(key, ((Integer)value).intValue() + 1); - } else if (value instanceof Long) { - this.put(key, ((Long)value).longValue() + 1); - } else if (value instanceof Double) { - this.put(key, ((Double)value).doubleValue() + 1); - } else if (value instanceof Float) { - this.put(key, ((Float)value).floatValue() + 1); - } else { - throw new JSONException("Unable to increment [" + quote(key) + "]."); - } - return this; - } - - - /** - * Determine if the value associated with the key is null or if there is - * no value. - * @param key A key string. - * @return true if there is no value associated with the key or if - * the value is the JSONObject.NULL object. - */ - public boolean isNull(String key) { - return JSONObject.NULL.equals(this.opt(key)); - } - - - /** - * Get an enumeration of the keys of the JSONObject. - * - * @return An iterator of the keys. - */ - public Iterator keys() { - return this.map.keySet().iterator(); - } - - - /** - * Get the number of keys stored in the JSONObject. - * - * @return The number of keys in the JSONObject. - */ - public int length() { - return this.map.size(); - } - - - /** - * Produce a JSONArray containing the names of the elements of this - * JSONObject. - * @return A JSONArray containing the key strings, or null if the JSONObject - * is empty. - */ - public JSONArray names() { - JSONArray ja = new JSONArray(); - Iterator keys = this.keys(); - while (keys.hasNext()) { - ja.put(keys.next()); - } - return ja.length() == 0 ? null : ja; - } - - /** - * Produce a string from a Number. - * @param number A Number - * @return A String. - * @throws JSONException If n is a non-finite number. - */ - public static String numberToString(Number number) - throws JSONException { - if (number == null) { - throw new JSONException("Null pointer"); - } - testValidity(number); - -// Shave off trailing zeros and decimal point, if possible. - - String string = number.toString(); - if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && - string.indexOf('E') < 0) { - while (string.endsWith("0")) { - string = string.substring(0, string.length() - 1); - } - if (string.endsWith(".")) { - string = string.substring(0, string.length() - 1); - } - } - return string; - } - - - /** - * Get an optional value associated with a key. - * @param key A key string. - * @return An object which is the value, or null if there is no value. - */ - public Object opt(String key) { - return key == null ? null : this.map.get(key); - } - - - /** - * Get an optional boolean associated with a key. - * It returns false if there is no such key, or if the value is not - * Boolean.TRUE or the String "true". - * - * @param key A key string. - * @return The truth. - */ - public boolean optBoolean(String key) { - return this.optBoolean(key, false); - } - - - /** - * Get an optional boolean associated with a key. - * It returns the defaultValue if there is no such key, or if it is not - * a Boolean or the String "true" or "false" (case insensitive). - * - * @param key A key string. - * @param defaultValue The default. - * @return The truth. - */ - public boolean optBoolean(String key, boolean defaultValue) { - try { - return this.getBoolean(key); - } catch (Exception e) { - return defaultValue; - } - } - - - /** - * Get an optional double associated with a key, - * or NaN if there is no such key or if its value is not a number. - * If the value is a string, an attempt will be made to evaluate it as - * a number. - * - * @param key A string which is the key. - * @return An object which is the value. - */ - public double optDouble(String key) { - return this.optDouble(key, Double.NaN); - } - - - /** - * Get an optional double associated with a key, or the - * defaultValue if there is no such key or if its value is not a number. - * If the value is a string, an attempt will be made to evaluate it as - * a number. - * - * @param key A key string. - * @param defaultValue The default. - * @return An object which is the value. - */ - public double optDouble(String key, double defaultValue) { - try { - return this.getDouble(key); - } catch (Exception e) { - return defaultValue; - } - } - - - /** - * Get an optional int value associated with a key, - * or zero if there is no such key or if the value is not a number. - * If the value is a string, an attempt will be made to evaluate it as - * a number. - * - * @param key A key string. - * @return An object which is the value. - */ - public int optInt(String key) { - return this.optInt(key, 0); - } - - - /** - * Get an optional int value associated with a key, - * or the default if there is no such key or if the value is not a number. - * If the value is a string, an attempt will be made to evaluate it as - * a number. - * - * @param key A key string. - * @param defaultValue The default. - * @return An object which is the value. - */ - public int optInt(String key, int defaultValue) { - try { - return this.getInt(key); - } catch (Exception e) { - return defaultValue; - } - } - - - /** - * Get an optional JSONArray associated with a key. - * It returns null if there is no such key, or if its value is not a - * JSONArray. - * - * @param key A key string. - * @return A JSONArray which is the value. - */ - public JSONArray optJSONArray(String key) { - Object o = this.opt(key); - return o instanceof JSONArray ? (JSONArray)o : null; - } - - - /** - * Get an optional JSONObject associated with a key. - * It returns null if there is no such key, or if its value is not a - * JSONObject. - * - * @param key A key string. - * @return A JSONObject which is the value. - */ - public JSONObject optJSONObject(String key) { - Object object = this.opt(key); - return object instanceof JSONObject ? (JSONObject)object : null; - } - - - /** - * Get an optional long value associated with a key, - * or zero if there is no such key or if the value is not a number. - * If the value is a string, an attempt will be made to evaluate it as - * a number. - * - * @param key A key string. - * @return An object which is the value. - */ - public long optLong(String key) { - return this.optLong(key, 0); - } - - - /** - * Get an optional long value associated with a key, - * or the default if there is no such key or if the value is not a number. - * If the value is a string, an attempt will be made to evaluate it as - * a number. - * - * @param key A key string. - * @param defaultValue The default. - * @return An object which is the value. - */ - public long optLong(String key, long defaultValue) { - try { - return this.getLong(key); - } catch (Exception e) { - return defaultValue; - } - } - - - /** - * Get an optional string associated with a key. - * It returns an empty string if there is no such key. If the value is not - * a string and is not null, then it is converted to a string. - * - * @param key A key string. - * @return A string which is the value. - */ - public String optString(String key) { - return this.optString(key, ""); - } - - - /** - * Get an optional string associated with a key. - * It returns the defaultValue if there is no such key. - * - * @param key A key string. - * @param defaultValue The default. - * @return A string which is the value. - */ - public String optString(String key, String defaultValue) { - Object object = this.opt(key); - return NULL.equals(object) ? defaultValue : object.toString(); - } - - - private void populateMap(Object bean) { - Class klass = bean.getClass(); - -// If klass is a System class then set includeSuperClass to false. - - boolean includeSuperClass = klass.getClassLoader() != null; - - Method[] methods = includeSuperClass - ? klass.getMethods() - : klass.getDeclaredMethods(); - for (int i = 0; i < methods.length; i += 1) { - try { - Method method = methods[i]; - if (Modifier.isPublic(method.getModifiers())) { - String name = method.getName(); - String key = ""; - if (name.startsWith("get")) { - if ("getClass".equals(name) || - "getDeclaringClass".equals(name)) { - key = ""; - } else { - key = name.substring(3); - } - } else if (name.startsWith("is")) { - key = name.substring(2); - } - if (key.length() > 0 && - Character.isUpperCase(key.charAt(0)) && - method.getParameterTypes().length == 0) { - if (key.length() == 1) { - key = key.toLowerCase(); - } else if (!Character.isUpperCase(key.charAt(1))) { - key = key.substring(0, 1).toLowerCase() + - key.substring(1); - } - - Object result = method.invoke(bean, (Object[])null); - if (result != null) { - this.map.put(key, wrap(result)); - } - } - } - } catch (Exception ignore) { - } - } - } - - - /** - * Put a key/boolean pair in the JSONObject. - * - * @param key A key string. - * @param value A boolean which is the value. - * @return this. - * @throws JSONException If the key is null. - */ - public JSONObject put(String key, boolean value) throws JSONException { - this.put(key, value ? Boolean.TRUE : Boolean.FALSE); - return this; - } - - - /** - * Put a key/value pair in the JSONObject, where the value will be a - * JSONArray which is produced from a Collection. - * @param key A key string. - * @param value A Collection value. - * @return this. - * @throws JSONException - */ - public JSONObject put(String key, Collection value) throws JSONException { - this.put(key, new JSONArray(value)); - return this; - } - - - /** - * Put a key/double pair in the JSONObject. - * - * @param key A key string. - * @param value A double which is the value. - * @return this. - * @throws JSONException If the key is null or if the number is invalid. - */ - public JSONObject put(String key, double value) throws JSONException { - this.put(key, new Double(value)); - return this; - } - - - /** - * Put a key/int pair in the JSONObject. - * - * @param key A key string. - * @param value An int which is the value. - * @return this. - * @throws JSONException If the key is null. - */ - public JSONObject put(String key, int value) throws JSONException { - this.put(key, new Integer(value)); - return this; - } - - - /** - * Put a key/long pair in the JSONObject. - * - * @param key A key string. - * @param value A long which is the value. - * @return this. - * @throws JSONException If the key is null. - */ - public JSONObject put(String key, long value) throws JSONException { - this.put(key, new Long(value)); - return this; - } - - - /** - * Put a key/value pair in the JSONObject, where the value will be a - * JSONObject which is produced from a Map. - * @param key A key string. - * @param value A Map value. - * @return this. - * @throws JSONException - */ - public JSONObject put(String key, Map value) throws JSONException { - this.put(key, new JSONObject(value)); - return this; - } - - - /** - * Put a key/value pair in the JSONObject. If the value is null, - * then the key will be removed from the JSONObject if it is present. - * @param key A key string. - * @param value An object which is the value. It should be of one of these - * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, - * or the JSONObject.NULL object. - * @return this. - * @throws JSONException If the value is non-finite number - * or if the key is null. - */ - public JSONObject put(String key, Object value) throws JSONException { - if (key == null) { - throw new JSONException("Null key."); - } - if (value != null) { - testValidity(value); - this.map.put(key, value); - } else { - this.remove(key); - } - return this; - } - - - /** - * Put a key/value pair in the JSONObject, but only if the key and the - * value are both non-null, and only if there is not already a member - * with that name. - * @param key - * @param value - * @return his. - * @throws JSONException if the key is a duplicate - */ - public JSONObject putOnce(String key, Object value) throws JSONException { - if (key != null && value != null) { - if (this.opt(key) != null) { - throw new JSONException("Duplicate key \"" + key + "\""); - } - this.put(key, value); - } - return this; - } - - - /** - * Put a key/value pair in the JSONObject, but only if the - * key and the value are both non-null. - * @param key A key string. - * @param value An object which is the value. It should be of one of these - * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, - * or the JSONObject.NULL object. - * @return this. - * @throws JSONException If the value is a non-finite number. - */ - public JSONObject putOpt(String key, Object value) throws JSONException { - if (key != null && value != null) { - this.put(key, value); - } - return this; - } - - - /** - * Produce a string in double quotes with backslash sequences in all the - * right places. A backslash will be inserted within </, producing <\/, - * allowing JSON text to be delivered in HTML. In JSON text, a string - * cannot contain a control character or an unescaped quote or backslash. - * @param string A String - * @return A String correctly formatted for insertion in a JSON text. - */ - public static String quote(String string) { - StringWriter sw = new StringWriter(); - synchronized (sw.getBuffer()) { - try { - return quote(string, sw).toString(); - } catch (IOException ignored) { - // will never happen - we are writing to a string writer - return ""; - } - } - } - - public static Writer quote(String string, Writer w) throws IOException { - if (string == null || string.length() == 0) { - w.write("\"\""); - return w; - } - - char b; - char c = 0; - String hhhh; - int i; - int len = string.length(); - - w.write('"'); - for (i = 0; i < len; i += 1) { - b = c; - c = string.charAt(i); - switch (c) { - case '\\': - case '"': - w.write('\\'); - w.write(c); - break; - case '/': - if (b == '<') { - w.write('\\'); - } - w.write(c); - break; - case '\b': - w.write("\\b"); - break; - case '\t': - w.write("\\t"); - break; - case '\n': - w.write("\\n"); - break; - case '\f': - w.write("\\f"); - break; - case '\r': - w.write("\\r"); - break; - default: - if (c < ' ' || (c >= '\u0080' && c < '\u00a0') - || (c >= '\u2000' && c < '\u2100')) { - hhhh = "000" + Integer.toHexString(c); - w.write("\\u" + hhhh.substring(hhhh.length() - 4)); - } else { - w.write(c); - } - } - } - w.write('"'); - return w; - } - - /** - * Remove a name and its value, if present. - * @param key The name to be removed. - * @return The value that was associated with the name, - * or null if there was no value. - */ - public Object remove(String key) { - return this.map.remove(key); - } - - /** - * Try to convert a string into a number, boolean, or null. If the string - * can't be converted, return the string. - * @param string A String. - * @return A simple JSON value. - */ - public static Object stringToValue(String string) { - Double d; - if (string.equals("")) { - return string; - } - if (string.equalsIgnoreCase("true")) { - return Boolean.TRUE; - } - if (string.equalsIgnoreCase("false")) { - return Boolean.FALSE; - } - if (string.equalsIgnoreCase("null")) { - return JSONObject.NULL; - } - - /* - * If it might be a number, try converting it. - * If a number cannot be produced, then the value will just - * be a string. Note that the plus and implied string - * conventions are non-standard. A JSON parser may accept - * non-JSON forms as long as it accepts all correct JSON forms. - */ - - char b = string.charAt(0); - if ((b >= '0' && b <= '9') || b == '.' || b == '-' || b == '+') { - try { - if (string.indexOf('.') > -1 || - string.indexOf('e') > -1 || string.indexOf('E') > -1) { - d = Double.valueOf(string); - if (!d.isInfinite() && !d.isNaN()) { - return d; - } - } else { - Long myLong = new Long(string); - if (myLong.longValue() == myLong.intValue()) { - return new Integer(myLong.intValue()); - } else { - return myLong; - } - } - } catch (Exception ignore) { - } - } - return string; - } - - - /** - * Throw an exception if the object is a NaN or infinite number. - * @param o The object to test. - * @throws JSONException If o is a non-finite number. - */ - public static void testValidity(Object o) throws JSONException { - if (o != null) { - if (o instanceof Double) { - if (((Double)o).isInfinite() || ((Double)o).isNaN()) { - throw new JSONException( - "JSON does not allow non-finite numbers."); - } - } else if (o instanceof Float) { - if (((Float)o).isInfinite() || ((Float)o).isNaN()) { - throw new JSONException( - "JSON does not allow non-finite numbers."); - } - } - } - } - - - /** - * Produce a JSONArray containing the values of the members of this - * JSONObject. - * @param names A JSONArray containing a list of key strings. This - * determines the sequence of the values in the result. - * @return A JSONArray of values. - * @throws JSONException If any of the values are non-finite numbers. - */ - public JSONArray toJSONArray(JSONArray names) throws JSONException { - if (names == null || names.length() == 0) { - return null; - } - JSONArray ja = new JSONArray(); - for (int i = 0; i < names.length(); i += 1) { - ja.put(this.opt(names.getString(i))); - } - return ja; - } - - /** - * Make a JSON text of this JSONObject. For compactness, no whitespace - * is added. If this would not result in a syntactically correct JSON text, - * then null will be returned instead. - * <p> - * Warning: This method assumes that the data structure is acyclical. - * - * @return a printable, displayable, portable, transmittable - * representation of the object, beginning - * with <code>{</code> <small>(left brace)</small> and ending - * with <code>}</code> <small>(right brace)</small>. - */ - public String toString() { - try { - return this.toString(0); - } catch (Exception e) { - return null; - } - } - - - /** - * Make a prettyprinted JSON text of this JSONObject. - * <p> - * Warning: This method assumes that the data structure is acyclical. - * @param indentFactor The number of spaces to add to each level of - * indentation. - * @return a printable, displayable, portable, transmittable - * representation of the object, beginning - * with <code>{</code> <small>(left brace)</small> and ending - * with <code>}</code> <small>(right brace)</small>. - * @throws JSONException If the object contains an invalid number. - */ - public String toString(int indentFactor) throws JSONException { - StringWriter w = new StringWriter(); - synchronized (w.getBuffer()) { - return this.write(w, indentFactor, 0).toString(); - } - } - - /** - * Make a JSON text of an Object value. If the object has an - * value.toJSONString() method, then that method will be used to produce - * the JSON text. The method is required to produce a strictly - * conforming text. If the object does not contain a toJSONString - * method (which is the most common case), then a text will be - * produced by other means. If the value is an array or Collection, - * then a JSONArray will be made from it and its toJSONString method - * will be called. If the value is a MAP, then a JSONObject will be made - * from it and its toJSONString method will be called. Otherwise, the - * value's toString method will be called, and the result will be quoted. - * - * <p> - * Warning: This method assumes that the data structure is acyclical. - * @param value The value to be serialized. - * @return a printable, displayable, transmittable - * representation of the object, beginning - * with <code>{</code> <small>(left brace)</small> and ending - * with <code>}</code> <small>(right brace)</small>. - * @throws JSONException If the value is or contains an invalid number. - */ - public static String valueToString(Object value) throws JSONException { - if (value == null || value.equals(null)) { - return "null"; - } - if (value instanceof JSONString) { - Object object; - try { - object = ((JSONString)value).toJSONString(); - } catch (Exception e) { - throw new JSONException(e); - } - if (object instanceof String) { - return (String)object; - } - throw new JSONException("Bad value from toJSONString: " + object); - } - if (value instanceof Number) { - return numberToString((Number) value); - } - if (value instanceof Boolean || value instanceof JSONObject || - value instanceof JSONArray) { - return value.toString(); - } - if (value instanceof Map) { - return new JSONObject((Map)value).toString(); - } - if (value instanceof Collection) { - return new JSONArray((Collection)value).toString(); - } - if (value.getClass().isArray()) { - return new JSONArray(value).toString(); - } - return quote(value.toString()); - } - - /** - * Wrap an object, if necessary. If the object is null, return the NULL - * object. If it is an array or collection, wrap it in a JSONArray. If - * it is a map, wrap it in a JSONObject. If it is a standard property - * (Double, String, et al) then it is already wrapped. Otherwise, if it - * comes from one of the java packages, turn it into a string. And if - * it doesn't, try to wrap it in a JSONObject. If the wrapping fails, - * then null is returned. - * - * @param object The object to wrap - * @return The wrapped value - */ - public static Object wrap(Object object) { - try { - if (object == null) { - return NULL; - } - if (object instanceof JSONObject || object instanceof JSONArray || - NULL.equals(object) || object instanceof JSONString || - object instanceof Byte || object instanceof Character || - object instanceof Short || object instanceof Integer || - object instanceof Long || object instanceof Boolean || - object instanceof Float || object instanceof Double || - object instanceof String) { - return object; - } - - if (object instanceof Collection) { - return new JSONArray((Collection)object); - } - if (object.getClass().isArray()) { - return new JSONArray(object); - } - if (object instanceof Map) { - return new JSONObject((Map)object); - } - Package objectPackage = object.getClass().getPackage(); - String objectPackageName = objectPackage != null - ? objectPackage.getName() - : ""; - if ( - objectPackageName.startsWith("java.") || - objectPackageName.startsWith("javax.") || - object.getClass().getClassLoader() == null - ) { - return object.toString(); - } - return new JSONObject(object); - } catch(Exception exception) { - return null; - } - } - - - /** - * Write the contents of the JSONObject as JSON text to a writer. - * For compactness, no whitespace is added. - * <p> - * Warning: This method assumes that the data structure is acyclical. - * - * @return The writer. - * @throws JSONException - */ - public Writer write(Writer writer) throws JSONException { - return this.write(writer, 0, 0); - } - - - static final Writer writeValue(Writer writer, Object value, - int indentFactor, int indent) throws JSONException, IOException { - if (value instanceof JSONObject) { - ((JSONObject) value).write(writer, indentFactor, indent); - } else if (value instanceof JSONArray) { - ((JSONArray) value).write(writer, indentFactor, indent); - } else if (value instanceof Map) { - new JSONObject((Map) value).write(writer, indentFactor, indent); - } else if (value instanceof Collection) { - new JSONArray((Collection) value).write(writer, indentFactor, - indent); - } else if (value.getClass().isArray()) { - new JSONArray(value).write(writer, indentFactor, indent); - } else if (value instanceof Number) { - writer.write(numberToString((Number) value)); - } else if (value instanceof Boolean) { - writer.write(value.toString()); - } else if (value instanceof JSONString) { - Object o; - try { - o = ((JSONString) value).toJSONString(); - } catch (Exception e) { - throw new JSONException(e); - } - writer.write(o != null ? o.toString() : quote(value.toString())); - } else if (value == null || value.equals(null)) { - writer.write("null"); - } else { - quote(value.toString(), writer); - } - return writer; - } - - static final void indent(Writer writer, int indent) throws IOException { - for (int i = 0; i < indent; i += 1) { - writer.write(' '); - } - } - - /** - * Write the contents of the JSONObject as JSON text to a writer. For - * compactness, no whitespace is added. - * <p> - * Warning: This method assumes that the data structure is acyclical. - * - * @return The writer. - * @throws JSONException - */ - Writer write(Writer writer, int indentFactor, int indent) - throws JSONException { - try { - boolean commanate = false; - final int length = this.length(); - Iterator keys = this.keys(); - writer.write('{'); - - if (length == 1) { - Object key = keys.next(); - writer.write(quote(key.toString())); - writer.write(':'); - if (indentFactor > 0) { - writer.write(' '); - } - writeValue(writer, this.map.get(key), indentFactor, indent); - } else if (length != 0) { - final int newindent = indent + indentFactor; - while (keys.hasNext()) { - Object key = keys.next(); - if (commanate) { - writer.write(','); - } - if (indentFactor > 0) { - writer.write('\n'); - } - indent(writer, newindent); - writer.write(quote(key.toString())); - writer.write(':'); - if (indentFactor > 0) { - writer.write(' '); - } - writeValue(writer, this.map.get(key), indentFactor, - newindent); - commanate = true; - } - if (indentFactor > 0) { - writer.write('\n'); - } - indent(writer, indent); - } - writer.write('}'); - return writer; - } catch (IOException exception) { - throw new JSONException(exception); - } - } + /** + * JSONObject.NULL is equivalent to the value that JavaScript calls null, + * whilst Java's null is equivalent to the value that JavaScript calls + * undefined. + */ + private static final class Null { + + /** + * There is only intended to be a single instance of the NULL object, + * so the clone method returns itself. + * @return NULL. + */ + protected final Object clone(){ + return this; + } + + /** + * A Null object is equal to the null value and to itself. + * @param object An object to test for nullness. + * @return true if the object parameter is the JSONObject.NULL object + * or null. + */ + public boolean equals(Object object){ + return object == null || object == this; + } + + /** + * Get the "null" string value. + * @return The string "null". + */ + public String toString(){ + return "null"; + } + } + + /** + * The map where the JSONObject's properties are kept. + */ + private final Map map; + + /** + * It is sometimes more convenient and less ambiguous to have a + * <code>NULL</code> object than to use Java's <code>null</code> value. + * <code>JSONObject.NULL.equals(null)</code> returns <code>true</code>. + * <code>JSONObject.NULL.toString()</code> returns <code>"null"</code>. + */ + public static final Object NULL = new Null(); + + /** + * Construct an empty JSONObject. + */ + public JSONObject(){ + this.map = new HashMap(); + } + + /** + * Construct a JSONObject from a subset of another JSONObject. + * An array of strings is used to identify the keys that should be copied. + * Missing keys are ignored. + * @param jo A JSONObject. + * @param names An array of strings. + * @throws JSONException + * @exception JSONException If a value is a non-finite number or if a name is duplicated. + */ + public JSONObject(JSONObject jo, String[] names){ + this(); + for(int i = 0; i < names.length; i += 1){ + try{ + this.putOnce(names[i], jo.opt(names[i])); + }catch(Exception ignore){} + } + } + + /** + * Construct a JSONObject from a JSONTokener. + * @param x A JSONTokener object containing the source string. + * @throws JSONException If there is a syntax error in the source string + * or a duplicated key. + */ + public JSONObject(JSONTokener x) throws JSONException{ + this(); + char c; + String key; + + if (x.nextClean() != '{'){ + throw x.syntaxError("A JSONObject text must begin with '{'"); + } + for(;;){ + c = x.nextClean(); + switch(c){ + case 0: + throw x.syntaxError("A JSONObject text must end with '}'"); + case '}': + return; + default: + x.back(); + key = x.nextValue().toString(); + } + + // The key is followed by ':'. We will also tolerate '=' or '=>'. + + c = x.nextClean(); + if (c == '='){ + if (x.next() != '>'){ + x.back(); + } + }else if (c != ':'){ + throw x.syntaxError("Expected a ':' after a key"); + } + this.putOnce(key, x.nextValue()); + + // Pairs are separated by ','. We will also tolerate ';'. + + switch(x.nextClean()){ + case ';': + case ',': + if (x.nextClean() == '}'){ + return; + } + x.back(); + break; + case '}': + return; + default: + throw x.syntaxError("Expected a ',' or '}'"); + } + } + } + + /** + * Construct a JSONObject from a Map. + * + * @param map A map object that can be used to initialize the contents of + * the JSONObject. + * @throws JSONException + */ + public JSONObject(Map map){ + this.map = new HashMap(); + if (map != null){ + Iterator i = map.entrySet().iterator(); + while(i.hasNext()){ + Map.Entry e = (Map.Entry)i.next(); + Object value = e.getValue(); + if (value != null){ + this.map.put(e.getKey(), wrap(value)); + } + } + } + } + + /** + * Construct a JSONObject from an Object using bean getters. + * It reflects on all of the public methods of the object. + * For each of the methods with no parameters and a name starting + * with <code>"get"</code> or <code>"is"</code> followed by an uppercase letter, + * the method is invoked, and a key and the value returned from the getter method + * are put into the new JSONObject. + * + * The key is formed by removing the <code>"get"</code> or <code>"is"</code> prefix. + * If the second remaining character is not upper case, then the first + * character is converted to lower case. + * + * For example, if an object has a method named <code>"getName"</code>, and + * if the result of calling <code>object.getName()</code> is <code>"Larry Fine"</code>, + * then the JSONObject will contain <code>"name": "Larry Fine"</code>. + * + * @param bean An object that has getter methods that should be used + * to make a JSONObject. + */ + public JSONObject(Object bean){ + this(); + this.populateMap(bean); + } + + /** + * Construct a JSONObject from an Object, using reflection to find the + * public members. The resulting JSONObject's keys will be the strings + * from the names array, and the values will be the field values associated + * with those keys in the object. If a key is not found or not visible, + * then it will not be copied into the new JSONObject. + * @param object An object that has fields that should be used to make a + * JSONObject. + * @param names An array of strings, the names of the fields to be obtained + * from the object. + */ + public JSONObject(Object object, String names[]){ + this(); + Class c = object.getClass(); + for(int i = 0; i < names.length; i += 1){ + String name = names[i]; + try{ + this.putOpt(name, c.getField(name).get(object)); + }catch(Exception ignore){} + } + } + + /** + * Construct a JSONObject from a source JSON text string. + * This is the most commonly used JSONObject constructor. + * @param source A string beginning + * with <code>{</code> <small>(left brace)</small> and ending + * with <code>}</code> <small>(right brace)</small>. + * @exception JSONException If there is a syntax error in the source + * string or a duplicated key. + */ + public JSONObject(String source) throws JSONException{ + this(new JSONTokener(source)); + } + + /** + * Construct a JSONObject from a ResourceBundle. + * @param baseName The ResourceBundle base name. + * @param locale The Locale to load the ResourceBundle for. + * @throws JSONException If any JSONExceptions are detected. + */ + public JSONObject(String baseName, Locale locale) throws JSONException{ + this(); + ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, Thread.currentThread().getContextClassLoader()); + + // Iterate through the keys in the bundle. + + Enumeration keys = bundle.getKeys(); + while(keys.hasMoreElements()){ + Object key = keys.nextElement(); + if (key instanceof String){ + + // Go through the path, ensuring that there is a nested JSONObject for each + // segment except the last. Add the value using the last segment's name into + // the deepest nested JSONObject. + + String[] path = ((String)key).split("\\."); + int last = path.length - 1; + JSONObject target = this; + for(int i = 0; i < last; i += 1){ + String segment = path[i]; + JSONObject nextTarget = target.optJSONObject(segment); + if (nextTarget == null){ + nextTarget = new JSONObject(); + target.put(segment, nextTarget); + } + target = nextTarget; + } + target.put(path[last], bundle.getString((String)key)); + } + } + } + + /** + * Accumulate values under a key. It is similar to the put method except + * that if there is already an object stored under the key then a + * JSONArray is stored under the key to hold all of the accumulated values. + * If there is already a JSONArray, then the new value is appended to it. + * In contrast, the put method replaces the previous value. + * + * If only one value is accumulated that is not a JSONArray, then the + * result will be the same as using put. But if multiple values are + * accumulated, then the result will be like append. + * @param key A key string. + * @param value An object to be accumulated under the key. + * @return this. + * @throws JSONException If the value is an invalid number + * or if the key is null. + */ + public JSONObject accumulate(String key, Object value) throws JSONException{ + testValidity(value); + Object object = this.opt(key); + if (object == null){ + this.put(key, value instanceof JSONArray ? new JSONArray().put(value) : value); + }else if (object instanceof JSONArray){ + ((JSONArray)object).put(value); + }else{ + this.put(key, new JSONArray().put(object).put(value)); + } + return this; + } + + /** + * Append values to the array under a key. If the key does not exist in the + * JSONObject, then the key is put in the JSONObject with its value being a + * JSONArray containing the value parameter. If the key was already + * associated with a JSONArray, then the value parameter is appended to it. + * @param key A key string. + * @param value An object to be accumulated under the key. + * @return this. + * @throws JSONException If the key is null or if the current value + * associated with the key is not a JSONArray. + */ + public JSONObject append(String key, Object value) throws JSONException{ + testValidity(value); + Object object = this.opt(key); + if (object == null){ + this.put(key, new JSONArray().put(value)); + }else if (object instanceof JSONArray){ + this.put(key, ((JSONArray)object).put(value)); + }else{ + throw new JSONException("JSONObject[" + key + "] is not a JSONArray."); + } + return this; + } + + /** + * Produce a string from a double. The string "null" will be returned if + * the number is not finite. + * @param d A double. + * @return A String. + */ + public static String doubleToString(double d){ + if (Double.isInfinite(d) || Double.isNaN(d)){ + return "null"; + } + + // Shave off trailing zeros and decimal point, if possible. + + String string = Double.toString(d); + if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0){ + while(string.endsWith("0")){ + string = string.substring(0, string.length() - 1); + } + if (string.endsWith(".")){ + string = string.substring(0, string.length() - 1); + } + } + return string; + } + + /** + * Get the value object associated with a key. + * + * @param key A key string. + * @return The object associated with the key. + * @throws JSONException if the key is not found. + */ + public Object get(String key) throws JSONException{ + if (key == null){ + throw new JSONException("Null key."); + } + Object object = this.opt(key); + if (object == null){ + throw new JSONException("JSONObject[" + quote(key) + "] not found."); + } + return object; + } + + /** + * Get the boolean value associated with a key. + * + * @param key A key string. + * @return The truth. + * @throws JSONException + * if the value is not a Boolean or the String "true" or "false". + */ + public boolean getBoolean(String key) throws JSONException{ + Object object = this.get(key); + if (object.equals(Boolean.FALSE) || (object instanceof String && ((String)object).equalsIgnoreCase("false"))){ + return false; + }else if (object.equals(Boolean.TRUE) || (object instanceof String && ((String)object).equalsIgnoreCase("true"))){ + return true; + } + throw new JSONException("JSONObject[" + quote(key) + "] is not a Boolean."); + } + + /** + * Get the double value associated with a key. + * @param key A key string. + * @return The numeric value. + * @throws JSONException if the key is not found or + * if the value is not a Number object and cannot be converted to a number. + */ + public double getDouble(String key) throws JSONException{ + Object object = this.get(key); + try{ + return object instanceof Number ? ((Number)object).doubleValue() : Double.parseDouble((String)object); + }catch(Exception e){ + throw new JSONException("JSONObject[" + quote(key) + "] is not a number."); + } + } + + /** + * Get the int value associated with a key. + * + * @param key A key string. + * @return The integer value. + * @throws JSONException if the key is not found or if the value cannot + * be converted to an integer. + */ + public int getInt(String key) throws JSONException{ + Object object = this.get(key); + try{ + return object instanceof Number ? ((Number)object).intValue() : Integer.parseInt((String)object); + }catch(Exception e){ + throw new JSONException("JSONObject[" + quote(key) + "] is not an int."); + } + } + + /** + * Get the JSONArray value associated with a key. + * + * @param key A key string. + * @return A JSONArray which is the value. + * @throws JSONException if the key is not found or + * if the value is not a JSONArray. + */ + public JSONArray getJSONArray(String key) throws JSONException{ + Object object = this.get(key); + if (object instanceof JSONArray){ + return (JSONArray)object; + } + throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONArray."); + } + + /** + * Get the JSONObject value associated with a key. + * + * @param key A key string. + * @return A JSONObject which is the value. + * @throws JSONException if the key is not found or + * if the value is not a JSONObject. + */ + public JSONObject getJSONObject(String key) throws JSONException{ + Object object = this.get(key); + if (object instanceof JSONObject){ + return (JSONObject)object; + } + throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONObject."); + } + + /** + * Get the long value associated with a key. + * + * @param key A key string. + * @return The long value. + * @throws JSONException if the key is not found or if the value cannot + * be converted to a long. + */ + public long getLong(String key) throws JSONException{ + Object object = this.get(key); + try{ + return object instanceof Number ? ((Number)object).longValue() : Long.parseLong((String)object); + }catch(Exception e){ + throw new JSONException("JSONObject[" + quote(key) + "] is not a long."); + } + } + + /** + * Get an array of field names from a JSONObject. + * + * @return An array of field names, or null if there are no names. + */ + public static String[] getNames(JSONObject jo){ + int length = jo.length(); + if (length == 0){ + return null; + } + Iterator iterator = jo.keys(); + String[] names = new String[length]; + int i = 0; + while(iterator.hasNext()){ + names[i] = (String)iterator.next(); + i += 1; + } + return names; + } + + /** + * Get an array of field names from an Object. + * + * @return An array of field names, or null if there are no names. + */ + public static String[] getNames(Object object){ + if (object == null){ + return null; + } + Class klass = object.getClass(); + Field[] fields = klass.getFields(); + int length = fields.length; + if (length == 0){ + return null; + } + String[] names = new String[length]; + for(int i = 0; i < length; i += 1){ + names[i] = fields[i].getName(); + } + return names; + } + + /** + * Get the string associated with a key. + * + * @param key A key string. + * @return A string which is the value. + * @throws JSONException if there is no string value for the key. + */ + public String getString(String key) throws JSONException{ + Object object = this.get(key); + if (object instanceof String){ + return (String)object; + } + throw new JSONException("JSONObject[" + quote(key) + "] not a string."); + } + + /** + * Determine if the JSONObject contains a specific key. + * @param key A key string. + * @return true if the key exists in the JSONObject. + */ + public boolean has(String key){ + return this.map.containsKey(key); + } + + /** + * Increment a property of a JSONObject. If there is no such property, + * create one with a value of 1. If there is such a property, and if + * it is an Integer, Long, Double, or Float, then add one to it. + * @param key A key string. + * @return this. + * @throws JSONException If there is already a property with this name + * that is not an Integer, Long, Double, or Float. + */ + public JSONObject increment(String key) throws JSONException{ + Object value = this.opt(key); + if (value == null){ + this.put(key, 1); + }else if (value instanceof Integer){ + this.put(key, ((Integer)value).intValue() + 1); + }else if (value instanceof Long){ + this.put(key, ((Long)value).longValue() + 1); + }else if (value instanceof Double){ + this.put(key, ((Double)value).doubleValue() + 1); + }else if (value instanceof Float){ + this.put(key, ((Float)value).floatValue() + 1); + }else{ + throw new JSONException("Unable to increment [" + quote(key) + "]."); + } + return this; + } + + /** + * Determine if the value associated with the key is null or if there is + * no value. + * @param key A key string. + * @return true if there is no value associated with the key or if + * the value is the JSONObject.NULL object. + */ + public boolean isNull(String key){ + return JSONObject.NULL.equals(this.opt(key)); + } + + /** + * Get an enumeration of the keys of the JSONObject. + * + * @return An iterator of the keys. + */ + public Iterator keys(){ + return this.map.keySet().iterator(); + } + + /** + * Get the number of keys stored in the JSONObject. + * + * @return The number of keys in the JSONObject. + */ + public int length(){ + return this.map.size(); + } + + /** + * Produce a JSONArray containing the names of the elements of this + * JSONObject. + * @return A JSONArray containing the key strings, or null if the JSONObject + * is empty. + */ + public JSONArray names(){ + JSONArray ja = new JSONArray(); + Iterator keys = this.keys(); + while(keys.hasNext()){ + ja.put(keys.next()); + } + return ja.length() == 0 ? null : ja; + } + + /** + * Produce a string from a Number. + * @param number A Number + * @return A String. + * @throws JSONException If n is a non-finite number. + */ + public static String numberToString(Number number) throws JSONException{ + if (number == null){ + throw new JSONException("Null pointer"); + } + testValidity(number); + + // Shave off trailing zeros and decimal point, if possible. + + String string = number.toString(); + if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0){ + while(string.endsWith("0")){ + string = string.substring(0, string.length() - 1); + } + if (string.endsWith(".")){ + string = string.substring(0, string.length() - 1); + } + } + return string; + } + + /** + * Get an optional value associated with a key. + * @param key A key string. + * @return An object which is the value, or null if there is no value. + */ + public Object opt(String key){ + return key == null ? null : this.map.get(key); + } + + /** + * Get an optional boolean associated with a key. + * It returns false if there is no such key, or if the value is not + * Boolean.TRUE or the String "true". + * + * @param key A key string. + * @return The truth. + */ + public boolean optBoolean(String key){ + return this.optBoolean(key, false); + } + + /** + * Get an optional boolean associated with a key. + * It returns the defaultValue if there is no such key, or if it is not + * a Boolean or the String "true" or "false" (case insensitive). + * + * @param key A key string. + * @param defaultValue The default. + * @return The truth. + */ + public boolean optBoolean(String key, boolean defaultValue){ + try{ + return this.getBoolean(key); + }catch(Exception e){ + return defaultValue; + } + } + + /** + * Get an optional double associated with a key, + * or NaN if there is no such key or if its value is not a number. + * If the value is a string, an attempt will be made to evaluate it as + * a number. + * + * @param key A string which is the key. + * @return An object which is the value. + */ + public double optDouble(String key){ + return this.optDouble(key, Double.NaN); + } + + /** + * Get an optional double associated with a key, or the + * defaultValue if there is no such key or if its value is not a number. + * If the value is a string, an attempt will be made to evaluate it as + * a number. + * + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. + */ + public double optDouble(String key, double defaultValue){ + try{ + return this.getDouble(key); + }catch(Exception e){ + return defaultValue; + } + } + + /** + * Get an optional int value associated with a key, + * or zero if there is no such key or if the value is not a number. + * If the value is a string, an attempt will be made to evaluate it as + * a number. + * + * @param key A key string. + * @return An object which is the value. + */ + public int optInt(String key){ + return this.optInt(key, 0); + } + + /** + * Get an optional int value associated with a key, + * or the default if there is no such key or if the value is not a number. + * If the value is a string, an attempt will be made to evaluate it as + * a number. + * + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. + */ + public int optInt(String key, int defaultValue){ + try{ + return this.getInt(key); + }catch(Exception e){ + return defaultValue; + } + } + + /** + * Get an optional JSONArray associated with a key. + * It returns null if there is no such key, or if its value is not a + * JSONArray. + * + * @param key A key string. + * @return A JSONArray which is the value. + */ + public JSONArray optJSONArray(String key){ + Object o = this.opt(key); + return o instanceof JSONArray ? (JSONArray)o : null; + } + + /** + * Get an optional JSONObject associated with a key. + * It returns null if there is no such key, or if its value is not a + * JSONObject. + * + * @param key A key string. + * @return A JSONObject which is the value. + */ + public JSONObject optJSONObject(String key){ + Object object = this.opt(key); + return object instanceof JSONObject ? (JSONObject)object : null; + } + + /** + * Get an optional long value associated with a key, + * or zero if there is no such key or if the value is not a number. + * If the value is a string, an attempt will be made to evaluate it as + * a number. + * + * @param key A key string. + * @return An object which is the value. + */ + public long optLong(String key){ + return this.optLong(key, 0); + } + + /** + * Get an optional long value associated with a key, + * or the default if there is no such key or if the value is not a number. + * If the value is a string, an attempt will be made to evaluate it as + * a number. + * + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. + */ + public long optLong(String key, long defaultValue){ + try{ + return this.getLong(key); + }catch(Exception e){ + return defaultValue; + } + } + + /** + * Get an optional string associated with a key. + * It returns an empty string if there is no such key. If the value is not + * a string and is not null, then it is converted to a string. + * + * @param key A key string. + * @return A string which is the value. + */ + public String optString(String key){ + return this.optString(key, ""); + } + + /** + * Get an optional string associated with a key. + * It returns the defaultValue if there is no such key. + * + * @param key A key string. + * @param defaultValue The default. + * @return A string which is the value. + */ + public String optString(String key, String defaultValue){ + Object object = this.opt(key); + return NULL.equals(object) ? defaultValue : object.toString(); + } + + private void populateMap(Object bean){ + Class klass = bean.getClass(); + + // If klass is a System class then set includeSuperClass to false. + + boolean includeSuperClass = klass.getClassLoader() != null; + + Method[] methods = includeSuperClass ? klass.getMethods() : klass.getDeclaredMethods(); + for(int i = 0; i < methods.length; i += 1){ + try{ + Method method = methods[i]; + if (Modifier.isPublic(method.getModifiers())){ + String name = method.getName(); + String key = ""; + if (name.startsWith("get")){ + if ("getClass".equals(name) || "getDeclaringClass".equals(name)){ + key = ""; + }else{ + key = name.substring(3); + } + }else if (name.startsWith("is")){ + key = name.substring(2); + } + if (key.length() > 0 && Character.isUpperCase(key.charAt(0)) && method.getParameterTypes().length == 0){ + if (key.length() == 1){ + key = key.toLowerCase(); + }else if (!Character.isUpperCase(key.charAt(1))){ + key = key.substring(0, 1).toLowerCase() + key.substring(1); + } + + Object result = method.invoke(bean, (Object[])null); + if (result != null){ + this.map.put(key, wrap(result)); + } + } + } + }catch(Exception ignore){} + } + } + + /** + * Put a key/boolean pair in the JSONObject. + * + * @param key A key string. + * @param value A boolean which is the value. + * @return this. + * @throws JSONException If the key is null. + */ + public JSONObject put(String key, boolean value) throws JSONException{ + this.put(key, value ? Boolean.TRUE : Boolean.FALSE); + return this; + } + + /** + * Put a key/value pair in the JSONObject, where the value will be a + * JSONArray which is produced from a Collection. + * @param key A key string. + * @param value A Collection value. + * @return this. + * @throws JSONException + */ + public JSONObject put(String key, Collection value) throws JSONException{ + this.put(key, new JSONArray(value)); + return this; + } + + /** + * Put a key/double pair in the JSONObject. + * + * @param key A key string. + * @param value A double which is the value. + * @return this. + * @throws JSONException If the key is null or if the number is invalid. + */ + public JSONObject put(String key, double value) throws JSONException{ + this.put(key, new Double(value)); + return this; + } + + /** + * Put a key/int pair in the JSONObject. + * + * @param key A key string. + * @param value An int which is the value. + * @return this. + * @throws JSONException If the key is null. + */ + public JSONObject put(String key, int value) throws JSONException{ + this.put(key, new Integer(value)); + return this; + } + + /** + * Put a key/long pair in the JSONObject. + * + * @param key A key string. + * @param value A long which is the value. + * @return this. + * @throws JSONException If the key is null. + */ + public JSONObject put(String key, long value) throws JSONException{ + this.put(key, new Long(value)); + return this; + } + + /** + * Put a key/value pair in the JSONObject, where the value will be a + * JSONObject which is produced from a Map. + * @param key A key string. + * @param value A Map value. + * @return this. + * @throws JSONException + */ + public JSONObject put(String key, Map value) throws JSONException{ + this.put(key, new JSONObject(value)); + return this; + } + + /** + * Put a key/value pair in the JSONObject. If the value is null, + * then the key will be removed from the JSONObject if it is present. + * @param key A key string. + * @param value An object which is the value. It should be of one of these + * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, + * or the JSONObject.NULL object. + * @return this. + * @throws JSONException If the value is non-finite number + * or if the key is null. + */ + public JSONObject put(String key, Object value) throws JSONException{ + if (key == null){ + throw new JSONException("Null key."); + } + if (value != null){ + testValidity(value); + this.map.put(key, value); + }else{ + this.remove(key); + } + return this; + } + + /** + * Put a key/value pair in the JSONObject, but only if the key and the + * value are both non-null, and only if there is not already a member + * with that name. + * @param key + * @param value + * @return his. + * @throws JSONException if the key is a duplicate + */ + public JSONObject putOnce(String key, Object value) throws JSONException{ + if (key != null && value != null){ + if (this.opt(key) != null){ + throw new JSONException("Duplicate key \"" + key + "\""); + } + this.put(key, value); + } + return this; + } + + /** + * Put a key/value pair in the JSONObject, but only if the + * key and the value are both non-null. + * @param key A key string. + * @param value An object which is the value. It should be of one of these + * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, + * or the JSONObject.NULL object. + * @return this. + * @throws JSONException If the value is a non-finite number. + */ + public JSONObject putOpt(String key, Object value) throws JSONException{ + if (key != null && value != null){ + this.put(key, value); + } + return this; + } + + /** + * Produce a string in double quotes with backslash sequences in all the + * right places. A backslash will be inserted within </, producing <\/, + * allowing JSON text to be delivered in HTML. In JSON text, a string + * cannot contain a control character or an unescaped quote or backslash. + * @param string A String + * @return A String correctly formatted for insertion in a JSON text. + */ + public static String quote(String string){ + StringWriter sw = new StringWriter(); + synchronized(sw.getBuffer()){ + try{ + return quote(string, sw).toString(); + }catch(IOException ignored){ + // will never happen - we are writing to a string writer + return ""; + } + } + } + + public static Writer quote(String string, Writer w) throws IOException{ + if (string == null || string.length() == 0){ + w.write("\"\""); + return w; + } + + char b; + char c = 0; + String hhhh; + int i; + int len = string.length(); + + w.write('"'); + for(i = 0; i < len; i += 1){ + b = c; + c = string.charAt(i); + switch(c){ + case '\\': + case '"': + w.write('\\'); + w.write(c); + break; + case '/': + if (b == '<'){ + w.write('\\'); + } + w.write(c); + break; + case '\b': + w.write("\\b"); + break; + case '\t': + w.write("\\t"); + break; + case '\n': + w.write("\\n"); + break; + case '\f': + w.write("\\f"); + break; + case '\r': + w.write("\\r"); + break; + default: + if (c < ' ' || (c >= '\u0080' && c < '\u00a0') || (c >= '\u2000' && c < '\u2100')){ + hhhh = "000" + Integer.toHexString(c); + w.write("\\u" + hhhh.substring(hhhh.length() - 4)); + }else{ + w.write(c); + } + } + } + w.write('"'); + return w; + } + + /** + * Remove a name and its value, if present. + * @param key The name to be removed. + * @return The value that was associated with the name, + * or null if there was no value. + */ + public Object remove(String key){ + return this.map.remove(key); + } + + /** + * Try to convert a string into a number, boolean, or null. If the string + * can't be converted, return the string. + * @param string A String. + * @return A simple JSON value. + */ + public static Object stringToValue(String string){ + Double d; + if (string.equals("")){ + return string; + } + if (string.equalsIgnoreCase("true")){ + return Boolean.TRUE; + } + if (string.equalsIgnoreCase("false")){ + return Boolean.FALSE; + } + if (string.equalsIgnoreCase("null")){ + return JSONObject.NULL; + } + + /* + * If it might be a number, try converting it. + * If a number cannot be produced, then the value will just + * be a string. Note that the plus and implied string + * conventions are non-standard. A JSON parser may accept + * non-JSON forms as long as it accepts all correct JSON forms. + */ + + char b = string.charAt(0); + if ((b >= '0' && b <= '9') || b == '.' || b == '-' || b == '+'){ + try{ + if (string.indexOf('.') > -1 || string.indexOf('e') > -1 || string.indexOf('E') > -1){ + d = Double.valueOf(string); + if (!d.isInfinite() && !d.isNaN()){ + return d; + } + }else{ + Long myLong = new Long(string); + if (myLong.longValue() == myLong.intValue()){ + return new Integer(myLong.intValue()); + }else{ + return myLong; + } + } + }catch(Exception ignore){} + } + return string; + } + + /** + * Throw an exception if the object is a NaN or infinite number. + * @param o The object to test. + * @throws JSONException If o is a non-finite number. + */ + public static void testValidity(Object o) throws JSONException{ + if (o != null){ + if (o instanceof Double){ + if (((Double)o).isInfinite() || ((Double)o).isNaN()){ + throw new JSONException("JSON does not allow non-finite numbers."); + } + }else if (o instanceof Float){ + if (((Float)o).isInfinite() || ((Float)o).isNaN()){ + throw new JSONException("JSON does not allow non-finite numbers."); + } + } + } + } + + /** + * Produce a JSONArray containing the values of the members of this + * JSONObject. + * @param names A JSONArray containing a list of key strings. This + * determines the sequence of the values in the result. + * @return A JSONArray of values. + * @throws JSONException If any of the values are non-finite numbers. + */ + public JSONArray toJSONArray(JSONArray names) throws JSONException{ + if (names == null || names.length() == 0){ + return null; + } + JSONArray ja = new JSONArray(); + for(int i = 0; i < names.length(); i += 1){ + ja.put(this.opt(names.getString(i))); + } + return ja; + } + + /** + * Make a JSON text of this JSONObject. For compactness, no whitespace + * is added. If this would not result in a syntactically correct JSON text, + * then null will be returned instead. + * <p> + * Warning: This method assumes that the data structure is acyclical. + * + * @return a printable, displayable, portable, transmittable + * representation of the object, beginning + * with <code>{</code> <small>(left brace)</small> and ending + * with <code>}</code> <small>(right brace)</small>. + */ + public String toString(){ + try{ + return this.toString(0); + }catch(Exception e){ + return null; + } + } + + /** + * Make a prettyprinted JSON text of this JSONObject. + * <p> + * Warning: This method assumes that the data structure is acyclical. + * @param indentFactor The number of spaces to add to each level of + * indentation. + * @return a printable, displayable, portable, transmittable + * representation of the object, beginning + * with <code>{</code> <small>(left brace)</small> and ending + * with <code>}</code> <small>(right brace)</small>. + * @throws JSONException If the object contains an invalid number. + */ + public String toString(int indentFactor) throws JSONException{ + StringWriter w = new StringWriter(); + synchronized(w.getBuffer()){ + return this.write(w, indentFactor, 0).toString(); + } + } + + /** + * Make a JSON text of an Object value. If the object has an + * value.toJSONString() method, then that method will be used to produce + * the JSON text. The method is required to produce a strictly + * conforming text. If the object does not contain a toJSONString + * method (which is the most common case), then a text will be + * produced by other means. If the value is an array or Collection, + * then a JSONArray will be made from it and its toJSONString method + * will be called. If the value is a MAP, then a JSONObject will be made + * from it and its toJSONString method will be called. Otherwise, the + * value's toString method will be called, and the result will be quoted. + * + * <p> + * Warning: This method assumes that the data structure is acyclical. + * @param value The value to be serialized. + * @return a printable, displayable, transmittable + * representation of the object, beginning + * with <code>{</code> <small>(left brace)</small> and ending + * with <code>}</code> <small>(right brace)</small>. + * @throws JSONException If the value is or contains an invalid number. + */ + public static String valueToString(Object value) throws JSONException{ + if (value == null || value.equals(null)){ + return "null"; + } + if (value instanceof JSONString){ + Object object; + try{ + object = ((JSONString)value).toJSONString(); + }catch(Exception e){ + throw new JSONException(e); + } + if (object instanceof String){ + return (String)object; + } + throw new JSONException("Bad value from toJSONString: " + object); + } + if (value instanceof Number){ + return numberToString((Number)value); + } + if (value instanceof Boolean || value instanceof JSONObject || value instanceof JSONArray){ + return value.toString(); + } + if (value instanceof Map){ + return new JSONObject((Map)value).toString(); + } + if (value instanceof Collection){ + return new JSONArray((Collection)value).toString(); + } + if (value.getClass().isArray()){ + return new JSONArray(value).toString(); + } + return quote(value.toString()); + } + + /** + * Wrap an object, if necessary. If the object is null, return the NULL + * object. If it is an array or collection, wrap it in a JSONArray. If + * it is a map, wrap it in a JSONObject. If it is a standard property + * (Double, String, et al) then it is already wrapped. Otherwise, if it + * comes from one of the java packages, turn it into a string. And if + * it doesn't, try to wrap it in a JSONObject. If the wrapping fails, + * then null is returned. + * + * @param object The object to wrap + * @return The wrapped value + */ + public static Object wrap(Object object){ + try{ + if (object == null){ + return NULL; + } + if (object instanceof JSONObject || object instanceof JSONArray || NULL.equals(object) || object instanceof JSONString || object instanceof Byte || object instanceof Character || object instanceof Short || object instanceof Integer || object instanceof Long || object instanceof Boolean || object instanceof Float || object instanceof Double || object instanceof String){ + return object; + } + + if (object instanceof Collection){ + return new JSONArray((Collection)object); + } + if (object.getClass().isArray()){ + return new JSONArray(object); + } + if (object instanceof Map){ + return new JSONObject((Map)object); + } + Package objectPackage = object.getClass().getPackage(); + String objectPackageName = objectPackage != null ? objectPackage.getName() : ""; + if (objectPackageName.startsWith("java.") || objectPackageName.startsWith("javax.") || object.getClass().getClassLoader() == null){ + return object.toString(); + } + return new JSONObject(object); + }catch(Exception exception){ + return null; + } + } + + /** + * Write the contents of the JSONObject as JSON text to a writer. + * For compactness, no whitespace is added. + * <p> + * Warning: This method assumes that the data structure is acyclical. + * + * @return The writer. + * @throws JSONException + */ + public Writer write(Writer writer) throws JSONException{ + return this.write(writer, 0, 0); + } + + static final Writer writeValue(Writer writer, Object value, int indentFactor, int indent) throws JSONException, IOException{ + if (value instanceof JSONObject){ + ((JSONObject)value).write(writer, indentFactor, indent); + }else if (value instanceof JSONArray){ + ((JSONArray)value).write(writer, indentFactor, indent); + }else if (value instanceof Map){ + new JSONObject((Map)value).write(writer, indentFactor, indent); + }else if (value instanceof Collection){ + new JSONArray((Collection)value).write(writer, indentFactor, indent); + }else if (value.getClass().isArray()){ + new JSONArray(value).write(writer, indentFactor, indent); + }else if (value instanceof Number){ + writer.write(numberToString((Number)value)); + }else if (value instanceof Boolean){ + writer.write(value.toString()); + }else if (value instanceof JSONString){ + Object o; + try{ + o = ((JSONString)value).toJSONString(); + }catch(Exception e){ + throw new JSONException(e); + } + writer.write(o != null ? o.toString() : quote(value.toString())); + }else if (value == null || value.equals(null)){ + writer.write("null"); + }else{ + quote(value.toString(), writer); + } + return writer; + } + + static final void indent(Writer writer, int indent) throws IOException{ + for(int i = 0; i < indent; i += 1){ + writer.write(' '); + } + } + + /** + * Write the contents of the JSONObject as JSON text to a writer. For + * compactness, no whitespace is added. + * <p> + * Warning: This method assumes that the data structure is acyclical. + * + * @return The writer. + * @throws JSONException + */ + Writer write(Writer writer, int indentFactor, int indent) throws JSONException{ + try{ + boolean commanate = false; + final int length = this.length(); + Iterator keys = this.keys(); + writer.write('{'); + + if (length == 1){ + Object key = keys.next(); + writer.write(quote(key.toString())); + writer.write(':'); + if (indentFactor > 0){ + writer.write(' '); + } + writeValue(writer, this.map.get(key), indentFactor, indent); + }else if (length != 0){ + final int newindent = indent + indentFactor; + while(keys.hasNext()){ + Object key = keys.next(); + if (commanate){ + writer.write(','); + } + if (indentFactor > 0){ + writer.write('\n'); + } + indent(writer, newindent); + writer.write(quote(key.toString())); + writer.write(':'); + if (indentFactor > 0){ + writer.write(' '); + } + writeValue(writer, this.map.get(key), indentFactor, newindent); + commanate = true; + } + if (indentFactor > 0){ + writer.write('\n'); + } + indent(writer, indent); + } + writer.write('}'); + return writer; + }catch(IOException exception){ + throw new JSONException(exception); + } + } } diff --git a/src/org/json/JSONString.java b/src/org/json/JSONString.java index 41726b1b076e2a1d4b304150f3f9e97f91afdfc6..c8c71d9d29da3888f46babf2ec1b6fd7bb7bcdf1 100644 --- a/src/org/json/JSONString.java +++ b/src/org/json/JSONString.java @@ -1,4 +1,5 @@ package org.json; + /** * The <code>JSONString</code> interface allows a <code>toJSONString()</code> * method so that a class can change the behavior of @@ -8,11 +9,11 @@ package org.json; * of using the Object's <code>toString()</code> method and quoting the result. */ public interface JSONString { - /** - * The <code>toJSONString</code> method allows a class to produce its own JSON - * serialization. - * - * @return A strictly syntactically correct JSON text. - */ - public String toJSONString(); + /** + * The <code>toJSONString</code> method allows a class to produce its own JSON + * serialization. + * + * @return A strictly syntactically correct JSON text. + */ + public String toJSONString(); } diff --git a/src/org/json/JSONStringer.java b/src/org/json/JSONStringer.java index 25c2e5d788b3ee35184418b4c74176a2e39672b6..88b44d1c29f49358d758c3dbc41853f92043c769 100644 --- a/src/org/json/JSONStringer.java +++ b/src/org/json/JSONStringer.java @@ -57,22 +57,22 @@ import java.io.StringWriter; * @version 2008-09-18 */ public class JSONStringer extends JSONWriter { - /** - * Make a fresh JSONStringer. It can be used to build one JSON text. - */ - public JSONStringer() { - super(new StringWriter()); - } + /** + * Make a fresh JSONStringer. It can be used to build one JSON text. + */ + public JSONStringer(){ + super(new StringWriter()); + } - /** - * Return the JSON text. This method is used to obtain the product of the - * JSONStringer instance. It will return <code>null</code> if there was a - * problem in the construction of the JSON text (such as the calls to - * <code>array</code> were not properly balanced with calls to - * <code>endArray</code>). - * @return The JSON text. - */ - public String toString() { - return this.mode == 'd' ? this.writer.toString() : null; - } + /** + * Return the JSON text. This method is used to obtain the product of the + * JSONStringer instance. It will return <code>null</code> if there was a + * problem in the construction of the JSON text (such as the calls to + * <code>array</code> were not properly balanced with calls to + * <code>endArray</code>). + * @return The JSON text. + */ + public String toString(){ + return this.mode == 'd' ? this.writer.toString() : null; + } } diff --git a/src/org/json/JSONTokener.java b/src/org/json/JSONTokener.java index 13c84f1f5ff7b7f040a8277415f6cbb87a5f6f78..5e71636ee117b5c98da11cf1df3ce39325e040c5 100644 --- a/src/org/json/JSONTokener.java +++ b/src/org/json/JSONTokener.java @@ -40,407 +40,385 @@ SOFTWARE. */ public class JSONTokener { - private long character; - private boolean eof; - private long index; - private long line; - private char previous; - private Reader reader; - private boolean usePrevious; - - - /** - * Construct a JSONTokener from a Reader. - * - * @param reader A reader. - */ - public JSONTokener(Reader reader) { - this.reader = reader.markSupported() - ? reader - : new BufferedReader(reader); - this.eof = false; - this.usePrevious = false; - this.previous = 0; - this.index = 0; - this.character = 1; - this.line = 1; - } - - - /** - * Construct a JSONTokener from an InputStream. - */ - public JSONTokener(InputStream inputStream) throws JSONException { - this(new InputStreamReader(inputStream)); - } - - - /** - * Construct a JSONTokener from a string. - * - * @param s A source string. - */ - public JSONTokener(String s) { - this(new StringReader(s)); - } - - - /** - * Back up one character. This provides a sort of lookahead capability, - * so that you can test for a digit or letter before attempting to parse - * the next number or identifier. - */ - public void back() throws JSONException { - if (this.usePrevious || this.index <= 0) { - throw new JSONException("Stepping back two steps is not supported"); - } - this.index -= 1; - this.character -= 1; - this.usePrevious = true; - this.eof = false; - } - - - /** - * Get the hex value of a character (base16). - * @param c A character between '0' and '9' or between 'A' and 'F' or - * between 'a' and 'f'. - * @return An int between 0 and 15, or -1 if c was not a hex digit. - */ - public static int dehexchar(char c) { - if (c >= '0' && c <= '9') { - return c - '0'; - } - if (c >= 'A' && c <= 'F') { - return c - ('A' - 10); - } - if (c >= 'a' && c <= 'f') { - return c - ('a' - 10); - } - return -1; - } - - public boolean end() { - return this.eof && !this.usePrevious; - } - - - /** - * Determine if the source string still contains characters that next() - * can consume. - * @return true if not yet at the end of the source. - */ - public boolean more() throws JSONException { - this.next(); - if (this.end()) { - return false; - } - this.back(); - return true; - } - - - /** - * Get the next character in the source string. - * - * @return The next character, or 0 if past the end of the source string. - */ - public char next() throws JSONException { - int c; - if (this.usePrevious) { - this.usePrevious = false; - c = this.previous; - } else { - try { - c = this.reader.read(); - } catch (IOException exception) { - throw new JSONException(exception); - } - - if (c <= 0) { // End of stream - this.eof = true; - c = 0; - } - } - this.index += 1; - if (this.previous == '\r') { - this.line += 1; - this.character = c == '\n' ? 0 : 1; - } else if (c == '\n') { - this.line += 1; - this.character = 0; - } else { - this.character += 1; - } - this.previous = (char) c; - return this.previous; - } - - - /** - * Consume the next character, and check that it matches a specified - * character. - * @param c The character to match. - * @return The character. - * @throws JSONException if the character does not match. - */ - public char next(char c) throws JSONException { - char n = this.next(); - if (n != c) { - throw this.syntaxError("Expected '" + c + "' and instead saw '" + - n + "'"); - } - return n; - } - - - /** - * Get the next n characters. - * - * @param n The number of characters to take. - * @return A string of n characters. - * @throws JSONException - * Substring bounds error if there are not - * n characters remaining in the source string. - */ - public String next(int n) throws JSONException { - if (n == 0) { - return ""; - } - - char[] chars = new char[n]; - int pos = 0; - - while (pos < n) { - chars[pos] = this.next(); - if (this.end()) { - throw this.syntaxError("Substring bounds error"); - } - pos += 1; - } - return new String(chars); - } - - - /** - * Get the next char in the string, skipping whitespace. - * @throws JSONException - * @return A character, or 0 if there are no more characters. - */ - public char nextClean() throws JSONException { - for (;;) { - char c = this.next(); - if (c == 0 || c > ' ') { - return c; - } - } - } - - - /** - * Return the characters up to the next close quote character. - * Backslash processing is done. The formal JSON format does not - * allow strings in single quotes, but an implementation is allowed to - * accept them. - * @param quote The quoting character, either - * <code>"</code> <small>(double quote)</small> or - * <code>'</code> <small>(single quote)</small>. - * @return A String. - * @throws JSONException Unterminated string. - */ - public String nextString(char quote) throws JSONException { - char c; - StringBuffer sb = new StringBuffer(); - for (;;) { - c = this.next(); - switch (c) { - case 0: - case '\n': - case '\r': - throw this.syntaxError("Unterminated string"); - case '\\': - c = this.next(); - switch (c) { - case 'b': - sb.append('\b'); - break; - case 't': - sb.append('\t'); - break; - case 'n': - sb.append('\n'); - break; - case 'f': - sb.append('\f'); - break; - case 'r': - sb.append('\r'); - break; - case 'u': - sb.append((char)Integer.parseInt(this.next(4), 16)); - break; - case '"': - case '\'': - case '\\': - case '/': - sb.append(c); - break; - default: - throw this.syntaxError("Illegal escape."); - } - break; - default: - if (c == quote) { - return sb.toString(); - } - sb.append(c); - } - } - } - - - /** - * Get the text up but not including the specified character or the - * end of line, whichever comes first. - * @param delimiter A delimiter character. - * @return A string. - */ - public String nextTo(char delimiter) throws JSONException { - StringBuffer sb = new StringBuffer(); - for (;;) { - char c = this.next(); - if (c == delimiter || c == 0 || c == '\n' || c == '\r') { - if (c != 0) { - this.back(); - } - return sb.toString().trim(); - } - sb.append(c); - } - } - - - /** - * Get the text up but not including one of the specified delimiter - * characters or the end of line, whichever comes first. - * @param delimiters A set of delimiter characters. - * @return A string, trimmed. - */ - public String nextTo(String delimiters) throws JSONException { - char c; - StringBuffer sb = new StringBuffer(); - for (;;) { - c = this.next(); - if (delimiters.indexOf(c) >= 0 || c == 0 || - c == '\n' || c == '\r') { - if (c != 0) { - this.back(); - } - return sb.toString().trim(); - } - sb.append(c); - } - } - - - /** - * Get the next value. The value can be a Boolean, Double, Integer, - * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object. - * @throws JSONException If syntax error. - * - * @return An object. - */ - public Object nextValue() throws JSONException { - char c = this.nextClean(); - String string; - - switch (c) { - case '"': - case '\'': - return this.nextString(c); - case '{': - this.back(); - return new JSONObject(this); - case '[': - this.back(); - return new JSONArray(this); - } - - /* - * Handle unquoted text. This could be the values true, false, or - * null, or it can be a number. An implementation (such as this one) - * is allowed to also accept non-standard forms. - * - * Accumulate characters until we reach the end of the text or a - * formatting character. - */ - - StringBuffer sb = new StringBuffer(); - while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { - sb.append(c); - c = this.next(); - } - this.back(); - - string = sb.toString().trim(); - if ("".equals(string)) { - throw this.syntaxError("Missing value"); - } - return JSONObject.stringToValue(string); - } - - - /** - * Skip characters until the next character is the requested character. - * If the requested character is not found, no characters are skipped. - * @param to A character to skip to. - * @return The requested character, or zero if the requested character - * is not found. - */ - public char skipTo(char to) throws JSONException { - char c; - try { - long startIndex = this.index; - long startCharacter = this.character; - long startLine = this.line; - this.reader.mark(1000000); - do { - c = this.next(); - if (c == 0) { - this.reader.reset(); - this.index = startIndex; - this.character = startCharacter; - this.line = startLine; - return c; - } - } while (c != to); - } catch (IOException exc) { - throw new JSONException(exc); - } - - this.back(); - return c; - } - - - /** - * Make a JSONException to signal a syntax error. - * - * @param message The error message. - * @return A JSONException object, suitable for throwing - */ - public JSONException syntaxError(String message) { - return new JSONException(message + this.toString()); - } - - - /** - * Make a printable string of this JSONTokener. - * - * @return " at {index} [character {character} line {line}]" - */ - public String toString() { - return " at " + this.index + " [character " + this.character + " line " + - this.line + "]"; - } + private long character; + private boolean eof; + private long index; + private long line; + private char previous; + private Reader reader; + private boolean usePrevious; + + /** + * Construct a JSONTokener from a Reader. + * + * @param reader A reader. + */ + public JSONTokener(Reader reader){ + this.reader = reader.markSupported() ? reader : new BufferedReader(reader); + this.eof = false; + this.usePrevious = false; + this.previous = 0; + this.index = 0; + this.character = 1; + this.line = 1; + } + + /** + * Construct a JSONTokener from an InputStream. + */ + public JSONTokener(InputStream inputStream) throws JSONException{ + this(new InputStreamReader(inputStream)); + } + + /** + * Construct a JSONTokener from a string. + * + * @param s A source string. + */ + public JSONTokener(String s){ + this(new StringReader(s)); + } + + /** + * Back up one character. This provides a sort of lookahead capability, + * so that you can test for a digit or letter before attempting to parse + * the next number or identifier. + */ + public void back() throws JSONException{ + if (this.usePrevious || this.index <= 0){ + throw new JSONException("Stepping back two steps is not supported"); + } + this.index -= 1; + this.character -= 1; + this.usePrevious = true; + this.eof = false; + } + + /** + * Get the hex value of a character (base16). + * @param c A character between '0' and '9' or between 'A' and 'F' or + * between 'a' and 'f'. + * @return An int between 0 and 15, or -1 if c was not a hex digit. + */ + public static int dehexchar(char c){ + if (c >= '0' && c <= '9'){ + return c - '0'; + } + if (c >= 'A' && c <= 'F'){ + return c - ('A' - 10); + } + if (c >= 'a' && c <= 'f'){ + return c - ('a' - 10); + } + return -1; + } + + public boolean end(){ + return this.eof && !this.usePrevious; + } + + /** + * Determine if the source string still contains characters that next() + * can consume. + * @return true if not yet at the end of the source. + */ + public boolean more() throws JSONException{ + this.next(); + if (this.end()){ + return false; + } + this.back(); + return true; + } + + /** + * Get the next character in the source string. + * + * @return The next character, or 0 if past the end of the source string. + */ + public char next() throws JSONException{ + int c; + if (this.usePrevious){ + this.usePrevious = false; + c = this.previous; + }else{ + try{ + c = this.reader.read(); + }catch(IOException exception){ + throw new JSONException(exception); + } + + if (c <= 0){ // End of stream + this.eof = true; + c = 0; + } + } + this.index += 1; + if (this.previous == '\r'){ + this.line += 1; + this.character = c == '\n' ? 0 : 1; + }else if (c == '\n'){ + this.line += 1; + this.character = 0; + }else{ + this.character += 1; + } + this.previous = (char)c; + return this.previous; + } + + /** + * Consume the next character, and check that it matches a specified + * character. + * @param c The character to match. + * @return The character. + * @throws JSONException if the character does not match. + */ + public char next(char c) throws JSONException{ + char n = this.next(); + if (n != c){ + throw this.syntaxError("Expected '" + c + "' and instead saw '" + n + "'"); + } + return n; + } + + /** + * Get the next n characters. + * + * @param n The number of characters to take. + * @return A string of n characters. + * @throws JSONException + * Substring bounds error if there are not + * n characters remaining in the source string. + */ + public String next(int n) throws JSONException{ + if (n == 0){ + return ""; + } + + char[] chars = new char[n]; + int pos = 0; + + while(pos < n){ + chars[pos] = this.next(); + if (this.end()){ + throw this.syntaxError("Substring bounds error"); + } + pos += 1; + } + return new String(chars); + } + + /** + * Get the next char in the string, skipping whitespace. + * @throws JSONException + * @return A character, or 0 if there are no more characters. + */ + public char nextClean() throws JSONException{ + for(;;){ + char c = this.next(); + if (c == 0 || c > ' '){ + return c; + } + } + } + + /** + * Return the characters up to the next close quote character. + * Backslash processing is done. The formal JSON format does not + * allow strings in single quotes, but an implementation is allowed to + * accept them. + * @param quote The quoting character, either + * <code>"</code> <small>(double quote)</small> or + * <code>'</code> <small>(single quote)</small>. + * @return A String. + * @throws JSONException Unterminated string. + */ + public String nextString(char quote) throws JSONException{ + char c; + StringBuffer sb = new StringBuffer(); + for(;;){ + c = this.next(); + switch(c){ + case 0: + case '\n': + case '\r': + throw this.syntaxError("Unterminated string"); + case '\\': + c = this.next(); + switch(c){ + case 'b': + sb.append('\b'); + break; + case 't': + sb.append('\t'); + break; + case 'n': + sb.append('\n'); + break; + case 'f': + sb.append('\f'); + break; + case 'r': + sb.append('\r'); + break; + case 'u': + sb.append((char)Integer.parseInt(this.next(4), 16)); + break; + case '"': + case '\'': + case '\\': + case '/': + sb.append(c); + break; + default: + throw this.syntaxError("Illegal escape."); + } + break; + default: + if (c == quote){ + return sb.toString(); + } + sb.append(c); + } + } + } + + /** + * Get the text up but not including the specified character or the + * end of line, whichever comes first. + * @param delimiter A delimiter character. + * @return A string. + */ + public String nextTo(char delimiter) throws JSONException{ + StringBuffer sb = new StringBuffer(); + for(;;){ + char c = this.next(); + if (c == delimiter || c == 0 || c == '\n' || c == '\r'){ + if (c != 0){ + this.back(); + } + return sb.toString().trim(); + } + sb.append(c); + } + } + + /** + * Get the text up but not including one of the specified delimiter + * characters or the end of line, whichever comes first. + * @param delimiters A set of delimiter characters. + * @return A string, trimmed. + */ + public String nextTo(String delimiters) throws JSONException{ + char c; + StringBuffer sb = new StringBuffer(); + for(;;){ + c = this.next(); + if (delimiters.indexOf(c) >= 0 || c == 0 || c == '\n' || c == '\r'){ + if (c != 0){ + this.back(); + } + return sb.toString().trim(); + } + sb.append(c); + } + } + + /** + * Get the next value. The value can be a Boolean, Double, Integer, + * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object. + * @throws JSONException If syntax error. + * + * @return An object. + */ + public Object nextValue() throws JSONException{ + char c = this.nextClean(); + String string; + + switch(c){ + case '"': + case '\'': + return this.nextString(c); + case '{': + this.back(); + return new JSONObject(this); + case '[': + this.back(); + return new JSONArray(this); + } + + /* + * Handle unquoted text. This could be the values true, false, or + * null, or it can be a number. An implementation (such as this one) + * is allowed to also accept non-standard forms. + * + * Accumulate characters until we reach the end of the text or a + * formatting character. + */ + + StringBuffer sb = new StringBuffer(); + while(c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0){ + sb.append(c); + c = this.next(); + } + this.back(); + + string = sb.toString().trim(); + if ("".equals(string)){ + throw this.syntaxError("Missing value"); + } + return JSONObject.stringToValue(string); + } + + /** + * Skip characters until the next character is the requested character. + * If the requested character is not found, no characters are skipped. + * @param to A character to skip to. + * @return The requested character, or zero if the requested character + * is not found. + */ + public char skipTo(char to) throws JSONException{ + char c; + try{ + long startIndex = this.index; + long startCharacter = this.character; + long startLine = this.line; + this.reader.mark(1000000); + do{ + c = this.next(); + if (c == 0){ + this.reader.reset(); + this.index = startIndex; + this.character = startCharacter; + this.line = startLine; + return c; + } + }while(c != to); + }catch(IOException exc){ + throw new JSONException(exc); + } + + this.back(); + return c; + } + + /** + * Make a JSONException to signal a syntax error. + * + * @param message The error message. + * @return A JSONException object, suitable for throwing + */ + public JSONException syntaxError(String message){ + return new JSONException(message + this.toString()); + } + + /** + * Make a printable string of this JSONTokener. + * + * @return " at {index} [character {character} line {line}]" + */ + public String toString(){ + return " at " + this.index + " [character " + this.character + " line " + this.line + "]"; + } } diff --git a/src/org/json/JSONWriter.java b/src/org/json/JSONWriter.java index 855b2bdb10de712869a3c1957c182a71e1cd31d4..04e7511ac066766ca2b2dcd47da4af6ee3f24dae 100644 --- a/src/org/json/JSONWriter.java +++ b/src/org/json/JSONWriter.java @@ -57,271 +57,261 @@ SOFTWARE. * @version 2011-11-24 */ public class JSONWriter { - private static final int maxdepth = 200; + private static final int maxdepth = 200; - /** - * The comma flag determines if a comma should be output before the next - * value. - */ - private boolean comma; + /** + * The comma flag determines if a comma should be output before the next + * value. + */ + private boolean comma; - /** - * The current mode. Values: - * 'a' (array), - * 'd' (done), - * 'i' (initial), - * 'k' (key), - * 'o' (object). - */ - protected char mode; + /** + * The current mode. Values: + * 'a' (array), + * 'd' (done), + * 'i' (initial), + * 'k' (key), + * 'o' (object). + */ + protected char mode; - /** - * The object/array stack. - */ - private final JSONObject stack[]; + /** + * The object/array stack. + */ + private final JSONObject stack[]; - /** - * The stack top index. A value of 0 indicates that the stack is empty. - */ - private int top; + /** + * The stack top index. A value of 0 indicates that the stack is empty. + */ + private int top; - /** - * The writer that will receive the output. - */ - protected Writer writer; + /** + * The writer that will receive the output. + */ + protected Writer writer; - /** - * Make a fresh JSONWriter. It can be used to build one JSON text. - */ - public JSONWriter(Writer w) { - this.comma = false; - this.mode = 'i'; - this.stack = new JSONObject[maxdepth]; - this.top = 0; - this.writer = w; - } + /** + * Make a fresh JSONWriter. It can be used to build one JSON text. + */ + public JSONWriter(Writer w){ + this.comma = false; + this.mode = 'i'; + this.stack = new JSONObject[maxdepth]; + this.top = 0; + this.writer = w; + } - /** - * Append a value. - * @param string A string value. - * @return this - * @throws JSONException If the value is out of sequence. - */ - private JSONWriter append(String string) throws JSONException { - if (string == null) { - throw new JSONException("Null pointer"); - } - if (this.mode == 'o' || this.mode == 'a') { - try { - if (this.comma && this.mode == 'a') { - this.writer.write(','); - } - this.writer.write(string); - } catch (IOException e) { - throw new JSONException(e); - } - if (this.mode == 'o') { - this.mode = 'k'; - } - this.comma = true; - return this; - } - throw new JSONException("Value out of sequence."); - } + /** + * Append a value. + * @param string A string value. + * @return this + * @throws JSONException If the value is out of sequence. + */ + private JSONWriter append(String string) throws JSONException{ + if (string == null){ + throw new JSONException("Null pointer"); + } + if (this.mode == 'o' || this.mode == 'a'){ + try{ + if (this.comma && this.mode == 'a'){ + this.writer.write(','); + } + this.writer.write(string); + }catch(IOException e){ + throw new JSONException(e); + } + if (this.mode == 'o'){ + this.mode = 'k'; + } + this.comma = true; + return this; + } + throw new JSONException("Value out of sequence."); + } - /** - * Begin appending a new array. All values until the balancing - * <code>endArray</code> will be appended to this array. The - * <code>endArray</code> method must be called to mark the array's end. - * @return this - * @throws JSONException If the nesting is too deep, or if the object is - * started in the wrong place (for example as a key or after the end of the - * outermost array or object). - */ - public JSONWriter array() throws JSONException { - if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') { - this.push(null); - this.append("["); - this.comma = false; - return this; - } - throw new JSONException("Misplaced array."); - } + /** + * Begin appending a new array. All values until the balancing + * <code>endArray</code> will be appended to this array. The + * <code>endArray</code> method must be called to mark the array's end. + * @return this + * @throws JSONException If the nesting is too deep, or if the object is + * started in the wrong place (for example as a key or after the end of the + * outermost array or object). + */ + public JSONWriter array() throws JSONException{ + if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a'){ + this.push(null); + this.append("["); + this.comma = false; + return this; + } + throw new JSONException("Misplaced array."); + } - /** - * End something. - * @param mode Mode - * @param c Closing character - * @return this - * @throws JSONException If unbalanced. - */ - private JSONWriter end(char mode, char c) throws JSONException { - if (this.mode != mode) { - throw new JSONException(mode == 'a' - ? "Misplaced endArray." - : "Misplaced endObject."); - } - this.pop(mode); - try { - this.writer.write(c); - } catch (IOException e) { - throw new JSONException(e); - } - this.comma = true; - return this; - } + /** + * End something. + * @param mode Mode + * @param c Closing character + * @return this + * @throws JSONException If unbalanced. + */ + private JSONWriter end(char mode, char c) throws JSONException{ + if (this.mode != mode){ + throw new JSONException(mode == 'a' ? "Misplaced endArray." : "Misplaced endObject."); + } + this.pop(mode); + try{ + this.writer.write(c); + }catch(IOException e){ + throw new JSONException(e); + } + this.comma = true; + return this; + } - /** - * End an array. This method most be called to balance calls to - * <code>array</code>. - * @return this - * @throws JSONException If incorrectly nested. - */ - public JSONWriter endArray() throws JSONException { - return this.end('a', ']'); - } + /** + * End an array. This method most be called to balance calls to + * <code>array</code>. + * @return this + * @throws JSONException If incorrectly nested. + */ + public JSONWriter endArray() throws JSONException{ + return this.end('a', ']'); + } - /** - * End an object. This method most be called to balance calls to - * <code>object</code>. - * @return this - * @throws JSONException If incorrectly nested. - */ - public JSONWriter endObject() throws JSONException { - return this.end('k', '}'); - } + /** + * End an object. This method most be called to balance calls to + * <code>object</code>. + * @return this + * @throws JSONException If incorrectly nested. + */ + public JSONWriter endObject() throws JSONException{ + return this.end('k', '}'); + } - /** - * Append a key. The key will be associated with the next value. In an - * object, every value must be preceded by a key. - * @param string A key string. - * @return this - * @throws JSONException If the key is out of place. For example, keys - * do not belong in arrays or if the key is null. - */ - public JSONWriter key(String string) throws JSONException { - if (string == null) { - throw new JSONException("Null key."); - } - if (this.mode == 'k') { - try { - this.stack[this.top - 1].putOnce(string, Boolean.TRUE); - if (this.comma) { - this.writer.write(','); - } - this.writer.write(JSONObject.quote(string)); - this.writer.write(':'); - this.comma = false; - this.mode = 'o'; - return this; - } catch (IOException e) { - throw new JSONException(e); - } - } - throw new JSONException("Misplaced key."); - } + /** + * Append a key. The key will be associated with the next value. In an + * object, every value must be preceded by a key. + * @param string A key string. + * @return this + * @throws JSONException If the key is out of place. For example, keys + * do not belong in arrays or if the key is null. + */ + public JSONWriter key(String string) throws JSONException{ + if (string == null){ + throw new JSONException("Null key."); + } + if (this.mode == 'k'){ + try{ + this.stack[this.top - 1].putOnce(string, Boolean.TRUE); + if (this.comma){ + this.writer.write(','); + } + this.writer.write(JSONObject.quote(string)); + this.writer.write(':'); + this.comma = false; + this.mode = 'o'; + return this; + }catch(IOException e){ + throw new JSONException(e); + } + } + throw new JSONException("Misplaced key."); + } + /** + * Begin appending a new object. All keys and values until the balancing + * <code>endObject</code> will be appended to this object. The + * <code>endObject</code> method must be called to mark the object's end. + * @return this + * @throws JSONException If the nesting is too deep, or if the object is + * started in the wrong place (for example as a key or after the end of the + * outermost array or object). + */ + public JSONWriter object() throws JSONException{ + if (this.mode == 'i'){ + this.mode = 'o'; + } + if (this.mode == 'o' || this.mode == 'a'){ + this.append("{"); + this.push(new JSONObject()); + this.comma = false; + return this; + } + throw new JSONException("Misplaced object."); - /** - * Begin appending a new object. All keys and values until the balancing - * <code>endObject</code> will be appended to this object. The - * <code>endObject</code> method must be called to mark the object's end. - * @return this - * @throws JSONException If the nesting is too deep, or if the object is - * started in the wrong place (for example as a key or after the end of the - * outermost array or object). - */ - public JSONWriter object() throws JSONException { - if (this.mode == 'i') { - this.mode = 'o'; - } - if (this.mode == 'o' || this.mode == 'a') { - this.append("{"); - this.push(new JSONObject()); - this.comma = false; - return this; - } - throw new JSONException("Misplaced object."); + } - } + /** + * Pop an array or object scope. + * @param c The scope to close. + * @throws JSONException If nesting is wrong. + */ + private void pop(char c) throws JSONException{ + if (this.top <= 0){ + throw new JSONException("Nesting error."); + } + char m = this.stack[this.top - 1] == null ? 'a' : 'k'; + if (m != c){ + throw new JSONException("Nesting error."); + } + this.top -= 1; + this.mode = this.top == 0 ? 'd' : this.stack[this.top - 1] == null ? 'a' : 'k'; + } + /** + * Push an array or object scope. + * @param c The scope to open. + * @throws JSONException If nesting is too deep. + */ + private void push(JSONObject jo) throws JSONException{ + if (this.top >= maxdepth){ + throw new JSONException("Nesting too deep."); + } + this.stack[this.top] = jo; + this.mode = jo == null ? 'a' : 'k'; + this.top += 1; + } - /** - * Pop an array or object scope. - * @param c The scope to close. - * @throws JSONException If nesting is wrong. - */ - private void pop(char c) throws JSONException { - if (this.top <= 0) { - throw new JSONException("Nesting error."); - } - char m = this.stack[this.top - 1] == null ? 'a' : 'k'; - if (m != c) { - throw new JSONException("Nesting error."); - } - this.top -= 1; - this.mode = this.top == 0 - ? 'd' - : this.stack[this.top - 1] == null - ? 'a' - : 'k'; - } + /** + * Append either the value <code>true</code> or the value + * <code>false</code>. + * @param b A boolean. + * @return this + * @throws JSONException + */ + public JSONWriter value(boolean b) throws JSONException{ + return this.append(b ? "true" : "false"); + } - /** - * Push an array or object scope. - * @param c The scope to open. - * @throws JSONException If nesting is too deep. - */ - private void push(JSONObject jo) throws JSONException { - if (this.top >= maxdepth) { - throw new JSONException("Nesting too deep."); - } - this.stack[this.top] = jo; - this.mode = jo == null ? 'a' : 'k'; - this.top += 1; - } + /** + * Append a double value. + * @param d A double. + * @return this + * @throws JSONException If the number is not finite. + */ + public JSONWriter value(double d) throws JSONException{ + return this.value(new Double(d)); + } + /** + * Append a long value. + * @param l A long. + * @return this + * @throws JSONException + */ + public JSONWriter value(long l) throws JSONException{ + return this.append(Long.toString(l)); + } - /** - * Append either the value <code>true</code> or the value - * <code>false</code>. - * @param b A boolean. - * @return this - * @throws JSONException - */ - public JSONWriter value(boolean b) throws JSONException { - return this.append(b ? "true" : "false"); - } - - /** - * Append a double value. - * @param d A double. - * @return this - * @throws JSONException If the number is not finite. - */ - public JSONWriter value(double d) throws JSONException { - return this.value(new Double(d)); - } - - /** - * Append a long value. - * @param l A long. - * @return this - * @throws JSONException - */ - public JSONWriter value(long l) throws JSONException { - return this.append(Long.toString(l)); - } - - - /** - * Append an object value. - * @param object The object to append. It can be null, or a Boolean, Number, - * String, JSONObject, or JSONArray, or an object that implements JSONString. - * @return this - * @throws JSONException If the value is out of sequence. - */ - public JSONWriter value(Object object) throws JSONException { - return this.append(JSONObject.valueToString(object)); - } + /** + * Append an object value. + * @param object The object to append. It can be null, or a Boolean, Number, + * String, JSONObject, or JSONArray, or an object that implements JSONString. + * @return this + * @throws JSONException If the value is out of sequence. + */ + public JSONWriter value(Object object) throws JSONException{ + return this.append(JSONObject.valueToString(object)); + } } diff --git a/src/org/json/Json4Uws.java b/src/org/json/Json4Uws.java index c4986f7c0668234a0dbd2fc285bbd5b72c24bef2..bfa25e3391b8b4958242832a0be8cb3b7d4507ff 100644 --- a/src/org/json/Json4Uws.java +++ b/src/org/json/Json4Uws.java @@ -39,7 +39,9 @@ import uws.service.UWSUrl; */ public final class Json4Uws { - private Json4Uws(){ ; } + private Json4Uws(){ + ; + } /** * Gets the JSON representation of the given UWS. @@ -47,7 +49,7 @@ public final class Json4Uws { * @return Its JSON representation. * @throws JSONException If there is an error while building the JSON object. */ - public final static JSONObject getJson(final UWS uws) throws JSONException { + public final static JSONObject getJson(final UWS uws) throws JSONException{ JSONObject json = new JSONObject(); if (uws != null){ json.put("name", uws.getName()); @@ -75,7 +77,7 @@ public final class Json4Uws { * @return Its JSON representation. * @throws JSONException If there is an error while building the JSON object. */ - public final static JSONObject getJson(final JobList jobsList, final JobOwner owner) throws JSONException { + public final static JSONObject getJson(final JobList jobsList, final JobOwner owner) throws JSONException{ JSONObject json = new JSONObject(); if (jobsList != null){ json.put("name", jobsList.getName()); @@ -99,7 +101,7 @@ public final class Json4Uws { * @return Its JSON representation. * @throws JSONException If there is an error while building the JSON object. */ - public final static JSONObject getJson(final UWSJob job) throws JSONException { + public final static JSONObject getJson(final UWSJob job) throws JSONException{ return getJson(job, null, false); } @@ -112,7 +114,7 @@ public final class Json4Uws { * @return Its JSON representation. * @throws JSONException If there is an error while building the JSON object. */ - public final static JSONObject getJson(final UWSJob job, final UWSUrl jobsListUrl, final boolean reference) throws JSONException { + public final static JSONObject getJson(final UWSJob job, final UWSUrl jobsListUrl, final boolean reference) throws JSONException{ JSONObject json = new JSONObject(); if (job != null){ json.put(UWSJob.PARAM_JOB_ID, job.getJobId()); @@ -148,7 +150,7 @@ public final class Json4Uws { * @return The JSON representation of its parameters. * @throws JSONException If there is an error while building the JSON object. */ - public final static JSONObject getJobParamsJson(final UWSJob job) throws JSONException { + public final static JSONObject getJobParamsJson(final UWSJob job) throws JSONException{ JSONObject json = new JSONObject(); if (job != null){ for(String name : job.getAdditionalParameters()) @@ -163,7 +165,7 @@ public final class Json4Uws { * @return The JSON representation of its results. * @throws JSONException If there is an error while building the JSON array. */ - public final static JSONArray getJobResultsJson(final UWSJob job) throws JSONException { + public final static JSONArray getJobResultsJson(final UWSJob job) throws JSONException{ JSONArray json = new JSONArray(); if (job != null){ Iterator<Result> it = job.getResults(); @@ -182,7 +184,7 @@ public final class Json4Uws { * @return Its JSON representation. * @throws JSONException If there is an error while building the JSON object. */ - public final static JSONObject getJobResultJson(final Result r) throws JSONException { + public final static JSONObject getJobResultJson(final Result r) throws JSONException{ JSONObject resultJson = new JSONObject(); if (r != null){ resultJson.put("id", r.getId()); @@ -202,7 +204,7 @@ public final class Json4Uws { * @return Its JSON representation. * @throws JSONException If there is an error while building the JSON object. */ - public final static JSONObject getJson(final ErrorSummary error) throws JSONException { + public final static JSONObject getJson(final ErrorSummary error) throws JSONException{ JSONObject errorJson = new JSONObject(); if (error != null){ errorJson.put("type", error.getType()); @@ -220,7 +222,7 @@ public final class Json4Uws { * @return Its JSON representation. * @throws JSONException If there is an error while building the JSON object. */ - public final static JSONObject getJson(final String key, final long value) throws JSONException { + public final static JSONObject getJson(final String key, final long value) throws JSONException{ JSONObject json = new JSONObject(); if (key != null && !key.trim().isEmpty()) json.put(key, value); @@ -234,7 +236,7 @@ public final class Json4Uws { * @return Its JSON representation. * @throws JSONException If there is an error while building the JSON object. */ - public final static JSONObject getJson(final String key, final String value) throws JSONException { + public final static JSONObject getJson(final String key, final String value) throws JSONException{ JSONObject json = new JSONObject(); if (key != null && !key.trim().isEmpty()) json.put(key, value); diff --git a/src/org/json/XML.java b/src/org/json/XML.java index 82455b33772b87ad9b92f3ccba3ec17d24183ec6..e9e429f52b7deeac0f210612a6d058a2578c112a 100644 --- a/src/org/json/XML.java +++ b/src/org/json/XML.java @@ -26,7 +26,6 @@ SOFTWARE. import java.util.Iterator; - /** * This provides static methods to convert an XML text into a JSONObject, * and to covert a JSONObject into an XML text. @@ -35,474 +34,460 @@ import java.util.Iterator; */ public class XML { - /** The Character '&'. */ - public static final Character AMP = new Character('&'); - - /** The Character '''. */ - public static final Character APOS = new Character('\''); - - /** The Character '!'. */ - public static final Character BANG = new Character('!'); - - /** The Character '='. */ - public static final Character EQ = new Character('='); - - /** The Character '>'. */ - public static final Character GT = new Character('>'); - - /** The Character '<'. */ - public static final Character LT = new Character('<'); - - /** The Character '?'. */ - public static final Character QUEST = new Character('?'); - - /** The Character '"'. */ - public static final Character QUOT = new Character('"'); - - /** The Character '/'. */ - public static final Character SLASH = new Character('/'); - - /** - * Replace special characters with XML escapes: - * <pre> - * & <small>(ampersand)</small> is replaced by &amp; - * < <small>(less than)</small> is replaced by &lt; - * > <small>(greater than)</small> is replaced by &gt; - * " <small>(double quote)</small> is replaced by &quot; - * </pre> - * @param string The string to be escaped. - * @return The escaped string. - */ - public static String escape(String string) { - StringBuffer sb = new StringBuffer(); - for (int i = 0, length = string.length(); i < length; i++) { - char c = string.charAt(i); - switch (c) { - case '&': - sb.append("&"); - break; - case '<': - sb.append("<"); - break; - case '>': - sb.append(">"); - break; - case '"': - sb.append("""); - break; - case '\'': - sb.append("'"); - break; - default: - sb.append(c); - } - } - return sb.toString(); - } - - /** - * Throw an exception if the string contains whitespace. - * Whitespace is not allowed in tagNames and attributes. - * @param string - * @throws JSONException - */ - public static void noSpace(String string) throws JSONException { - int i, length = string.length(); - if (length == 0) { - throw new JSONException("Empty string."); - } - for (i = 0; i < length; i += 1) { - if (Character.isWhitespace(string.charAt(i))) { - throw new JSONException("'" + string + - "' contains a space character."); - } - } - } - - /** - * Scan the content following the named tag, attaching it to the context. - * @param x The XMLTokener containing the source string. - * @param context The JSONObject that will include the new material. - * @param name The tag name. - * @return true if the close tag is processed. - * @throws JSONException - */ - private static boolean parse(XMLTokener x, JSONObject context, - String name) throws JSONException { - char c; - int i; - JSONObject jsonobject = null; - String string; - String tagName; - Object token; - -// Test for and skip past these forms: -// <!-- ... --> -// <! ... > -// <![ ... ]]> -// <? ... ?> -// Report errors for these forms: -// <> -// <= -// << - - token = x.nextToken(); - -// <! - - if (token == BANG) { - c = x.next(); - if (c == '-') { - if (x.next() == '-') { - x.skipPast("-->"); - return false; - } - x.back(); - } else if (c == '[') { - token = x.nextToken(); - if ("CDATA".equals(token)) { - if (x.next() == '[') { - string = x.nextCDATA(); - if (string.length() > 0) { - context.accumulate("content", string); - } - return false; - } - } - throw x.syntaxError("Expected 'CDATA['"); - } - i = 1; - do { - token = x.nextMeta(); - if (token == null) { - throw x.syntaxError("Missing '>' after '<!'."); - } else if (token == LT) { - i += 1; - } else if (token == GT) { - i -= 1; - } - } while (i > 0); - return false; - } else if (token == QUEST) { - -// <? - - x.skipPast("?>"); - return false; - } else if (token == SLASH) { - -// Close tag </ - - token = x.nextToken(); - if (name == null) { - throw x.syntaxError("Mismatched close tag " + token); - } - if (!token.equals(name)) { - throw x.syntaxError("Mismatched " + name + " and " + token); - } - if (x.nextToken() != GT) { - throw x.syntaxError("Misshaped close tag"); - } - return true; - - } else if (token instanceof Character) { - throw x.syntaxError("Misshaped tag"); - -// Open tag < - - } else { - tagName = (String)token; - token = null; - jsonobject = new JSONObject(); - for (;;) { - if (token == null) { - token = x.nextToken(); - } - -// attribute = value - - if (token instanceof String) { - string = (String)token; - token = x.nextToken(); - if (token == EQ) { - token = x.nextToken(); - if (!(token instanceof String)) { - throw x.syntaxError("Missing value"); - } - jsonobject.accumulate(string, - XML.stringToValue((String)token)); - token = null; - } else { - jsonobject.accumulate(string, ""); - } - -// Empty tag <.../> - - } else if (token == SLASH) { - if (x.nextToken() != GT) { - throw x.syntaxError("Misshaped tag"); - } - if (jsonobject.length() > 0) { - context.accumulate(tagName, jsonobject); - } else { - context.accumulate(tagName, ""); - } - return false; - -// Content, between <...> and </...> - - } else if (token == GT) { - for (;;) { - token = x.nextContent(); - if (token == null) { - if (tagName != null) { - throw x.syntaxError("Unclosed tag " + tagName); - } - return false; - } else if (token instanceof String) { - string = (String)token; - if (string.length() > 0) { - jsonobject.accumulate("content", - XML.stringToValue(string)); - } - -// Nested element - - } else if (token == LT) { - if (parse(x, jsonobject, tagName)) { - if (jsonobject.length() == 0) { - context.accumulate(tagName, ""); - } else if (jsonobject.length() == 1 && - jsonobject.opt("content") != null) { - context.accumulate(tagName, - jsonobject.opt("content")); - } else { - context.accumulate(tagName, jsonobject); - } - return false; - } - } - } - } else { - throw x.syntaxError("Misshaped tag"); - } - } - } - } - - - /** - * Try to convert a string into a number, boolean, or null. If the string - * can't be converted, return the string. This is much less ambitious than - * JSONObject.stringToValue, especially because it does not attempt to - * convert plus forms, octal forms, hex forms, or E forms lacking decimal - * points. - * @param string A String. - * @return A simple JSON value. - */ - public static Object stringToValue(String string) { - if ("".equals(string)) { - return string; - } - if ("true".equalsIgnoreCase(string)) { - return Boolean.TRUE; - } - if ("false".equalsIgnoreCase(string)) { - return Boolean.FALSE; - } - if ("null".equalsIgnoreCase(string)) { - return JSONObject.NULL; - } - if ("0".equals(string)) { - return new Integer(0); - } - -// If it might be a number, try converting it. If that doesn't work, -// return the string. - - try { - char initial = string.charAt(0); - boolean negative = false; - if (initial == '-') { - initial = string.charAt(1); - negative = true; - } - if (initial == '0' && string.charAt(negative ? 2 : 1) == '0') { - return string; - } - if ((initial >= '0' && initial <= '9')) { - if (string.indexOf('.') >= 0) { - return Double.valueOf(string); - } else if (string.indexOf('e') < 0 && string.indexOf('E') < 0) { - Long myLong = new Long(string); - if (myLong.longValue() == myLong.intValue()) { - return new Integer(myLong.intValue()); - } else { - return myLong; - } - } - } - } catch (Exception ignore) { - } - return string; - } - - - /** - * Convert a well-formed (but not necessarily valid) XML string into a - * JSONObject. Some information may be lost in this transformation - * because JSON is a data format and XML is a document format. XML uses - * elements, attributes, and content text, while JSON uses unordered - * collections of name/value pairs and arrays of values. JSON does not - * does not like to distinguish between elements and attributes. - * Sequences of similar elements are represented as JSONArrays. Content - * text may be placed in a "content" member. Comments, prologs, DTDs, and - * <code><[ [ ]]></code> are ignored. - * @param string The source string. - * @return A JSONObject containing the structured data from the XML string. - * @throws JSONException - */ - public static JSONObject toJSONObject(String string) throws JSONException { - JSONObject jo = new JSONObject(); - XMLTokener x = new XMLTokener(string); - while (x.more() && x.skipPast("<")) { - parse(x, jo, null); - } - return jo; - } - - - /** - * Convert a JSONObject into a well-formed, element-normal XML string. - * @param object A JSONObject. - * @return A string. - * @throws JSONException - */ - public static String toString(Object object) throws JSONException { - return toString(object, null); - } - - - /** - * Convert a JSONObject into a well-formed, element-normal XML string. - * @param object A JSONObject. - * @param tagName The optional name of the enclosing tag. - * @return A string. - * @throws JSONException - */ - public static String toString(Object object, String tagName) - throws JSONException { - StringBuffer sb = new StringBuffer(); - int i; - JSONArray ja; - JSONObject jo; - String key; - Iterator keys; - int length; - String string; - Object value; - if (object instanceof JSONObject) { - -// Emit <tagName> - - if (tagName != null) { - sb.append('<'); - sb.append(tagName); - sb.append('>'); - } - -// Loop thru the keys. - - jo = (JSONObject)object; - keys = jo.keys(); - while (keys.hasNext()) { - key = keys.next().toString(); - value = jo.opt(key); - if (value == null) { - value = ""; - } - if (value instanceof String) { - string = (String)value; - } else { - string = null; - } - -// Emit content in body - - if ("content".equals(key)) { - if (value instanceof JSONArray) { - ja = (JSONArray)value; - length = ja.length(); - for (i = 0; i < length; i += 1) { - if (i > 0) { - sb.append('\n'); - } - sb.append(escape(ja.get(i).toString())); - } - } else { - sb.append(escape(value.toString())); - } - -// Emit an array of similar keys - - } else if (value instanceof JSONArray) { - ja = (JSONArray)value; - length = ja.length(); - for (i = 0; i < length; i += 1) { - value = ja.get(i); - if (value instanceof JSONArray) { - sb.append('<'); - sb.append(key); - sb.append('>'); - sb.append(toString(value)); - sb.append("</"); - sb.append(key); - sb.append('>'); - } else { - sb.append(toString(value, key)); - } - } - } else if ("".equals(value)) { - sb.append('<'); - sb.append(key); - sb.append("/>"); - -// Emit a new tag <k> - - } else { - sb.append(toString(value, key)); - } - } - if (tagName != null) { - -// Emit the </tagname> close tag - - sb.append("</"); - sb.append(tagName); - sb.append('>'); - } - return sb.toString(); - -// XML does not have good support for arrays. If an array appears in a place -// where XML is lacking, synthesize an <array> element. - - } else { - if (object.getClass().isArray()) { - object = new JSONArray(object); - } - if (object instanceof JSONArray) { - ja = (JSONArray)object; - length = ja.length(); - for (i = 0; i < length; i += 1) { - sb.append(toString(ja.opt(i), tagName == null ? "array" : tagName)); - } - return sb.toString(); - } else { - string = (object == null) ? "null" : escape(object.toString()); - return (tagName == null) ? "\"" + string + "\"" : - (string.length() == 0) ? "<" + tagName + "/>" : - "<" + tagName + ">" + string + "</" + tagName + ">"; - } - } - } + /** The Character '&'. */ + public static final Character AMP = new Character('&'); + + /** The Character '''. */ + public static final Character APOS = new Character('\''); + + /** The Character '!'. */ + public static final Character BANG = new Character('!'); + + /** The Character '='. */ + public static final Character EQ = new Character('='); + + /** The Character '>'. */ + public static final Character GT = new Character('>'); + + /** The Character '<'. */ + public static final Character LT = new Character('<'); + + /** The Character '?'. */ + public static final Character QUEST = new Character('?'); + + /** The Character '"'. */ + public static final Character QUOT = new Character('"'); + + /** The Character '/'. */ + public static final Character SLASH = new Character('/'); + + /** + * Replace special characters with XML escapes: + * <pre> + * & <small>(ampersand)</small> is replaced by &amp; + * < <small>(less than)</small> is replaced by &lt; + * > <small>(greater than)</small> is replaced by &gt; + * " <small>(double quote)</small> is replaced by &quot; + * </pre> + * @param string The string to be escaped. + * @return The escaped string. + */ + public static String escape(String string){ + StringBuffer sb = new StringBuffer(); + for(int i = 0, length = string.length(); i < length; i++){ + char c = string.charAt(i); + switch(c){ + case '&': + sb.append("&"); + break; + case '<': + sb.append("<"); + break; + case '>': + sb.append(">"); + break; + case '"': + sb.append("""); + break; + case '\'': + sb.append("'"); + break; + default: + sb.append(c); + } + } + return sb.toString(); + } + + /** + * Throw an exception if the string contains whitespace. + * Whitespace is not allowed in tagNames and attributes. + * @param string + * @throws JSONException + */ + public static void noSpace(String string) throws JSONException{ + int i, length = string.length(); + if (length == 0){ + throw new JSONException("Empty string."); + } + for(i = 0; i < length; i += 1){ + if (Character.isWhitespace(string.charAt(i))){ + throw new JSONException("'" + string + "' contains a space character."); + } + } + } + + /** + * Scan the content following the named tag, attaching it to the context. + * @param x The XMLTokener containing the source string. + * @param context The JSONObject that will include the new material. + * @param name The tag name. + * @return true if the close tag is processed. + * @throws JSONException + */ + private static boolean parse(XMLTokener x, JSONObject context, String name) throws JSONException{ + char c; + int i; + JSONObject jsonobject = null; + String string; + String tagName; + Object token; + + // Test for and skip past these forms: + // <!-- ... --> + // <! ... > + // <![ ... ]]> + // <? ... ?> + // Report errors for these forms: + // <> + // <= + // << + + token = x.nextToken(); + + // <! + + if (token == BANG){ + c = x.next(); + if (c == '-'){ + if (x.next() == '-'){ + x.skipPast("-->"); + return false; + } + x.back(); + }else if (c == '['){ + token = x.nextToken(); + if ("CDATA".equals(token)){ + if (x.next() == '['){ + string = x.nextCDATA(); + if (string.length() > 0){ + context.accumulate("content", string); + } + return false; + } + } + throw x.syntaxError("Expected 'CDATA['"); + } + i = 1; + do{ + token = x.nextMeta(); + if (token == null){ + throw x.syntaxError("Missing '>' after '<!'."); + }else if (token == LT){ + i += 1; + }else if (token == GT){ + i -= 1; + } + }while(i > 0); + return false; + }else if (token == QUEST){ + + // <? + + x.skipPast("?>"); + return false; + }else if (token == SLASH){ + + // Close tag </ + + token = x.nextToken(); + if (name == null){ + throw x.syntaxError("Mismatched close tag " + token); + } + if (!token.equals(name)){ + throw x.syntaxError("Mismatched " + name + " and " + token); + } + if (x.nextToken() != GT){ + throw x.syntaxError("Misshaped close tag"); + } + return true; + + }else if (token instanceof Character){ + throw x.syntaxError("Misshaped tag"); + + // Open tag < + + }else{ + tagName = (String)token; + token = null; + jsonobject = new JSONObject(); + for(;;){ + if (token == null){ + token = x.nextToken(); + } + + // attribute = value + + if (token instanceof String){ + string = (String)token; + token = x.nextToken(); + if (token == EQ){ + token = x.nextToken(); + if (!(token instanceof String)){ + throw x.syntaxError("Missing value"); + } + jsonobject.accumulate(string, XML.stringToValue((String)token)); + token = null; + }else{ + jsonobject.accumulate(string, ""); + } + + // Empty tag <.../> + + }else if (token == SLASH){ + if (x.nextToken() != GT){ + throw x.syntaxError("Misshaped tag"); + } + if (jsonobject.length() > 0){ + context.accumulate(tagName, jsonobject); + }else{ + context.accumulate(tagName, ""); + } + return false; + + // Content, between <...> and </...> + + }else if (token == GT){ + for(;;){ + token = x.nextContent(); + if (token == null){ + if (tagName != null){ + throw x.syntaxError("Unclosed tag " + tagName); + } + return false; + }else if (token instanceof String){ + string = (String)token; + if (string.length() > 0){ + jsonobject.accumulate("content", XML.stringToValue(string)); + } + + // Nested element + + }else if (token == LT){ + if (parse(x, jsonobject, tagName)){ + if (jsonobject.length() == 0){ + context.accumulate(tagName, ""); + }else if (jsonobject.length() == 1 && jsonobject.opt("content") != null){ + context.accumulate(tagName, jsonobject.opt("content")); + }else{ + context.accumulate(tagName, jsonobject); + } + return false; + } + } + } + }else{ + throw x.syntaxError("Misshaped tag"); + } + } + } + } + + /** + * Try to convert a string into a number, boolean, or null. If the string + * can't be converted, return the string. This is much less ambitious than + * JSONObject.stringToValue, especially because it does not attempt to + * convert plus forms, octal forms, hex forms, or E forms lacking decimal + * points. + * @param string A String. + * @return A simple JSON value. + */ + public static Object stringToValue(String string){ + if ("".equals(string)){ + return string; + } + if ("true".equalsIgnoreCase(string)){ + return Boolean.TRUE; + } + if ("false".equalsIgnoreCase(string)){ + return Boolean.FALSE; + } + if ("null".equalsIgnoreCase(string)){ + return JSONObject.NULL; + } + if ("0".equals(string)){ + return new Integer(0); + } + + // If it might be a number, try converting it. If that doesn't work, + // return the string. + + try{ + char initial = string.charAt(0); + boolean negative = false; + if (initial == '-'){ + initial = string.charAt(1); + negative = true; + } + if (initial == '0' && string.charAt(negative ? 2 : 1) == '0'){ + return string; + } + if ((initial >= '0' && initial <= '9')){ + if (string.indexOf('.') >= 0){ + return Double.valueOf(string); + }else if (string.indexOf('e') < 0 && string.indexOf('E') < 0){ + Long myLong = new Long(string); + if (myLong.longValue() == myLong.intValue()){ + return new Integer(myLong.intValue()); + }else{ + return myLong; + } + } + } + }catch(Exception ignore){} + return string; + } + + /** + * Convert a well-formed (but not necessarily valid) XML string into a + * JSONObject. Some information may be lost in this transformation + * because JSON is a data format and XML is a document format. XML uses + * elements, attributes, and content text, while JSON uses unordered + * collections of name/value pairs and arrays of values. JSON does not + * does not like to distinguish between elements and attributes. + * Sequences of similar elements are represented as JSONArrays. Content + * text may be placed in a "content" member. Comments, prologs, DTDs, and + * <code><[ [ ]]></code> are ignored. + * @param string The source string. + * @return A JSONObject containing the structured data from the XML string. + * @throws JSONException + */ + public static JSONObject toJSONObject(String string) throws JSONException{ + JSONObject jo = new JSONObject(); + XMLTokener x = new XMLTokener(string); + while(x.more() && x.skipPast("<")){ + parse(x, jo, null); + } + return jo; + } + + /** + * Convert a JSONObject into a well-formed, element-normal XML string. + * @param object A JSONObject. + * @return A string. + * @throws JSONException + */ + public static String toString(Object object) throws JSONException{ + return toString(object, null); + } + + /** + * Convert a JSONObject into a well-formed, element-normal XML string. + * @param object A JSONObject. + * @param tagName The optional name of the enclosing tag. + * @return A string. + * @throws JSONException + */ + public static String toString(Object object, String tagName) throws JSONException{ + StringBuffer sb = new StringBuffer(); + int i; + JSONArray ja; + JSONObject jo; + String key; + Iterator keys; + int length; + String string; + Object value; + if (object instanceof JSONObject){ + + // Emit <tagName> + + if (tagName != null){ + sb.append('<'); + sb.append(tagName); + sb.append('>'); + } + + // Loop thru the keys. + + jo = (JSONObject)object; + keys = jo.keys(); + while(keys.hasNext()){ + key = keys.next().toString(); + value = jo.opt(key); + if (value == null){ + value = ""; + } + if (value instanceof String){ + string = (String)value; + }else{ + string = null; + } + + // Emit content in body + + if ("content".equals(key)){ + if (value instanceof JSONArray){ + ja = (JSONArray)value; + length = ja.length(); + for(i = 0; i < length; i += 1){ + if (i > 0){ + sb.append('\n'); + } + sb.append(escape(ja.get(i).toString())); + } + }else{ + sb.append(escape(value.toString())); + } + + // Emit an array of similar keys + + }else if (value instanceof JSONArray){ + ja = (JSONArray)value; + length = ja.length(); + for(i = 0; i < length; i += 1){ + value = ja.get(i); + if (value instanceof JSONArray){ + sb.append('<'); + sb.append(key); + sb.append('>'); + sb.append(toString(value)); + sb.append("</"); + sb.append(key); + sb.append('>'); + }else{ + sb.append(toString(value, key)); + } + } + }else if ("".equals(value)){ + sb.append('<'); + sb.append(key); + sb.append("/>"); + + // Emit a new tag <k> + + }else{ + sb.append(toString(value, key)); + } + } + if (tagName != null){ + + // Emit the </tagname> close tag + + sb.append("</"); + sb.append(tagName); + sb.append('>'); + } + return sb.toString(); + + // XML does not have good support for arrays. If an array appears in a place + // where XML is lacking, synthesize an <array> element. + + }else{ + if (object.getClass().isArray()){ + object = new JSONArray(object); + } + if (object instanceof JSONArray){ + ja = (JSONArray)object; + length = ja.length(); + for(i = 0; i < length; i += 1){ + sb.append(toString(ja.opt(i), tagName == null ? "array" : tagName)); + } + return sb.toString(); + }else{ + string = (object == null) ? "null" : escape(object.toString()); + return (tagName == null) ? "\"" + string + "\"" : (string.length() == 0) ? "<" + tagName + "/>" : "<" + tagName + ">" + string + "</" + tagName + ">"; + } + } + } } \ No newline at end of file diff --git a/src/org/json/XMLTokener.java b/src/org/json/XMLTokener.java index 07574b09298f52e2e0ce2b7d3f46ab6de2445c02..400d7fa8f4fc5edd262c34ce048bb7cb83e79546 100644 --- a/src/org/json/XMLTokener.java +++ b/src/org/json/XMLTokener.java @@ -32,334 +32,327 @@ SOFTWARE. */ public class XMLTokener extends JSONTokener { + /** The table of entity values. It initially contains Character values for + * amp, apos, gt, lt, quot. + */ + public static final java.util.HashMap entity; - /** The table of entity values. It initially contains Character values for - * amp, apos, gt, lt, quot. - */ - public static final java.util.HashMap entity; + static{ + entity = new java.util.HashMap(8); + entity.put("amp", XML.AMP); + entity.put("apos", XML.APOS); + entity.put("gt", XML.GT); + entity.put("lt", XML.LT); + entity.put("quot", XML.QUOT); + } - static { - entity = new java.util.HashMap(8); - entity.put("amp", XML.AMP); - entity.put("apos", XML.APOS); - entity.put("gt", XML.GT); - entity.put("lt", XML.LT); - entity.put("quot", XML.QUOT); - } + /** + * Construct an XMLTokener from a string. + * @param s A source string. + */ + public XMLTokener(String s){ + super(s); + } - /** - * Construct an XMLTokener from a string. - * @param s A source string. - */ - public XMLTokener(String s) { - super(s); - } + /** + * Get the text in the CDATA block. + * @return The string up to the <code>]]></code>. + * @throws JSONException If the <code>]]></code> is not found. + */ + public String nextCDATA() throws JSONException{ + char c; + int i; + StringBuffer sb = new StringBuffer(); + for(;;){ + c = next(); + if (end()){ + throw syntaxError("Unclosed CDATA"); + } + sb.append(c); + i = sb.length() - 3; + if (i >= 0 && sb.charAt(i) == ']' && sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>'){ + sb.setLength(i); + return sb.toString(); + } + } + } - /** - * Get the text in the CDATA block. - * @return The string up to the <code>]]></code>. - * @throws JSONException If the <code>]]></code> is not found. - */ - public String nextCDATA() throws JSONException { - char c; - int i; - StringBuffer sb = new StringBuffer(); - for (;;) { - c = next(); - if (end()) { - throw syntaxError("Unclosed CDATA"); - } - sb.append(c); - i = sb.length() - 3; - if (i >= 0 && sb.charAt(i) == ']' && - sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>') { - sb.setLength(i); - return sb.toString(); - } - } - } + /** + * Get the next XML outer token, trimming whitespace. There are two kinds + * of tokens: the '<' character which begins a markup tag, and the content + * text between markup tags. + * + * @return A string, or a '<' Character, or null if there is no more + * source text. + * @throws JSONException + */ + public Object nextContent() throws JSONException{ + char c; + StringBuffer sb; + do{ + c = next(); + }while(Character.isWhitespace(c)); + if (c == 0){ + return null; + } + if (c == '<'){ + return XML.LT; + } + sb = new StringBuffer(); + for(;;){ + if (c == '<' || c == 0){ + back(); + return sb.toString().trim(); + } + if (c == '&'){ + sb.append(nextEntity(c)); + }else{ + sb.append(c); + } + c = next(); + } + } + /** + * Return the next entity. These entities are translated to Characters: + * <code>& ' > < "</code>. + * @param ampersand An ampersand character. + * @return A Character or an entity String if the entity is not recognized. + * @throws JSONException If missing ';' in XML entity. + */ + public Object nextEntity(char ampersand) throws JSONException{ + StringBuffer sb = new StringBuffer(); + for(;;){ + char c = next(); + if (Character.isLetterOrDigit(c) || c == '#'){ + sb.append(Character.toLowerCase(c)); + }else if (c == ';'){ + break; + }else{ + throw syntaxError("Missing ';' in XML entity: &" + sb); + } + } + String string = sb.toString(); + Object object = entity.get(string); + return object != null ? object : ampersand + string + ";"; + } - /** - * Get the next XML outer token, trimming whitespace. There are two kinds - * of tokens: the '<' character which begins a markup tag, and the content - * text between markup tags. - * - * @return A string, or a '<' Character, or null if there is no more - * source text. - * @throws JSONException - */ - public Object nextContent() throws JSONException { - char c; - StringBuffer sb; - do { - c = next(); - } while (Character.isWhitespace(c)); - if (c == 0) { - return null; - } - if (c == '<') { - return XML.LT; - } - sb = new StringBuffer(); - for (;;) { - if (c == '<' || c == 0) { - back(); - return sb.toString().trim(); - } - if (c == '&') { - sb.append(nextEntity(c)); - } else { - sb.append(c); - } - c = next(); - } - } + /** + * Returns the next XML meta token. This is used for skipping over <!...> + * and <?...?> structures. + * @return Syntax characters (<code>< > / = ! ?</code>) are returned as + * Character, and strings and names are returned as Boolean. We don't care + * what the values actually are. + * @throws JSONException If a string is not properly closed or if the XML + * is badly structured. + */ + public Object nextMeta() throws JSONException{ + char c; + char q; + do{ + c = next(); + }while(Character.isWhitespace(c)); + switch(c){ + case 0: + throw syntaxError("Misshaped meta tag"); + case '<': + return XML.LT; + case '>': + return XML.GT; + case '/': + return XML.SLASH; + case '=': + return XML.EQ; + case '!': + return XML.BANG; + case '?': + return XML.QUEST; + case '"': + case '\'': + q = c; + for(;;){ + c = next(); + if (c == 0){ + throw syntaxError("Unterminated string"); + } + if (c == q){ + return Boolean.TRUE; + } + } + default: + for(;;){ + c = next(); + if (Character.isWhitespace(c)){ + return Boolean.TRUE; + } + switch(c){ + case 0: + case '<': + case '>': + case '/': + case '=': + case '!': + case '?': + case '"': + case '\'': + back(); + return Boolean.TRUE; + } + } + } + } + /** + * Get the next XML Token. These tokens are found inside of angle + * brackets. It may be one of these characters: <code>/ > = ! ?</code> or it + * may be a string wrapped in single quotes or double quotes, or it may be a + * name. + * @return a String or a Character. + * @throws JSONException If the XML is not well formed. + */ + public Object nextToken() throws JSONException{ + char c; + char q; + StringBuffer sb; + do{ + c = next(); + }while(Character.isWhitespace(c)); + switch(c){ + case 0: + throw syntaxError("Misshaped element"); + case '<': + throw syntaxError("Misplaced '<'"); + case '>': + return XML.GT; + case '/': + return XML.SLASH; + case '=': + return XML.EQ; + case '!': + return XML.BANG; + case '?': + return XML.QUEST; - /** - * Return the next entity. These entities are translated to Characters: - * <code>& ' > < "</code>. - * @param ampersand An ampersand character. - * @return A Character or an entity String if the entity is not recognized. - * @throws JSONException If missing ';' in XML entity. - */ - public Object nextEntity(char ampersand) throws JSONException { - StringBuffer sb = new StringBuffer(); - for (;;) { - char c = next(); - if (Character.isLetterOrDigit(c) || c == '#') { - sb.append(Character.toLowerCase(c)); - } else if (c == ';') { - break; - } else { - throw syntaxError("Missing ';' in XML entity: &" + sb); - } - } - String string = sb.toString(); - Object object = entity.get(string); - return object != null ? object : ampersand + string + ";"; - } + // Quoted string + case '"': + case '\'': + q = c; + sb = new StringBuffer(); + for(;;){ + c = next(); + if (c == 0){ + throw syntaxError("Unterminated string"); + } + if (c == q){ + return sb.toString(); + } + if (c == '&'){ + sb.append(nextEntity(c)); + }else{ + sb.append(c); + } + } + default: - /** - * Returns the next XML meta token. This is used for skipping over <!...> - * and <?...?> structures. - * @return Syntax characters (<code>< > / = ! ?</code>) are returned as - * Character, and strings and names are returned as Boolean. We don't care - * what the values actually are. - * @throws JSONException If a string is not properly closed or if the XML - * is badly structured. - */ - public Object nextMeta() throws JSONException { - char c; - char q; - do { - c = next(); - } while (Character.isWhitespace(c)); - switch (c) { - case 0: - throw syntaxError("Misshaped meta tag"); - case '<': - return XML.LT; - case '>': - return XML.GT; - case '/': - return XML.SLASH; - case '=': - return XML.EQ; - case '!': - return XML.BANG; - case '?': - return XML.QUEST; - case '"': - case '\'': - q = c; - for (;;) { - c = next(); - if (c == 0) { - throw syntaxError("Unterminated string"); - } - if (c == q) { - return Boolean.TRUE; - } - } - default: - for (;;) { - c = next(); - if (Character.isWhitespace(c)) { - return Boolean.TRUE; - } - switch (c) { - case 0: - case '<': - case '>': - case '/': - case '=': - case '!': - case '?': - case '"': - case '\'': - back(); - return Boolean.TRUE; - } - } - } - } + // Name + sb = new StringBuffer(); + for(;;){ + sb.append(c); + c = next(); + if (Character.isWhitespace(c)){ + return sb.toString(); + } + switch(c){ + case 0: + return sb.toString(); + case '>': + case '/': + case '=': + case '!': + case '?': + case '[': + case ']': + back(); + return sb.toString(); + case '<': + case '"': + case '\'': + throw syntaxError("Bad character in a name"); + } + } + } + } - /** - * Get the next XML Token. These tokens are found inside of angle - * brackets. It may be one of these characters: <code>/ > = ! ?</code> or it - * may be a string wrapped in single quotes or double quotes, or it may be a - * name. - * @return a String or a Character. - * @throws JSONException If the XML is not well formed. - */ - public Object nextToken() throws JSONException { - char c; - char q; - StringBuffer sb; - do { - c = next(); - } while (Character.isWhitespace(c)); - switch (c) { - case 0: - throw syntaxError("Misshaped element"); - case '<': - throw syntaxError("Misplaced '<'"); - case '>': - return XML.GT; - case '/': - return XML.SLASH; - case '=': - return XML.EQ; - case '!': - return XML.BANG; - case '?': - return XML.QUEST; + /** + * Skip characters until past the requested string. + * If it is not found, we are left at the end of the source with a result of false. + * @param to A string to skip past. + * @throws JSONException + */ + public boolean skipPast(String to) throws JSONException{ + boolean b; + char c; + int i; + int j; + int offset = 0; + int length = to.length(); + char[] circle = new char[length]; -// Quoted string + /* + * First fill the circle buffer with as many characters as are in the + * to string. If we reach an early end, bail. + */ - case '"': - case '\'': - q = c; - sb = new StringBuffer(); - for (;;) { - c = next(); - if (c == 0) { - throw syntaxError("Unterminated string"); - } - if (c == q) { - return sb.toString(); - } - if (c == '&') { - sb.append(nextEntity(c)); - } else { - sb.append(c); - } - } - default: - -// Name - - sb = new StringBuffer(); - for (;;) { - sb.append(c); - c = next(); - if (Character.isWhitespace(c)) { - return sb.toString(); - } - switch (c) { - case 0: - return sb.toString(); - case '>': - case '/': - case '=': - case '!': - case '?': - case '[': - case ']': - back(); - return sb.toString(); - case '<': - case '"': - case '\'': - throw syntaxError("Bad character in a name"); - } - } - } - } - - - /** - * Skip characters until past the requested string. - * If it is not found, we are left at the end of the source with a result of false. - * @param to A string to skip past. - * @throws JSONException - */ - public boolean skipPast(String to) throws JSONException { - boolean b; - char c; - int i; - int j; - int offset = 0; - int length = to.length(); - char[] circle = new char[length]; - - /* - * First fill the circle buffer with as many characters as are in the - * to string. If we reach an early end, bail. - */ - - for (i = 0; i < length; i += 1) { - c = next(); - if (c == 0) { - return false; - } - circle[i] = c; - } - /* - * We will loop, possibly for all of the remaining characters. - */ - for (;;) { - j = offset; - b = true; - /* - * Compare the circle buffer with the to string. - */ - for (i = 0; i < length; i += 1) { - if (circle[j] != to.charAt(i)) { - b = false; - break; - } - j += 1; - if (j >= length) { - j -= length; - } - } - /* - * If we exit the loop with b intact, then victory is ours. - */ - if (b) { - return true; - } - /* - * Get the next character. If there isn't one, then defeat is ours. - */ - c = next(); - if (c == 0) { - return false; - } - /* - * Shove the character in the circle buffer and advance the - * circle offset. The offset is mod n. - */ - circle[offset] = c; - offset += 1; - if (offset >= length) { - offset -= length; - } - } - } + for(i = 0; i < length; i += 1){ + c = next(); + if (c == 0){ + return false; + } + circle[i] = c; + } + /* + * We will loop, possibly for all of the remaining characters. + */ + for(;;){ + j = offset; + b = true; + /* + * Compare the circle buffer with the to string. + */ + for(i = 0; i < length; i += 1){ + if (circle[j] != to.charAt(i)){ + b = false; + break; + } + j += 1; + if (j >= length){ + j -= length; + } + } + /* + * If we exit the loop with b intact, then victory is ours. + */ + if (b){ + return true; + } + /* + * Get the next character. If there isn't one, then defeat is ours. + */ + c = next(); + if (c == 0){ + return false; + } + /* + * Shove the character in the circle buffer and advance the + * circle offset. The offset is mod n. + */ + circle[offset] = c; + offset += 1; + if (offset >= length){ + offset -= length; + } + } + } } diff --git a/src/tap/ADQLExecutor.java b/src/tap/ADQLExecutor.java index 946bb335a3b587b8ff1ba61893d737a51710277e..149f7649b4c1c8f5199ea12d521f3e5b2ed43789 100644 --- a/src/tap/ADQLExecutor.java +++ b/src/tap/ADQLExecutor.java @@ -53,7 +53,7 @@ import uws.UWSException; import uws.job.JobThread; import uws.job.Result; -public class ADQLExecutor<R> { +public class ADQLExecutor< R > { protected final ServiceConnection<R> service; protected final TAPLog logger; @@ -66,13 +66,12 @@ public class ADQLExecutor<R> { private DBConnection<R> dbConn = null; protected TAPSchema uploadSchema = null; - public ADQLExecutor(final ServiceConnection<R> service){ this.service = service; this.logger = service.getLogger(); } - public final TAPLog getLogger() { + public final TAPLog getLogger(){ return logger; } @@ -84,39 +83,39 @@ public class ADQLExecutor<R> { return (uploadSchema != null) && (uploadSchema.getNbTables() > 0); } - protected final DBConnection<R> getDBConnection() throws TAPException { - return (dbConn != null) ? dbConn : (dbConn=service.getFactory().createDBConnection((report!=null)?report.jobID:null)); + protected final DBConnection<R> getDBConnection() throws TAPException{ + return (dbConn != null) ? dbConn : (dbConn = service.getFactory().createDBConnection((report != null) ? report.jobID : null)); } - public final void closeDBConnection() throws TAPException { + public final void closeDBConnection() throws TAPException{ if (dbConn != null){ dbConn.close(); dbConn = null; } } - private final void uploadTables() throws TAPException { + private final void uploadTables() throws TAPException{ TableLoader[] tables = tapParams.getTableLoaders(); if (tables.length > 0){ - logger.info("JOB "+report.jobID+"\tLoading uploaded tables ("+tables.length+")..."); + logger.info("JOB " + report.jobID + "\tLoading uploaded tables (" + tables.length + ")..."); long start = System.currentTimeMillis(); try{ uploadSchema = service.getFactory().createUploader(getDBConnection()).upload(tables); }finally{ TAPParameters.deleteUploadedTables(tables); - report.setDuration(ExecutionProgression.UPLOADING, System.currentTimeMillis()-start); + report.setDuration(ExecutionProgression.UPLOADING, System.currentTimeMillis() - start); } } } - private final R executeADQL() throws ParseException, InterruptedException, TranslationException, SQLException, TAPException, UWSException { + private final R executeADQL() throws ParseException, InterruptedException, TranslationException, SQLException, TAPException, UWSException{ long start; tapParams.set(TAPJob.PARAM_PROGRESSION, ExecutionProgression.PARSING); start = System.currentTimeMillis(); ADQLQuery adql = parseADQL(); - report.setDuration(ExecutionProgression.PARSING, System.currentTimeMillis()-start); + report.setDuration(ExecutionProgression.PARSING, System.currentTimeMillis() - start); if (thread.isInterrupted()) throw new InterruptedException(); @@ -127,13 +126,13 @@ public class ADQLExecutor<R> { final int maxRec = tapParams.getMaxRec(); if (maxRec > -1){ if (limit <= -1 || limit > maxRec) - adql.getSelect().setLimit(maxRec+1); + adql.getSelect().setLimit(maxRec + 1); } tapParams.set(TAPJob.PARAM_PROGRESSION, ExecutionProgression.TRANSLATING); start = System.currentTimeMillis(); String sqlQuery = translateADQL(adql); - report.setDuration(ExecutionProgression.TRANSLATING, System.currentTimeMillis()-start); + report.setDuration(ExecutionProgression.TRANSLATING, System.currentTimeMillis() - start); report.sqlTranslation = sqlQuery; if (thread.isInterrupted()) @@ -142,12 +141,12 @@ public class ADQLExecutor<R> { tapParams.set(TAPJob.PARAM_PROGRESSION, ExecutionProgression.EXECUTING_SQL); start = System.currentTimeMillis(); R result = executeQuery(sqlQuery, adql); - report.setDuration(ExecutionProgression.EXECUTING_SQL, System.currentTimeMillis()-start); + report.setDuration(ExecutionProgression.EXECUTING_SQL, System.currentTimeMillis() - start); return result; } - public final TAPExecutionReport start(final AsyncThread<R> thread) throws TAPException, UWSException, InterruptedException, ParseException, TranslationException, SQLException { + public final TAPExecutionReport start(final AsyncThread<R> thread) throws TAPException, UWSException, InterruptedException, ParseException, TranslationException, SQLException{ if (this.thread != null || this.report != null) throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, "This ADQLExecutor has already been executed !"); @@ -161,7 +160,7 @@ public class ADQLExecutor<R> { return start(); } - public final TAPExecutionReport start(final Thread thread, final String jobId, final TAPParameters params, final HttpServletResponse response) throws TAPException, UWSException, InterruptedException, ParseException, TranslationException, SQLException { + public final TAPExecutionReport start(final Thread thread, final String jobId, final TAPParameters params, final HttpServletResponse response) throws TAPException, UWSException, InterruptedException, ParseException, TranslationException, SQLException{ if (this.thread != null || this.report != null) throw new TAPException("This ADQLExecutor has already been executed !"); @@ -173,7 +172,7 @@ public class ADQLExecutor<R> { return start(); } - protected final TAPExecutionReport start() throws TAPException, UWSException, InterruptedException, ParseException, TranslationException, SQLException { + protected final TAPExecutionReport start() throws TAPException, UWSException, InterruptedException, ParseException, TranslationException, SQLException{ long start = System.currentTimeMillis(); try{ // Upload tables if needed: @@ -194,7 +193,7 @@ public class ADQLExecutor<R> { tapParams.set(TAPJob.PARAM_PROGRESSION, ExecutionProgression.WRITING_RESULT); writeResult(queryResult); - logger.info("JOB "+report.jobID+" COMPLETED"); + logger.info("JOB " + report.jobID + " COMPLETED"); tapParams.set(TAPJob.PARAM_PROGRESSION, ExecutionProgression.FINISHED); report.success = true; @@ -203,19 +202,23 @@ public class ADQLExecutor<R> { }catch(NullPointerException npe){ npe.printStackTrace(); throw npe; - } finally { - try { + }finally{ + try{ dropUploadedTables(); - } catch (TAPException e) { logger.error("JOB "+report.jobID+"\tCan not drop uploaded tables !", e); } - try { + }catch(TAPException e){ + logger.error("JOB " + report.jobID + "\tCan not drop uploaded tables !", e); + } + try{ closeDBConnection(); - } catch (TAPException e) { logger.error("JOB "+report.jobID+"\tCan not close the DB connection !", e); } - report.setTotalDuration(System.currentTimeMillis()-start); + }catch(TAPException e){ + logger.error("JOB " + report.jobID + "\tCan not close the DB connection !", e); + } + report.setTotalDuration(System.currentTimeMillis() - start); logger.queryFinished(report); } } - protected ADQLQuery parseADQL() throws ParseException, InterruptedException, TAPException { + protected ADQLQuery parseADQL() throws ParseException, InterruptedException, TAPException{ ADQLQueryFactory queryFactory = service.getFactory().createQueryFactory(); QueryChecker queryChecker = service.getFactory().createQueryChecker(uploadSchema); ADQLParser parser; @@ -229,40 +232,40 @@ public class ADQLExecutor<R> { return parser.parseQuery(tapParams.getQuery()); } - protected String translateADQL(ADQLQuery query) throws TranslationException, InterruptedException, TAPException { + protected String translateADQL(ADQLQuery query) throws TranslationException, InterruptedException, TAPException{ ADQLTranslator translator = service.getFactory().createADQLTranslator(); //logger.info("Job "+report.jobID+" - 2/5 Translating ADQL..."); return translator.translate(query); } - protected R executeQuery(String sql, ADQLQuery adql) throws SQLException, InterruptedException, TAPException { + protected R executeQuery(String sql, ADQLQuery adql) throws SQLException, InterruptedException, TAPException{ //logger.info("Job "+report.jobID+" - 3/5 Creating DBConnection...."); DBConnection<R> dbConn = getDBConnection(); //logger.info("Job "+report.jobID+" - 4/5 Executing query...\n"+sql); final long startTime = System.currentTimeMillis(); R result = dbConn.executeQuery(sql, adql); if (result == null) - logger.info("JOB "+report.jobID+" - QUERY ABORTED AFTER "+(System.currentTimeMillis()-startTime)+" MS !"); + logger.info("JOB " + report.jobID + " - QUERY ABORTED AFTER " + (System.currentTimeMillis() - startTime) + " MS !"); else - logger.info("JOB "+report.jobID+" - QUERY SUCCESFULLY EXECUTED IN "+(System.currentTimeMillis()-startTime)+" MS !"); + logger.info("JOB " + report.jobID + " - QUERY SUCCESFULLY EXECUTED IN " + (System.currentTimeMillis() - startTime) + " MS !"); return result; } - protected OutputFormat<R> getFormatter() throws TAPException { + protected OutputFormat<R> getFormatter() throws TAPException{ // Search for the corresponding formatter: String format = tapParams.getFormat(); - OutputFormat<R> formatter = service.getOutputFormat((format == null)?"votable":format); + OutputFormat<R> formatter = service.getOutputFormat((format == null) ? "votable" : format); if (format != null && formatter == null) formatter = service.getOutputFormat("votable"); // Format the result: if (formatter == null) - throw new TAPException("Impossible to format the query result: no formatter has been found for the given MIME type \""+format+"\" and for the default MIME type \"votable\" (short form) !"); + throw new TAPException("Impossible to format the query result: no formatter has been found for the given MIME type \"" + format + "\" and for the default MIME type \"votable\" (short form) !"); return formatter; } - protected final void writeResult(R queryResult) throws InterruptedException, TAPException, UWSException { + protected final void writeResult(R queryResult) throws InterruptedException, TAPException, UWSException{ OutputFormat<R> formatter = getFormatter(); // Synchronous case: @@ -272,9 +275,9 @@ public class ADQLExecutor<R> { response.setContentType(formatter.getMimeType()); writeResult(queryResult, formatter, response.getOutputStream()); }catch(IOException ioe){ - throw new TAPException("Impossible to get the output stream of the HTTP request to write the result of the job "+report.jobID+" !", ioe); + throw new TAPException("Impossible to get the output stream of the HTTP request to write the result of the job " + report.jobID + " !", ioe); }finally{ - report.setDuration(ExecutionProgression.WRITING_RESULT, System.currentTimeMillis()-start); + report.setDuration(ExecutionProgression.WRITING_RESULT, System.currentTimeMillis() - start); } }// Asynchronous case: @@ -288,19 +291,19 @@ public class ADQLExecutor<R> { result.setSize(jobThread.getResultSize(result)); jobThread.publishResult(result); }catch(IOException ioe){ - throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, ioe, "Impossible to get the output stream of the result file to write the result of the job "+report.jobID+" !"); + throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, ioe, "Impossible to get the output stream of the result file to write the result of the job " + report.jobID + " !"); }finally{ - report.setDuration(ExecutionProgression.WRITING_RESULT, System.currentTimeMillis()-start); + report.setDuration(ExecutionProgression.WRITING_RESULT, System.currentTimeMillis() - start); } } } - protected void writeResult(R queryResult, OutputFormat<R> formatter, OutputStream output) throws InterruptedException, TAPException { + protected void writeResult(R queryResult, OutputFormat<R> formatter, OutputStream output) throws InterruptedException, TAPException{ //logger.info("Job "+report.jobID+" - 5/5 Writing result file..."); formatter.writeResult(queryResult, output, report, thread); } - protected void dropUploadedTables() throws TAPException { + protected void dropUploadedTables() throws TAPException{ if (uploadSchema != null){ // Drop all uploaded tables: DBConnection<R> dbConn = getDBConnection(); @@ -308,7 +311,7 @@ public class ADQLExecutor<R> { try{ dbConn.dropTable(t); }catch(DBException dbe){ - logger.error("JOB "+report.jobID+"\tCan not drop the table \""+t.getDBName()+"\" (in adql \""+t.getADQLName()+"\") from the database !", dbe); + logger.error("JOB " + report.jobID + "\tCan not drop the table \"" + t.getDBName() + "\" (in adql \"" + t.getADQLName() + "\") from the database !", dbe); } } closeDBConnection(); diff --git a/src/tap/AbstractTAPFactory.java b/src/tap/AbstractTAPFactory.java index db1fc9a64fae183f00356d7c726823445e169935..91bad42e857dae762b36d571b0a589b5bdf8c75d 100644 --- a/src/tap/AbstractTAPFactory.java +++ b/src/tap/AbstractTAPFactory.java @@ -54,11 +54,11 @@ import adql.db.DBTable; import adql.parser.ADQLQueryFactory; import adql.parser.QueryChecker; -public abstract class AbstractTAPFactory<R> extends AbstractUWSFactory implements TAPFactory<R> { +public abstract class AbstractTAPFactory< R > extends AbstractUWSFactory implements TAPFactory<R> { protected final ServiceConnection<R> service; - protected AbstractTAPFactory(ServiceConnection<R> service) throws NullPointerException { + protected AbstractTAPFactory(ServiceConnection<R> service) throws NullPointerException{ if (service == null) throw new NullPointerException("Can not create a TAPFactory without a ServiceConnection instance !"); @@ -66,17 +66,17 @@ public abstract class AbstractTAPFactory<R> extends AbstractUWSFactory implement } @Override - public UWSService createUWS() throws TAPException, UWSException { + public UWSService createUWS() throws TAPException, UWSException{ return new UWSService(this.service.getFactory(), this.service.getFileManager(), this.service.getLogger()); } @Override - public UWSBackupManager createUWSBackupManager(final UWSService uws) throws TAPException, UWSException { + public UWSBackupManager createUWSBackupManager(final UWSService uws) throws TAPException, UWSException{ return null; } @Override - public UWSJob createJob(HttpServletRequest request, JobOwner owner) throws UWSException { + public UWSJob createJob(HttpServletRequest request, JobOwner owner) throws UWSException{ if (!service.isAvailable()) throw new UWSException(HttpServletResponse.SC_SERVICE_UNAVAILABLE, service.getAvailability()); @@ -89,7 +89,7 @@ public abstract class AbstractTAPFactory<R> extends AbstractUWSFactory implement } @Override - public UWSJob createJob(String jobId, JobOwner owner, final UWSParameters params, long quote, long startTime, long endTime, List<Result> results, ErrorSummary error) throws UWSException { + public UWSJob createJob(String jobId, JobOwner owner, final UWSParameters params, long quote, long startTime, long endTime, List<Result> results, ErrorSummary error) throws UWSException{ if (!service.isAvailable()) throw new UWSException(HttpServletResponse.SC_SERVICE_UNAVAILABLE, service.getAvailability()); try{ @@ -100,7 +100,7 @@ public abstract class AbstractTAPFactory<R> extends AbstractUWSFactory implement } @Override - public final JobThread createJobThread(final UWSJob job) throws UWSException { + public final JobThread createJobThread(final UWSJob job) throws UWSException{ try{ return new AsyncThread<R>((TAPJob)job, createADQLExecutor()); }catch(TAPException te){ @@ -108,7 +108,7 @@ public abstract class AbstractTAPFactory<R> extends AbstractUWSFactory implement } } - public ADQLExecutor<R> createADQLExecutor() throws TAPException { + public ADQLExecutor<R> createADQLExecutor() throws TAPException{ return new ADQLExecutor<R>(service); } @@ -119,7 +119,7 @@ public abstract class AbstractTAPFactory<R> extends AbstractUWSFactory implement * @see uws.service.AbstractUWSFactory#extractParameters(javax.servlet.http.HttpServletRequest, uws.service.UWS) */ @Override - public UWSParameters createUWSParameters(HttpServletRequest request) throws UWSException { + public UWSParameters createUWSParameters(HttpServletRequest request) throws UWSException{ try{ return new TAPParameters(request, service, getExpectedAdditionalParameters(), getInputParamControllers()); }catch(TAPException te){ @@ -128,10 +128,10 @@ public abstract class AbstractTAPFactory<R> extends AbstractUWSFactory implement } @Override - public UWSParameters createUWSParameters(Map<String, Object> params) throws UWSException { - try { + public UWSParameters createUWSParameters(Map<String,Object> params) throws UWSException{ + try{ return new TAPParameters(service, params, getExpectedAdditionalParameters(), getInputParamControllers()); - } catch (TAPException te) { + }catch(TAPException te){ throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, te); } } @@ -142,7 +142,7 @@ public abstract class AbstractTAPFactory<R> extends AbstractUWSFactory implement } @Override - public QueryChecker createQueryChecker(TAPSchema uploadSchema) throws TAPException { + public QueryChecker createQueryChecker(TAPSchema uploadSchema) throws TAPException{ TAPMetadata meta = service.getTAPMetadata(); ArrayList<DBTable> tables = new ArrayList<DBTable>(meta.getNbTables()); Iterator<TAPTable> it = meta.getTables(); @@ -155,7 +155,7 @@ public abstract class AbstractTAPFactory<R> extends AbstractUWSFactory implement return new DBChecker(tables); } - public Uploader createUploader(final DBConnection<R> dbConn) throws TAPException { + public Uploader createUploader(final DBConnection<R> dbConn) throws TAPException{ return new Uploader(service, dbConn); } diff --git a/src/tap/AsyncThread.java b/src/tap/AsyncThread.java index 9f5c33ebb995a98cfbb131e652be52229898a8d3..4581c0900f4cb93f8b9814e9ead36d9fc690a33d 100644 --- a/src/tap/AsyncThread.java +++ b/src/tap/AsyncThread.java @@ -25,44 +25,44 @@ import uws.UWSException; import uws.job.JobThread; -public class AsyncThread<R> extends JobThread { +public class AsyncThread< R > extends JobThread { protected final ADQLExecutor<R> executor; - public AsyncThread(TAPJob j, ADQLExecutor<R> executor) throws UWSException { - super(j, "Execute the ADQL query of the TAP request "+j.getJobId()); + public AsyncThread(TAPJob j, ADQLExecutor<R> executor) throws UWSException{ + super(j, "Execute the ADQL query of the TAP request " + j.getJobId()); this.executor = executor; } @Override - public void interrupt() { + public void interrupt(){ if (isAlive()){ - try { + try{ executor.closeDBConnection(); - } catch (TAPException e) { + }catch(TAPException e){ if (job != null && job.getLogger() != null) - job.getLogger().error("Can not close the DBConnection for the executing job \""+job.getJobId()+"\" ! => the job will be probably not totally aborted.", e); + job.getLogger().error("Can not close the DBConnection for the executing job \"" + job.getJobId() + "\" ! => the job will be probably not totally aborted.", e); } } super.interrupt(); } @Override - protected void jobWork() throws UWSException, InterruptedException { + protected void jobWork() throws UWSException, InterruptedException{ try{ executor.start(this); }catch(InterruptedException ie){ throw ie; }catch(UWSException ue){ throw ue; - }catch(TAPException te) { + }catch(TAPException te){ throw new UWSException(te.getHttpErrorCode(), te, te.getMessage()); - }catch(ParseException pe) { + }catch(ParseException pe){ throw new UWSException(UWSException.BAD_REQUEST, pe, pe.getMessage()); }catch(TranslationException te){ throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, te, te.getMessage()); - }catch(Exception ex) { - throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, ex, "Error while processing the ADQL query of the job "+job.getJobId()+" !"); + }catch(Exception ex){ + throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, ex, "Error while processing the ADQL query of the job " + job.getJobId() + " !"); }finally{ getTAPJob().setExecReport(executor.getExecReport()); } diff --git a/src/tap/ExecutionProgression.java b/src/tap/ExecutionProgression.java index 7da0daeba91765fd5eaab399719b5c4a08d5c762..618d2104813c7d0584be6f136e4b4390b3ef95a6 100644 --- a/src/tap/ExecutionProgression.java +++ b/src/tap/ExecutionProgression.java @@ -19,6 +19,6 @@ package tap; * Copyright 2012 - UDS/Centre de Données astronomiques de Strasbourg (CDS) */ -public enum ExecutionProgression { +public enum ExecutionProgression{ PENDING, UPLOADING, PARSING, TRANSLATING, EXECUTING_SQL, WRITING_RESULT, FINISHED; } diff --git a/src/tap/ServiceConnection.java b/src/tap/ServiceConnection.java index 25852d230995d63c00cef618c18152e686c62fca..40e3745205e86a5a6dcea1cdd9fa647eb5459935 100644 --- a/src/tap/ServiceConnection.java +++ b/src/tap/ServiceConnection.java @@ -32,9 +32,9 @@ import tap.metadata.TAPMetadata; import uws.service.UserIdentifier; -public interface ServiceConnection<R> { +public interface ServiceConnection< R > { - public static enum LimitUnit { + public static enum LimitUnit{ rows, bytes; } diff --git a/src/tap/TAPException.java b/src/tap/TAPException.java index ebee39209b92bf0a3e566a90848e3c685bbcb891..89a4feeef6723558f5d32f9203862329310ec361 100644 --- a/src/tap/TAPException.java +++ b/src/tap/TAPException.java @@ -30,31 +30,31 @@ public class TAPException extends Exception { private int httpErrorCode = UWSException.INTERNAL_SERVER_ERROR; - public TAPException(String message) { + public TAPException(String message){ super(message); } - public TAPException(String message, int httpErrorCode) { + public TAPException(String message, int httpErrorCode){ super(message); this.httpErrorCode = httpErrorCode; } - public TAPException(String message, String query) { + public TAPException(String message, String query){ super(message); adqlQuery = query; } - public TAPException(String message, int httpErrorCode, String query) { + public TAPException(String message, int httpErrorCode, String query){ this(message, httpErrorCode); adqlQuery = query; } - public TAPException(String message, String query, ExecutionProgression status) { + public TAPException(String message, String query, ExecutionProgression status){ this(message, query); executionStatus = status; } - public TAPException(String message, int httpErrorCode, String query, ExecutionProgression status) { + public TAPException(String message, int httpErrorCode, String query, ExecutionProgression status){ this(message, httpErrorCode, query); executionStatus = status; } @@ -63,70 +63,70 @@ public class TAPException extends Exception { this(ue.getMessage(), ue.getCause(), ue.getHttpErrorCode()); } - public TAPException(UWSException cause, int httpErrorCode) { + public TAPException(UWSException cause, int httpErrorCode){ this(cause); this.httpErrorCode = httpErrorCode; } - public TAPException(UWSException cause, int httpErrorCode, ExecutionProgression status) { + public TAPException(UWSException cause, int httpErrorCode, ExecutionProgression status){ this(cause, httpErrorCode); this.executionStatus = status; } - public TAPException(Throwable cause) { + public TAPException(Throwable cause){ super(cause); } - public TAPException(Throwable cause, int httpErrorCode) { + public TAPException(Throwable cause, int httpErrorCode){ super(cause); this.httpErrorCode = httpErrorCode; } - public TAPException(Throwable cause, String query) { + public TAPException(Throwable cause, String query){ super(cause); adqlQuery = query; } - public TAPException(Throwable cause, int httpErrorCode, String query) { + public TAPException(Throwable cause, int httpErrorCode, String query){ this(cause, httpErrorCode); adqlQuery = query; } - public TAPException(Throwable cause, String query, ExecutionProgression status) { + public TAPException(Throwable cause, String query, ExecutionProgression status){ this(cause, query); executionStatus = status; } - public TAPException(Throwable cause, int httpErrorCode, String query, ExecutionProgression status) { + public TAPException(Throwable cause, int httpErrorCode, String query, ExecutionProgression status){ this(cause, httpErrorCode, query); executionStatus = status; } - public TAPException(String message, Throwable cause) { + public TAPException(String message, Throwable cause){ super(message, cause); } - public TAPException(String message, Throwable cause, int httpErrorCode) { + public TAPException(String message, Throwable cause, int httpErrorCode){ super(message, cause); this.httpErrorCode = httpErrorCode; } - public TAPException(String message, Throwable cause, String query) { + public TAPException(String message, Throwable cause, String query){ super(message, cause); adqlQuery = query; } - public TAPException(String message, Throwable cause, int httpErrorCode, String query) { + public TAPException(String message, Throwable cause, int httpErrorCode, String query){ this(message, cause, httpErrorCode); adqlQuery = query; } - public TAPException(String message, Throwable cause, String query, ExecutionProgression status) { + public TAPException(String message, Throwable cause, String query, ExecutionProgression status){ this(message, cause, query); executionStatus = status; } - public TAPException(String message, Throwable cause, int httpErrorCode, String query, ExecutionProgression status) { + public TAPException(String message, Throwable cause, int httpErrorCode, String query, ExecutionProgression status){ this(message, cause, httpErrorCode, query); executionStatus = status; } diff --git a/src/tap/TAPExecutionReport.java b/src/tap/TAPExecutionReport.java index 0f4dfb4253b7b0b1898cf1d9708ddc5ac8d94693..bf95af1a449dd836cc4b16f1c65960e90d7db4b4 100644 --- a/src/tap/TAPExecutionReport.java +++ b/src/tap/TAPExecutionReport.java @@ -45,18 +45,18 @@ public class TAPExecutionReport { protected int getIndexDuration(final ExecutionProgression tapProgression){ switch(tapProgression){ - case UPLOADING: - return 0; - case PARSING: - return 1; - case TRANSLATING: - return 2; - case EXECUTING_SQL: - return 3; - case WRITING_RESULT: - return 4; - default: - return -1; + case UPLOADING: + return 0; + case PARSING: + return 1; + case TRANSLATING: + return 2; + case EXECUTING_SQL: + return 3; + case WRITING_RESULT: + return 4; + default: + return -1; } } diff --git a/src/tap/TAPFactory.java b/src/tap/TAPFactory.java index 55918c8dcebd3fe3bf2ec0ae9cdb3e64ac664917..785be4795659e53d11bc2b0ffecf32477784f5dd 100644 --- a/src/tap/TAPFactory.java +++ b/src/tap/TAPFactory.java @@ -37,7 +37,7 @@ import adql.parser.QueryChecker; import adql.translator.ADQLTranslator; -public interface TAPFactory<R> extends UWSFactory { +public interface TAPFactory< R > extends UWSFactory { public UWSService createUWS() throws TAPException, UWSException; diff --git a/src/tap/TAPJob.java b/src/tap/TAPJob.java index a2ebb0b14c97398d154144546e7d27711e0230cf..52510c5b6290ba737cf07049cf62892d99a3a29c 100644 --- a/src/tap/TAPJob.java +++ b/src/tap/TAPJob.java @@ -62,8 +62,7 @@ public class TAPJob extends UWSJob { protected final TAPParameters tapParams; - - public TAPJob(final JobOwner owner, final TAPParameters tapParams) throws UWSException, TAPException { + public TAPJob(final JobOwner owner, final TAPParameters tapParams) throws UWSException, TAPException{ super(owner, tapParams); this.tapParams = tapParams; tapParams.check(); @@ -71,7 +70,7 @@ public class TAPJob extends UWSJob { //loadTAPParams(tapParams); } - public TAPJob(final String jobID, final JobOwner owner, final TAPParameters params, final long quote, final long startTime, final long endTime, final List<Result> results, final ErrorSummary error) throws UWSException, TAPException { + public TAPJob(final String jobID, final JobOwner owner, final TAPParameters params, final long quote, final long startTime, final long endTime, final List<Result> results, final ErrorSummary error) throws UWSException, TAPException{ super(jobID, owner, params, quote, startTime, endTime, results, error); this.tapParams = params; this.tapParams.check(); @@ -95,7 +94,7 @@ public class TAPJob extends UWSJob { /** * @return The tapParams. */ - public final TAPParameters getTapParams() { + public final TAPParameters getTapParams(){ return tapParams; } @@ -134,16 +133,16 @@ public class TAPJob extends UWSJob { /** * @return The execReport. */ - public final TAPExecutionReport getExecReport() { + public final TAPExecutionReport getExecReport(){ return execReport; } /** * @param execReport The execReport to set. */ - public final void setExecReport(TAPExecutionReport execReport) throws UWSException { + public final void setExecReport(TAPExecutionReport execReport) throws UWSException{ if (getRestorationDate() == null && !isRunning()) - throw new UWSException("Impossible to set an execution report if the job is not in the EXECUTING phase ! Here, the job \""+jobId+"\" is in the phase "+getPhase()); + throw new UWSException("Impossible to set an execution report if the job is not in the EXECUTING phase ! Here, the job \"" + jobId + "\" is in the phase " + getPhase()); this.execReport = execReport; } @@ -169,7 +168,7 @@ public class TAPJob extends UWSJob { }*/ @Override - protected void stop() { + protected void stop(){ if (!isStopped()){ //try { stopping = true; @@ -193,10 +192,9 @@ public class TAPJob extends UWSJob { }*/ @Override - public void clearResources() { + public void clearResources(){ super.clearResources(); // TODO deleteResultFiles(); } - } diff --git a/src/tap/TAPSyncJob.java b/src/tap/TAPSyncJob.java index 22e0a28996dea8a4da1edb3021660721da1e4aab..726712873fde4feddddd14505922c02c47d49f79 100644 --- a/src/tap/TAPSyncJob.java +++ b/src/tap/TAPSyncJob.java @@ -45,7 +45,7 @@ public class TAPSyncJob { private Date startedAt = null; - public TAPSyncJob(final ServiceConnection<?> service, final TAPParameters params) throws NullPointerException { + public TAPSyncJob(final ServiceConnection<?> service, final TAPParameters params) throws NullPointerException{ if (params == null) throw new NullPointerException("Missing TAP parameters ! => Impossible to create a synchronous TAP job."); tapParams = params; @@ -69,11 +69,11 @@ public class TAPSyncJob { * * @return A unique job identifier. */ - protected String generateId() { - String generatedId = "S"+System.currentTimeMillis()+"A"; + protected String generateId(){ + String generatedId = "S" + System.currentTimeMillis() + "A"; if (lastId != null){ while(lastId.equals(generatedId)) - generatedId = generatedId.substring(0, generatedId.length()-1)+(char)(generatedId.charAt(generatedId.length()-1)+1); + generatedId = generatedId.substring(0, generatedId.length() - 1) + (char)(generatedId.charAt(generatedId.length() - 1) + 1); } lastId = generatedId; return generatedId; @@ -87,18 +87,18 @@ public class TAPSyncJob { return tapParams; } - public final TAPExecutionReport getExecReport() { + public final TAPExecutionReport getExecReport(){ return execReport; } - public synchronized boolean start(final HttpServletResponse response) throws IllegalStateException, UWSException, TAPException { + public synchronized boolean start(final HttpServletResponse response) throws IllegalStateException, UWSException, TAPException{ if (startedAt != null) throw new IllegalStateException("Impossible to restart a synchronous TAP query !"); ADQLExecutor<?> executor; - try { + try{ executor = service.getFactory().createADQLExecutor(); - } catch (TAPException e) { + }catch(TAPException e){ // TODO Log this error ! return true; } @@ -123,9 +123,9 @@ public class TAPSyncJob { if (!thread.isSuccess()){ if (thread.isAlive()) - throw new TAPException("Time out (="+tapParams.getExecutionDuration()+"ms) ! However, the thread (synchronous query) can not be stopped !", HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + throw new TAPException("Time out (=" + tapParams.getExecutionDuration() + "ms) ! However, the thread (synchronous query) can not be stopped !", HttpServletResponse.SC_INTERNAL_SERVER_ERROR); else if (timeout) - throw new TAPException("Time out ! The execution of this synchronous TAP query was limited to "+tapParams.getExecutionDuration()+"ms.", HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + throw new TAPException("Time out ! The execution of this synchronous TAP query was limited to " + tapParams.getExecutionDuration() + "ms.", HttpServletResponse.SC_INTERNAL_SERVER_ERROR); else{ Throwable t = thread.getError(); if (t instanceof InterruptedException) @@ -152,7 +152,7 @@ public class TAPSyncJob { public SyncThread(final ADQLExecutor<?> executor, final String ID, final TAPParameters tapParams, final HttpServletResponse response){ super(JobThread.tg, ID); - taskDescription = "Executing the synchronous TAP query "+ID; + taskDescription = "Executing the synchronous TAP query " + ID; this.executor = executor; this.ID = ID; this.tapParams = tapParams; @@ -172,14 +172,14 @@ public class TAPSyncJob { } @Override - public void run() { + public void run(){ // Log the start of this thread: executor.getLogger().threadStarted(this, taskDescription); - try { + try{ report = executor.start(this, ID, tapParams, response); executor.getLogger().threadFinished(this, taskDescription); - } catch (Throwable e) { + }catch(Throwable e){ exception = e; if (e instanceof InterruptedException){ // Log the abortion: diff --git a/src/tap/backup/DefaultTAPBackupManager.java b/src/tap/backup/DefaultTAPBackupManager.java index b43899d3f01465c7ac4fedba039cfbe37362e260..4e4a86f48d84062a03a162b2a9fd8e1bc00c1366 100644 --- a/src/tap/backup/DefaultTAPBackupManager.java +++ b/src/tap/backup/DefaultTAPBackupManager.java @@ -32,24 +32,24 @@ import uws.service.backup.DefaultUWSBackupManager; public class DefaultTAPBackupManager extends DefaultUWSBackupManager { - public DefaultTAPBackupManager(UWS uws) { + public DefaultTAPBackupManager(UWS uws){ super(uws); } - public DefaultTAPBackupManager(UWS uws, long frequency) { + public DefaultTAPBackupManager(UWS uws, long frequency){ super(uws, frequency); } - public DefaultTAPBackupManager(UWS uws, boolean byUser) throws UWSException { + public DefaultTAPBackupManager(UWS uws, boolean byUser) throws UWSException{ super(uws, byUser); } - public DefaultTAPBackupManager(UWS uws, boolean byUser, long frequency) throws UWSException { + public DefaultTAPBackupManager(UWS uws, boolean byUser, long frequency) throws UWSException{ super(uws, byUser, frequency); } @Override - protected JSONObject getJSONJob(UWSJob job, String jlName) throws UWSException, JSONException { + protected JSONObject getJSONJob(UWSJob job, String jlName) throws UWSException, JSONException{ JSONObject json = super.getJSONJob(job, jlName); if (job instanceof TAPJob && ((TAPJob)job).getExecReport() != null){ @@ -77,7 +77,7 @@ public class DefaultTAPBackupManager extends DefaultUWSBackupManager { } @Override - protected void restoreOtherJobParams(JSONObject json, UWSJob job) throws UWSException { + protected void restoreOtherJobParams(JSONObject json, UWSJob job) throws UWSException{ if (job != null && json != null && job instanceof TAPJob){ TAPJob tapJob = (TAPJob)job; Object obj = job.getAdditionalParameterValue("tapexecreport"); @@ -105,14 +105,14 @@ public class DefaultTAPBackupManager extends DefaultUWSBackupManager { else if (key.equalsIgnoreCase("totalduration")) execReport.setTotalDuration(jsonExecReport.getLong(key)); else - getLogger().warning("The execution report attribute '"+key+"' of the job \""+job.getJobId()+"\" has been ignored because unknown !"); + getLogger().warning("The execution report attribute '" + key + "' of the job \"" + job.getJobId() + "\" has been ignored because unknown !"); }catch(JSONException je){ - getLogger().error("[restoration] Incorrect JSON format for the execution report serialization of the job \""+job.getJobId()+"\" (attribute: \""+key+"\") !", je); + getLogger().error("[restoration] Incorrect JSON format for the execution report serialization of the job \"" + job.getJobId() + "\" (attribute: \"" + key + "\") !", je); } } tapJob.setExecReport(execReport); }else if (!(obj instanceof JSONObject)) - getLogger().warning("[restoration] Impossible to restore the execution report of the job \""+job.getJobId()+"\" because the stored object is not a JSONObject !"); + getLogger().warning("[restoration] Impossible to restore the execution report of the job \"" + job.getJobId() + "\" because the stored object is not a JSONObject !"); } } } diff --git a/src/tap/db/DBConnection.java b/src/tap/db/DBConnection.java index 1e916b30e4a19bb2f0a8481a58831052af5d246f..695cf14ffde4c236e56b6c99157cb9b5a2aefee2 100644 --- a/src/tap/db/DBConnection.java +++ b/src/tap/db/DBConnection.java @@ -33,7 +33,7 @@ import adql.query.ADQLQuery; * * @param <R> Result type of the execution of a query (see {@link #executeQuery(String, ADQLQuery)}. */ -public interface DBConnection<R> { +public interface DBConnection< R > { public final static UWSLogType LOG_TYPE_DB_ACTIVITY = UWSLogType.createCustomLogType("DBActivity"); diff --git a/src/tap/db/DBException.java b/src/tap/db/DBException.java index 8e0da456f8f7d7f02f4bc41c6685e3e2e7614228..e28dba18fc139348aa0d4274448034fd493ba67f 100644 --- a/src/tap/db/DBException.java +++ b/src/tap/db/DBException.java @@ -38,7 +38,7 @@ public class DBException extends TAPException { * * @param message Error message. */ - public DBException(String message) { + public DBException(String message){ super(message); } @@ -53,7 +53,7 @@ public class DBException extends TAPException { * @param message Error message. * @param query ADQL query (this string may be displayed to the user). */ - public DBException(String message, String query) { + public DBException(String message, String query){ super(message, query); } @@ -62,7 +62,7 @@ public class DBException extends TAPException { * * @param cause Cause of this error. */ - public DBException(Throwable cause) { + public DBException(Throwable cause){ super(cause); } @@ -77,7 +77,7 @@ public class DBException extends TAPException { * @param cause Cause of this error. * @param query ADQL query (this string may be displayed to the user). */ - public DBException(Throwable cause, String query) { + public DBException(Throwable cause, String query){ super(cause, query); } @@ -87,7 +87,7 @@ public class DBException extends TAPException { * @param message Error message. * @param cause Cause of this error. */ - public DBException(String message, Throwable cause) { + public DBException(String message, Throwable cause){ super(message, cause); } @@ -103,7 +103,7 @@ public class DBException extends TAPException { * @param cause Cause of this error. * @param query ADQL query (this string may be displayed to the user). */ - public DBException(String message, Throwable cause, String query) { + public DBException(String message, Throwable cause, String query){ super(message, cause, query); } diff --git a/src/tap/db/JDBCConnection.java b/src/tap/db/JDBCConnection.java index 962e2127a8b34acc9e585d550ce9339fd3b051b5..a557cf381b223b0836e3856951e598ba671ded39 100644 --- a/src/tap/db/JDBCConnection.java +++ b/src/tap/db/JDBCConnection.java @@ -73,34 +73,34 @@ public class JDBCConnection implements DBConnection<ResultSet> { * * @throws DBException If the specified driver can not be found, or if the database URL or user is incorrect. */ - public JDBCConnection(final String ID, final String driverPath, final String dbUrl, final String dbUser, final String dbPassword, final TAPLog logger) throws DBException { + public JDBCConnection(final String ID, final String driverPath, final String dbUrl, final String dbUser, final String dbPassword, final TAPLog logger) throws DBException{ this.logger = logger; this.ID = ID; // Load the specified JDBC driver: - try { + try{ Class.forName(driverPath); - } catch (ClassNotFoundException cnfe) { - logger.dbError("Impossible to find the JDBC driver \""+driverPath+"\" !", cnfe); - throw new DBException("Impossible to find the JDBC driver \""+driverPath+"\" !", cnfe); + }catch(ClassNotFoundException cnfe){ + logger.dbError("Impossible to find the JDBC driver \"" + driverPath + "\" !", cnfe); + throw new DBException("Impossible to find the JDBC driver \"" + driverPath + "\" !", cnfe); } // Build a connection to the specified database: - String url = dbUrl.startsWith(JDBC_PREFIX) ? dbUrl : (JDBC_PREFIX+dbUrl); - try { + String url = dbUrl.startsWith(JDBC_PREFIX) ? dbUrl : (JDBC_PREFIX + dbUrl); + try{ connection = DriverManager.getConnection(url, dbUser, dbPassword); logger.connectionOpened(this, dbUrl.substring(dbUrl.lastIndexOf('/'))); - } catch (SQLException se) { - logger.dbError("Impossible to establish a connection to the database \""+url+"\" !", se); - throw new DBException("Impossible to establish a connection to the database \""+url+"\" !", se); + }catch(SQLException se){ + logger.dbError("Impossible to establish a connection to the database \"" + url + "\" !", se); + throw new DBException("Impossible to establish a connection to the database \"" + url + "\" !", se); } } - public final String getID() { + public final String getID(){ return ID; } - public void startTransaction() throws DBException { + public void startTransaction() throws DBException{ try{ Statement st = connection.createStatement(); st.execute("begin"); @@ -111,31 +111,31 @@ public class JDBCConnection implements DBConnection<ResultSet> { } } - public void cancelTransaction() throws DBException { - try { + public void cancelTransaction() throws DBException{ + try{ connection.rollback(); logger.transactionCancelled(this); - } catch (SQLException se) { + }catch(SQLException se){ logger.dbError("Impossible to cancel/rollback a transaction !", se); throw new DBException("Impossible to cancel (rollback) the transaction !", se); } } - public void endTransaction() throws DBException { - try { + public void endTransaction() throws DBException{ + try{ connection.commit(); logger.transactionEnded(this); - } catch (SQLException se) { + }catch(SQLException se){ logger.dbError("Impossible to end/commit a transaction !", se); throw new DBException("Impossible to end/commit the transaction !", se); } } - public void close() throws DBException { - try { + public void close() throws DBException{ + try{ connection.close(); logger.connectionClosed(this); - } catch (SQLException se) { + }catch(SQLException se){ logger.dbError("Impossible to close a database transaction !", se); throw new DBException("Impossible to close the database transaction !", se); } @@ -144,7 +144,7 @@ public class JDBCConnection implements DBConnection<ResultSet> { /* ********************* */ /* INTERROGATION METHODS */ /* ********************* */ - public ResultSet executeQuery(final String sqlQuery, final ADQLQuery adqlQuery) throws DBException { + public ResultSet executeQuery(final String sqlQuery, final ADQLQuery adqlQuery) throws DBException{ try{ Statement stmt = connection.createStatement(); logger.sqlQueryExecuting(this, sqlQuery); @@ -153,38 +153,38 @@ public class JDBCConnection implements DBConnection<ResultSet> { return result; }catch(SQLException se){ logger.sqlQueryError(this, sqlQuery, se); - throw new DBException("Unexpected error while executing a SQL query: "+se.getMessage(), se); + throw new DBException("Unexpected error while executing a SQL query: " + se.getMessage(), se); } } /* ************** */ /* UPLOAD METHODS */ /* ************** */ - public void createSchema(final String schemaName) throws DBException { - String sql = "CREATE SCHEMA "+schemaName+";"; + public void createSchema(final String schemaName) throws DBException{ + String sql = "CREATE SCHEMA " + schemaName + ";"; try{ Statement stmt = connection.createStatement(); stmt.executeUpdate(sql); logger.schemaCreated(this, schemaName); }catch(SQLException se){ - logger.dbError("Impossible to create the schema \""+schemaName+"\" !", se); - throw new DBException("Impossible to create the schema \""+schemaName+"\" !", se); + logger.dbError("Impossible to create the schema \"" + schemaName + "\" !", se); + throw new DBException("Impossible to create the schema \"" + schemaName + "\" !", se); } } - public void dropSchema(final String schemaName) throws DBException { - String sql = "DROP SCHEMA IF EXISTS "+schemaName+" CASCADE;"; + public void dropSchema(final String schemaName) throws DBException{ + String sql = "DROP SCHEMA IF EXISTS " + schemaName + " CASCADE;"; try{ Statement stmt = connection.createStatement(); stmt.executeUpdate(sql); logger.schemaDropped(this, schemaName); }catch(SQLException se){ - logger.dbError("Impossible to drop the schema \""+schemaName+"\" !", se); - throw new DBException("Impossible to drop the schema \""+schemaName+"\" !", se); + logger.dbError("Impossible to drop the schema \"" + schemaName + "\" !", se); + throw new DBException("Impossible to drop the schema \"" + schemaName + "\" !", se); } } - public void createTable(final TAPTable table) throws DBException { + public void createTable(final TAPTable table) throws DBException{ // Build the SQL query: StringBuffer sqlBuf = new StringBuffer(); sqlBuf.append("CREATE TABLE ").append(table.getDBSchemaName()).append('.').append(table.getDBName()).append("("); @@ -204,8 +204,8 @@ public class JDBCConnection implements DBConnection<ResultSet> { stmt.executeUpdate(sql); logger.tableCreated(this, table); }catch(SQLException se){ - logger.dbError("Impossible to create the table \""+table.getFullName()+"\" !", se); - throw new DBException("Impossible to create the table \""+table.getFullName()+"\" !", se); + logger.dbError("Impossible to create the table \"" + table.getFullName() + "\" !", se); + throw new DBException("Impossible to create the table \"" + table.getFullName() + "\" !", se); } } @@ -218,8 +218,8 @@ public class JDBCConnection implements DBConnection<ResultSet> { * * @return The corresponding database type or the given datatype if unknown. */ - public static String getDBType(String datatype, final int arraysize, final TAPLog logger) { - datatype = (datatype == null)?null:datatype.trim().toLowerCase(); + public static String getDBType(String datatype, final int arraysize, final TAPLog logger){ + datatype = (datatype == null) ? null : datatype.trim().toLowerCase(); if (datatype == null || datatype.isEmpty()){ if (logger != null) @@ -228,41 +228,41 @@ public class JDBCConnection implements DBConnection<ResultSet> { } if (datatype.equals("short")) - return (arraysize==1)?"INT2":"BYTEA"; + return (arraysize == 1) ? "INT2" : "BYTEA"; else if (datatype.equals("int")) - return (arraysize==1)?"INT4":"BYTEA"; + return (arraysize == 1) ? "INT4" : "BYTEA"; else if (datatype.equals("long")) - return (arraysize==1)?"INT8":"BYTEA"; + return (arraysize == 1) ? "INT8" : "BYTEA"; else if (datatype.equals("float")) - return (arraysize==1)?"FLOAT4":"BYTEA"; + return (arraysize == 1) ? "FLOAT4" : "BYTEA"; else if (datatype.equals("double")) - return (arraysize==1)?"FLOAT8":"BYTEA"; + return (arraysize == 1) ? "FLOAT8" : "BYTEA"; else if (datatype.equals("boolean")) - return (arraysize==1)?"BOOL":"BYTEA"; + return (arraysize == 1) ? "BOOL" : "BYTEA"; else if (datatype.equals("char")) - return (arraysize==1)?"CHAR(1)":((arraysize<=0)?"VARCHAR":("VARCHAR("+arraysize+")")); + return (arraysize == 1) ? "CHAR(1)" : ((arraysize <= 0) ? "VARCHAR" : ("VARCHAR(" + arraysize + ")")); else if (datatype.equals("unsignedbyte")) return "BYTEA"; else{ if (logger != null) - logger.dbInfo("Warning: unknown datatype: \""+datatype+"\" => considered as \""+datatype+"\" !"); + logger.dbInfo("Warning: unknown datatype: \"" + datatype + "\" => considered as \"" + datatype + "\" !"); return datatype; } } - public void dropTable(final TAPTable table) throws DBException { - String sql = "DROP TABLE "+table.getDBSchemaName()+"."+table.getDBName()+";"; + public void dropTable(final TAPTable table) throws DBException{ + String sql = "DROP TABLE " + table.getDBSchemaName() + "." + table.getDBName() + ";"; try{ Statement stmt = connection.createStatement(); stmt.executeUpdate(sql); logger.tableDropped(this, table); }catch(SQLException se){ - logger.dbError("Impossible to drop the table \""+table.getFullName()+"\" !", se); - throw new DBException("Impossible to drop the table \""+table.getFullName()+"\" !", se); + logger.dbError("Impossible to drop the table \"" + table.getFullName() + "\" !", se); + throw new DBException("Impossible to drop the table \"" + table.getFullName() + "\" !", se); } } - public void insertRow(final SavotTR row, final TAPTable table) throws DBException { + public void insertRow(final SavotTR row, final TAPTable table) throws DBException{ StringBuffer sql = new StringBuffer("INSERT INTO "); sql.append(table.getDBSchemaName()).append('.').append(table.getDBName()).append(" VALUES ("); @@ -270,10 +270,11 @@ public class JDBCConnection implements DBConnection<ResultSet> { Iterator<TAPColumn> it = table.getColumns(); String datatype, value; TAPColumn col; - int i=0; + int i = 0; while(it.hasNext()){ col = it.next(); - if (i>0) sql.append(','); + if (i > 0) + sql.append(','); datatype = col.getDatatype(); value = cells.getContent(i); if (value == null || value.isEmpty()) @@ -295,8 +296,8 @@ public class JDBCConnection implements DBConnection<ResultSet> { int nbInsertedRows = stmt.executeUpdate(sql.toString()); logger.rowsInserted(this, table, nbInsertedRows); }catch(SQLException se){ - logger.dbError("Impossible to insert a row into the table \""+table.getFullName()+"\" !", se); - throw new DBException("Impossible to insert a row in the table \""+table.getFullName()+"\" !", se); + logger.dbError("Impossible to insert a row into the table \"" + table.getFullName() + "\" !", se); + throw new DBException("Impossible to insert a row in the table \"" + table.getFullName() + "\" !", se); } } } diff --git a/src/tap/error/DefaultTAPErrorWriter.java b/src/tap/error/DefaultTAPErrorWriter.java index 2d9b205df36a1ffa93ed3fcee28e1e660bcfdb4f..40534f08d768a3a4a23a3ac052808d79c0e3dde3 100644 --- a/src/tap/error/DefaultTAPErrorWriter.java +++ b/src/tap/error/DefaultTAPErrorWriter.java @@ -55,20 +55,20 @@ public class DefaultTAPErrorWriter extends AbstractServiceErrorWriter { protected final ServiceConnection<?> service; - public DefaultTAPErrorWriter(final ServiceConnection<?> service) { + public DefaultTAPErrorWriter(final ServiceConnection<?> service){ this.service = service; } @Override - protected final UWSLog getLogger() { + protected final UWSLog getLogger(){ return service.getLogger(); } @Override - public void writeError(Throwable t, HttpServletResponse response, HttpServletRequest request, JobOwner user, String action) throws IOException { + public void writeError(Throwable t, HttpServletResponse response, HttpServletRequest request, JobOwner user, String action) throws IOException{ if (t instanceof UWSException){ UWSException ue = (UWSException)t; - formatError(ue, (ue.getMessage() == null || ue.getMessage().trim().isEmpty()), ue.getUWSErrorType(), ue.getHttpErrorCode(), action, user, response, (request != null)?request.getHeader("Accept"):null); + formatError(ue, (ue.getMessage() == null || ue.getMessage().trim().isEmpty()), ue.getUWSErrorType(), ue.getHttpErrorCode(), action, user, response, (request != null) ? request.getHeader("Accept") : null); if (ue.getHttpErrorCode() == UWSException.INTERNAL_SERVER_ERROR) getLogger().error(ue); getLogger().httpRequest(request, user, action, ue.getHttpErrorCode(), ue.getMessage(), ue); diff --git a/src/tap/file/LocalTAPFileManager.java b/src/tap/file/LocalTAPFileManager.java index 2895ea9d3dd0c5bd188cdc569c30cb6f16af366b..2e9beecb5e191f07f0e46b4fd695407287d5171f 100644 --- a/src/tap/file/LocalTAPFileManager.java +++ b/src/tap/file/LocalTAPFileManager.java @@ -67,7 +67,7 @@ public class LocalTAPFileManager extends LocalUWSFileManager implements TAPFileM * @see LocalUWSFileManager#LocalUWSFileManager(File) * @see #getUploadDirectoryName() */ - public LocalTAPFileManager(File root) throws UWSException { + public LocalTAPFileManager(File root) throws UWSException{ super(root); uploadDirectory = new File(rootDirectory, getUploadDirectoryName()); } @@ -89,7 +89,7 @@ public class LocalTAPFileManager extends LocalUWSFileManager implements TAPFileM * @see LocalUWSFileManager#LocalUWSFileManager(File, boolean, boolean) * @see #getUploadDirectoryName() */ - public LocalTAPFileManager(File root, boolean oneDirectoryForEachUser, boolean groupUserDirectories) throws UWSException { + public LocalTAPFileManager(File root, boolean oneDirectoryForEachUser, boolean groupUserDirectories) throws UWSException{ super(root, oneDirectoryForEachUser, groupUserDirectories); uploadDirectory = new File(rootDirectory, getUploadDirectoryName()); } @@ -113,13 +113,13 @@ public class LocalTAPFileManager extends LocalUWSFileManager implements TAPFileM * @see LocalUWSFileManager#LocalUWSFileManager(File, boolean, boolean, OwnerGroupIdentifier) * @see #getUploadDirectoryName() */ - public LocalTAPFileManager(File root, boolean oneDirectoryForEachUser, boolean groupUserDirectories, OwnerGroupIdentifier ownerGroupIdentifier) throws UWSException { + public LocalTAPFileManager(File root, boolean oneDirectoryForEachUser, boolean groupUserDirectories, OwnerGroupIdentifier ownerGroupIdentifier) throws UWSException{ super(root, oneDirectoryForEachUser, groupUserDirectories, ownerGroupIdentifier); uploadDirectory = new File(rootDirectory, getUploadDirectoryName()); } @Override - protected String getLogFileName(final String logTypeGroup) { + protected String getLogFileName(final String logTypeGroup){ if (logTypeGroup != null && logTypeGroup.equals(DBConnection.LOG_TYPE_DB_ACTIVITY.getCustomType())) return DEFAULT_DB_ACTIVITY_LOG_FILE_NAME; else @@ -139,7 +139,7 @@ public class LocalTAPFileManager extends LocalUWSFileManager implements TAPFileM } @Override - public final File getUploadDirectory() { + public final File getUploadDirectory(){ if (uploadDirectory != null && !uploadDirectory.exists()) uploadDirectory.mkdirs(); return uploadDirectory; diff --git a/src/tap/formatter/JSONFormat.java b/src/tap/formatter/JSONFormat.java index 52ab47829030dc02809c81dac8813bb878f65f17..c15625fcff4fae81a515543080c53995756b6750 100644 --- a/src/tap/formatter/JSONFormat.java +++ b/src/tap/formatter/JSONFormat.java @@ -36,7 +36,7 @@ import tap.TAPExecutionReport; import tap.metadata.TAPColumn; import tap.metadata.TAPTypes; -public abstract class JSONFormat<R> implements OutputFormat<R> { +public abstract class JSONFormat< R > implements OutputFormat<R> { /** Indicates whether a format report (start and end date/time) must be printed in the log output. */ private boolean logFormatReport; @@ -44,7 +44,6 @@ public abstract class JSONFormat<R> implements OutputFormat<R> { /** The {@link ServiceConnection} to use (for the log and to have some information about the service (particularly: name, description). */ protected final ServiceConnection<R> service; - public JSONFormat(final ServiceConnection<R> service){ this(service, false); } @@ -54,16 +53,24 @@ public abstract class JSONFormat<R> implements OutputFormat<R> { this.logFormatReport = logFormatReport; } - public String getMimeType() { return "application/json"; } + public String getMimeType(){ + return "application/json"; + } - public String getShortMimeType() { return "json"; } + public String getShortMimeType(){ + return "json"; + } - public String getDescription() { return null; } + public String getDescription(){ + return null; + } - public String getFileExtension() { return "json"; } + public String getFileExtension(){ + return "json"; + } @Override - public void writeResult(R queryResult, OutputStream output, TAPExecutionReport execReport, Thread thread) throws TAPException, InterruptedException { + public void writeResult(R queryResult, OutputStream output, TAPExecutionReport execReport, Thread thread) throws TAPException, InterruptedException{ try{ long start = System.currentTimeMillis(); @@ -84,7 +91,7 @@ public abstract class JSONFormat<R> implements OutputFormat<R> { writer.flush(); if (logFormatReport) - service.getLogger().info("JOB "+execReport.jobID+" WRITTEN\tResult formatted (in JSON ; "+nbRows+" rows ; "+columns.length+" columns) in "+(System.currentTimeMillis()-start)+" ms !"); + service.getLogger().info("JOB " + execReport.jobID + " WRITTEN\tResult formatted (in JSON ; " + nbRows + " rows ; " + columns.length + " columns) in " + (System.currentTimeMillis() - start) + " ms !"); }catch(JSONException je){ throw new TAPException("Error while writing a query result in JSON !", je); }catch(IOException ioe){ @@ -105,7 +112,7 @@ public abstract class JSONFormat<R> implements OutputFormat<R> { * @throws IOException If there is an error while writing the field metadata. * @throws TAPException If there is any other error (by default: never happen). */ - protected void writeFieldMeta(TAPColumn tapCol, JSONWriter out) throws IOException, TAPException, JSONException { + protected void writeFieldMeta(TAPColumn tapCol, JSONWriter out) throws IOException, TAPException, JSONException{ out.object(); out.key("name").value(tapCol.getName()); @@ -153,7 +160,7 @@ public abstract class JSONFormat<R> implements OutputFormat<R> { * @throws IOException If there is an error while writing the given field value in the given stream. * @throws TAPException If there is any other error (by default: never happen). */ - protected void writeFieldValue(final Object value, final DBColumn column, final JSONWriter out) throws IOException, TAPException, JSONException { + protected void writeFieldValue(final Object value, final DBColumn column, final JSONWriter out) throws IOException, TAPException, JSONException{ if (value instanceof Double && (((Double)value).isNaN() || ((Double)value).isInfinite())) out.value((Object)null); else if (value instanceof Float && (((Float)value).isNaN() || ((Float)value).isInfinite())) diff --git a/src/tap/formatter/OutputFormat.java b/src/tap/formatter/OutputFormat.java index d10cd463b171cd772377460a41f9854a19b56597..13fa7c22bf77f3efcd09b80fbda9e092bb407e3a 100644 --- a/src/tap/formatter/OutputFormat.java +++ b/src/tap/formatter/OutputFormat.java @@ -35,7 +35,7 @@ import tap.TAPExecutionReport; * * @see VOTableFormat */ -public interface OutputFormat<R> { +public interface OutputFormat< R > { /** * Gets the MIME type corresponding to this format. diff --git a/src/tap/formatter/ResultSet2JsonFormatter.java b/src/tap/formatter/ResultSet2JsonFormatter.java index 95a83492ac41885eede92aac786375655853e5f3..d7e47f860da0a97f689eb83d1bdf439e88a56b04 100644 --- a/src/tap/formatter/ResultSet2JsonFormatter.java +++ b/src/tap/formatter/ResultSet2JsonFormatter.java @@ -39,16 +39,16 @@ import adql.db.DBColumn; public class ResultSet2JsonFormatter extends JSONFormat<ResultSet> implements ResultSetFormatter { - public ResultSet2JsonFormatter(ServiceConnection<ResultSet> service, boolean logFormatReport) { + public ResultSet2JsonFormatter(ServiceConnection<ResultSet> service, boolean logFormatReport){ super(service, logFormatReport); } - public ResultSet2JsonFormatter(ServiceConnection<ResultSet> service) { + public ResultSet2JsonFormatter(ServiceConnection<ResultSet> service){ super(service); } @Override - protected DBColumn[] writeMetadata(ResultSet queryResult, JSONWriter out, TAPExecutionReport execReport, Thread thread) throws IOException, TAPException, InterruptedException, JSONException { + protected DBColumn[] writeMetadata(ResultSet queryResult, JSONWriter out, TAPExecutionReport execReport, Thread thread) throws IOException, TAPException, InterruptedException, JSONException{ out.array(); DBColumn[] selectedColumns = execReport.resultingColumns; @@ -63,8 +63,8 @@ public class ResultSet2JsonFormatter extends JSONFormat<ResultSet> implements Re }catch(ClassCastException ex){ tapCol = new TAPColumn(field.getADQLName()); tapCol.setDatatype(meta.getColumnTypeName(indField), TAPTypes.NO_SIZE); - service.getLogger().warning("Unknown DB datatype for the field \""+tapCol.getName()+"\" ! It is supposed to be \""+tapCol.getDatatype()+"\" (original value: \""+meta.getColumnTypeName(indField)+"\")."); - selectedColumns[indField-1] = tapCol; + service.getLogger().warning("Unknown DB datatype for the field \"" + tapCol.getName() + "\" ! It is supposed to be \"" + tapCol.getDatatype() + "\" (original value: \"" + meta.getColumnTypeName(indField) + "\")."); + selectedColumns[indField - 1] = tapCol; } writeFieldMeta(tapCol, out); indField++; @@ -73,8 +73,8 @@ public class ResultSet2JsonFormatter extends JSONFormat<ResultSet> implements Re throw new InterruptedException(); } } - } catch (SQLException e) { - service.getLogger().error("Job N°"+execReport.jobID+" - Impossible to get the metadata of the given ResultSet !", e); + }catch(SQLException e){ + service.getLogger().error("Job N°" + execReport.jobID + " - Impossible to get the metadata of the given ResultSet !", e); } out.endArray(); @@ -82,7 +82,7 @@ public class ResultSet2JsonFormatter extends JSONFormat<ResultSet> implements Re } @Override - protected int writeData(ResultSet queryResult, DBColumn[] selectedColumns, JSONWriter out, TAPExecutionReport execReport, Thread thread) throws IOException, TAPException, InterruptedException, JSONException { + protected int writeData(ResultSet queryResult, DBColumn[] selectedColumns, JSONWriter out, TAPExecutionReport execReport, Thread thread) throws IOException, TAPException, InterruptedException, JSONException{ out.array(); int nbRows = 0; try{ @@ -93,9 +93,9 @@ public class ResultSet2JsonFormatter extends JSONFormat<ResultSet> implements Re out.array(); Object value; - for(int i=1; i<=nbColumns; i++){ - value = formatValue(queryResult.getObject(i), selectedColumns[i-1]); - writeFieldValue(value, selectedColumns[i-1], out); + for(int i = 1; i <= nbColumns; i++){ + value = formatValue(queryResult.getObject(i), selectedColumns[i - 1]); + writeFieldValue(value, selectedColumns[i - 1], out); if (thread.isInterrupted()) throw new InterruptedException(); } @@ -106,7 +106,7 @@ public class ResultSet2JsonFormatter extends JSONFormat<ResultSet> implements Re throw new InterruptedException(); } }catch(SQLException se){ - throw new TAPException("Job N°"+execReport.jobID+" - Impossible to get the "+(nbRows+1)+"-th rows from the given ResultSet !", se); + throw new TAPException("Job N°" + execReport.jobID + " - Impossible to get the " + (nbRows + 1) + "-th rows from the given ResultSet !", se); } out.endArray(); @@ -114,7 +114,7 @@ public class ResultSet2JsonFormatter extends JSONFormat<ResultSet> implements Re } @Override - public Object formatValue(Object value, DBColumn colMeta) { + public Object formatValue(Object value, DBColumn colMeta){ return value; } diff --git a/src/tap/formatter/ResultSet2SVFormatter.java b/src/tap/formatter/ResultSet2SVFormatter.java index 808bcafe6bbb659abf9e4d794bd48fe631da5b5a..628957071ee609e48f2db64d99bfde961803610d 100644 --- a/src/tap/formatter/ResultSet2SVFormatter.java +++ b/src/tap/formatter/ResultSet2SVFormatter.java @@ -33,32 +33,32 @@ import tap.TAPExecutionReport; public class ResultSet2SVFormatter extends SVFormat<ResultSet> implements ResultSetFormatter { - public ResultSet2SVFormatter(final ServiceConnection<ResultSet> service, char colSeparator, boolean delimitStrings) { + public ResultSet2SVFormatter(final ServiceConnection<ResultSet> service, char colSeparator, boolean delimitStrings){ super(service, colSeparator, delimitStrings); } - public ResultSet2SVFormatter(final ServiceConnection<ResultSet> service, char colSeparator) { + public ResultSet2SVFormatter(final ServiceConnection<ResultSet> service, char colSeparator){ super(service, colSeparator); } - public ResultSet2SVFormatter(final ServiceConnection<ResultSet> service, String colSeparator, boolean delimitStrings) { + public ResultSet2SVFormatter(final ServiceConnection<ResultSet> service, String colSeparator, boolean delimitStrings){ super(service, colSeparator, delimitStrings); } - public ResultSet2SVFormatter(final ServiceConnection<ResultSet> service, String colSeparator) { + public ResultSet2SVFormatter(final ServiceConnection<ResultSet> service, String colSeparator){ super(service, colSeparator); } @Override - protected DBColumn[] writeMetadata(ResultSet queryResult, PrintWriter writer, TAPExecutionReport execReport, Thread thread) throws IOException, TAPException, InterruptedException { + protected DBColumn[] writeMetadata(ResultSet queryResult, PrintWriter writer, TAPExecutionReport execReport, Thread thread) throws IOException, TAPException, InterruptedException{ DBColumn[] selectedColumns = execReport.resultingColumns; int nbColumns = (selectedColumns == null) ? -1 : selectedColumns.length; if (nbColumns > 0){ - for(int i=0; i<nbColumns-1; i++){ + for(int i = 0; i < nbColumns - 1; i++){ writer.print(selectedColumns[i].getADQLName()); writer.print(separator); } - writer.print(selectedColumns[nbColumns-1].getADQLName()); + writer.print(selectedColumns[nbColumns - 1].getADQLName()); writer.println(); writer.flush(); } @@ -66,7 +66,7 @@ public class ResultSet2SVFormatter extends SVFormat<ResultSet> implements Result } @Override - protected int writeData(ResultSet queryResult, DBColumn[] selectedColumns, PrintWriter writer, TAPExecutionReport execReport, Thread thread) throws IOException, TAPException, InterruptedException { + protected int writeData(ResultSet queryResult, DBColumn[] selectedColumns, PrintWriter writer, TAPExecutionReport execReport, Thread thread) throws IOException, TAPException, InterruptedException{ int nbRows = 0; try{ int nbColumns = queryResult.getMetaData().getColumnCount(); @@ -75,9 +75,9 @@ public class ResultSet2SVFormatter extends SVFormat<ResultSet> implements Result break; Object value; - for(int i=1; i<=nbColumns; i++){ - value = formatValue(queryResult.getObject(i), selectedColumns[i-1]); - writeFieldValue(value, selectedColumns[i-1], writer); + for(int i = 1; i <= nbColumns; i++){ + value = formatValue(queryResult.getObject(i), selectedColumns[i - 1]); + writeFieldValue(value, selectedColumns[i - 1], writer); if (i != nbColumns) writer.print(separator); if (thread.isInterrupted()) @@ -91,7 +91,7 @@ public class ResultSet2SVFormatter extends SVFormat<ResultSet> implements Result } writer.flush(); }catch(SQLException se){ - throw new TAPException("Job N°"+execReport.jobID+" - Impossible to get the "+(nbRows+1)+"-th rows from the given ResultSet !", se); + throw new TAPException("Job N°" + execReport.jobID + " - Impossible to get the " + (nbRows + 1) + "-th rows from the given ResultSet !", se); } return nbRows; diff --git a/src/tap/formatter/ResultSet2TextFormatter.java b/src/tap/formatter/ResultSet2TextFormatter.java index 1076993b7b938ad77eba02cbf4d065dbba96515b..045bf804ec630856dc7032f3a832fb4de844e1de 100644 --- a/src/tap/formatter/ResultSet2TextFormatter.java +++ b/src/tap/formatter/ResultSet2TextFormatter.java @@ -32,25 +32,25 @@ import tap.TAPExecutionReport; public class ResultSet2TextFormatter extends TextFormat<ResultSet> implements ResultSetFormatter { - public ResultSet2TextFormatter(ServiceConnection<ResultSet> service) { + public ResultSet2TextFormatter(ServiceConnection<ResultSet> service){ super(service); } @Override - protected String getHeader(ResultSet queryResult, TAPExecutionReport execReport, Thread thread) throws TAPException { + protected String getHeader(ResultSet queryResult, TAPExecutionReport execReport, Thread thread) throws TAPException{ DBColumn[] selectedColumns = execReport.resultingColumns; StringBuffer line = new StringBuffer(); int nbColumns = (selectedColumns == null) ? -1 : selectedColumns.length; if (nbColumns > 0){ - for(int i=0; i<nbColumns-1; i++) + for(int i = 0; i < nbColumns - 1; i++) line.append(selectedColumns[i].getADQLName()).append('|'); - line.append(selectedColumns[nbColumns-1].getADQLName()); + line.append(selectedColumns[nbColumns - 1].getADQLName()); } return line.toString(); } @Override - protected int writeData(ResultSet queryResult, AsciiTable asciiTable, TAPExecutionReport execReport, Thread thread) throws TAPException { + protected int writeData(ResultSet queryResult, AsciiTable asciiTable, TAPExecutionReport execReport, Thread thread) throws TAPException{ int nbRows = 0; try{ DBColumn[] selectedColumns = execReport.resultingColumns; @@ -62,9 +62,9 @@ public class ResultSet2TextFormatter extends TextFormat<ResultSet> implements Re line.delete(0, line.length()); Object value; - for(int i=1; i<=nbColumns; i++){ - value = formatValue(queryResult.getObject(i), selectedColumns[i-1]); - writeFieldValue(value, selectedColumns[i-1], line); + for(int i = 1; i <= nbColumns; i++){ + value = formatValue(queryResult.getObject(i), selectedColumns[i - 1]); + writeFieldValue(value, selectedColumns[i - 1], line); if (i != nbColumns) line.append('|'); } @@ -72,13 +72,13 @@ public class ResultSet2TextFormatter extends TextFormat<ResultSet> implements Re nbRows++; } }catch(SQLException se){ - throw new TAPException("Job N°"+execReport.jobID+" - Impossible to get the "+(nbRows+1)+"-th rows from the given ResultSet !", se); + throw new TAPException("Job N°" + execReport.jobID + " - Impossible to get the " + (nbRows + 1) + "-th rows from the given ResultSet !", se); } return nbRows; } @Override - public Object formatValue(Object value, DBColumn colMeta) { + public Object formatValue(Object value, DBColumn colMeta){ return value; } diff --git a/src/tap/formatter/ResultSet2VotableFormatter.java b/src/tap/formatter/ResultSet2VotableFormatter.java index ee0d751279821f4e5677acf3f76ea47c32ede753..cc841bda7d57f4635c187bde4edaffeff0b2cc2c 100644 --- a/src/tap/formatter/ResultSet2VotableFormatter.java +++ b/src/tap/formatter/ResultSet2VotableFormatter.java @@ -45,30 +45,30 @@ import adql.db.DBColumn; */ public class ResultSet2VotableFormatter extends VOTableFormat<ResultSet> implements ResultSetFormatter { - public ResultSet2VotableFormatter(final ServiceConnection<ResultSet> service) throws NullPointerException { + public ResultSet2VotableFormatter(final ServiceConnection<ResultSet> service) throws NullPointerException{ super(service); } - public ResultSet2VotableFormatter(final ServiceConnection<ResultSet> service, final boolean logFormatReport) throws NullPointerException { + public ResultSet2VotableFormatter(final ServiceConnection<ResultSet> service, final boolean logFormatReport) throws NullPointerException{ super(service, logFormatReport); } @Override - protected DBColumn[] writeMetadata(final ResultSet queryResult, final PrintWriter output, final TAPExecutionReport execReport, final Thread thread) throws IOException, TAPException, InterruptedException { + protected DBColumn[] writeMetadata(final ResultSet queryResult, final PrintWriter output, final TAPExecutionReport execReport, final Thread thread) throws IOException, TAPException, InterruptedException{ DBColumn[] selectedColumns = execReport.resultingColumns; - try { + try{ ResultSetMetaData meta = queryResult.getMetaData(); int indField = 1; if (selectedColumns != null){ for(DBColumn field : selectedColumns){ TAPColumn tapCol = null; - try { + try{ tapCol = (TAPColumn)field; - } catch(ClassCastException ex){ + }catch(ClassCastException ex){ tapCol = new TAPColumn(field.getADQLName()); tapCol.setDatatype(meta.getColumnTypeName(indField), TAPTypes.NO_SIZE); - service.getLogger().warning("Unknown DB datatype for the field \""+tapCol.getName()+"\" ! It is supposed to be \""+tapCol.getDatatype()+"\" (original value: \""+meta.getColumnTypeName(indField)+"\")."); - selectedColumns[indField-1] = tapCol; + service.getLogger().warning("Unknown DB datatype for the field \"" + tapCol.getName() + "\" ! It is supposed to be \"" + tapCol.getDatatype() + "\" (original value: \"" + meta.getColumnTypeName(indField) + "\")."); + selectedColumns[indField - 1] = tapCol; } writeFieldMeta(tapCol, output); indField++; @@ -77,17 +77,17 @@ public class ResultSet2VotableFormatter extends VOTableFormat<ResultSet> impleme throw new InterruptedException(); } } - } catch (SQLException e) { - service.getLogger().error("Job N°"+execReport.jobID+" - Impossible to get the metadata of the given ResultSet !", e); + }catch(SQLException e){ + service.getLogger().error("Job N°" + execReport.jobID + " - Impossible to get the metadata of the given ResultSet !", e); output.println("<INFO name=\"WARNING\" value=\"MISSING_META\">Error while getting field(s) metadata</INFO>"); } return selectedColumns; } @Override - protected int writeData(final ResultSet queryResult, final DBColumn[] selectedColumns, final OutputStream output, final TAPExecutionReport execReport, final Thread thread) throws IOException, TAPException, InterruptedException { + protected int writeData(final ResultSet queryResult, final DBColumn[] selectedColumns, final OutputStream output, final TAPExecutionReport execReport, final Thread thread) throws IOException, TAPException, InterruptedException{ int nbRows = 0; - try { + try{ output.write("\t\t\t\t<TABLEDATA>\n".getBytes()); int nbColumns = queryResult.getMetaData().getColumnCount(); while(queryResult.next()){ @@ -96,10 +96,10 @@ public class ResultSet2VotableFormatter extends VOTableFormat<ResultSet> impleme output.write("\t\t\t\t\t<TR>\n".getBytes()); Object value; - for(int i=1; i<=nbColumns; i++){ + for(int i = 1; i <= nbColumns; i++){ output.write("\t\t\t\t\t\t<TD>".getBytes()); - value = formatValue(queryResult.getObject(i), selectedColumns[i-1]); - writeFieldValue(value, selectedColumns[i-1], output); + value = formatValue(queryResult.getObject(i), selectedColumns[i - 1]); + writeFieldValue(value, selectedColumns[i - 1], output); output.write("</TD>\n".getBytes()); if (thread.isInterrupted()) @@ -114,13 +114,13 @@ public class ResultSet2VotableFormatter extends VOTableFormat<ResultSet> impleme } output.write("\t\t\t\t</TABLEDATA>\n".getBytes()); return nbRows; - } catch (SQLException e) { - throw new TAPException("Job N°"+execReport.jobID+" - Impossible to get the "+(nbRows+1)+"-th rows from the given ResultSet !", e); + }catch(SQLException e){ + throw new TAPException("Job N°" + execReport.jobID + " - Impossible to get the " + (nbRows + 1) + "-th rows from the given ResultSet !", e); } } @Override - public Object formatValue(Object value, DBColumn colMeta) { + public Object formatValue(Object value, DBColumn colMeta){ return value; } diff --git a/src/tap/formatter/SVFormat.java b/src/tap/formatter/SVFormat.java index a4e0822ece90e1139b55a75a6b72fda900701fc3..259fff2ef5129a7f1013c079edd7080c4eed363c 100644 --- a/src/tap/formatter/SVFormat.java +++ b/src/tap/formatter/SVFormat.java @@ -29,7 +29,7 @@ import tap.ServiceConnection; import tap.TAPException; import tap.TAPExecutionReport; -public abstract class SVFormat<R> implements OutputFormat<R> { +public abstract class SVFormat< R > implements OutputFormat<R> { /** Indicates whether a format report (start and end date/time) must be printed in the log output. */ private boolean logFormatReport; @@ -52,7 +52,7 @@ public abstract class SVFormat<R> implements OutputFormat<R> { } public SVFormat(final ServiceConnection<R> service, char colSeparator, boolean delimitStrings, final boolean logFormatReport){ - separator = ""+colSeparator; + separator = "" + colSeparator; delimitStr = delimitStrings; this.service = service; this.logFormatReport = logFormatReport; @@ -63,51 +63,53 @@ public abstract class SVFormat<R> implements OutputFormat<R> { } public SVFormat(final ServiceConnection<R> service, String colSeparator, boolean delimitStrings){ - separator = (colSeparator==null)?(""+COMMA_SEPARATOR):colSeparator; + separator = (colSeparator == null) ? ("" + COMMA_SEPARATOR) : colSeparator; delimitStr = delimitStrings; this.service = service; } - public String getMimeType() { + public String getMimeType(){ switch(separator.charAt(0)){ - case COMMA_SEPARATOR: - case SEMI_COLON_SEPARATOR: - return "text/csv"; - case TAB_SEPARATOR: - return "text/tsv"; - default: - return "text/plain"; + case COMMA_SEPARATOR: + case SEMI_COLON_SEPARATOR: + return "text/csv"; + case TAB_SEPARATOR: + return "text/tsv"; + default: + return "text/plain"; } } - public String getShortMimeType() { + public String getShortMimeType(){ switch(separator.charAt(0)){ - case COMMA_SEPARATOR: - case SEMI_COLON_SEPARATOR: - return "csv"; - case TAB_SEPARATOR: - return "tsv"; - default: - return "text"; + case COMMA_SEPARATOR: + case SEMI_COLON_SEPARATOR: + return "csv"; + case TAB_SEPARATOR: + return "tsv"; + default: + return "text"; } } - public String getDescription() { return null; } + public String getDescription(){ + return null; + } - public String getFileExtension() { + public String getFileExtension(){ switch(separator.charAt(0)){ - case COMMA_SEPARATOR: - case SEMI_COLON_SEPARATOR: - return "csv"; - case TAB_SEPARATOR: - return "tsv"; - default: - return "txt"; + case COMMA_SEPARATOR: + case SEMI_COLON_SEPARATOR: + return "csv"; + case TAB_SEPARATOR: + return "tsv"; + default: + return "txt"; } } @Override - public void writeResult(R queryResult, OutputStream output, TAPExecutionReport execReport, Thread thread) throws TAPException, InterruptedException { + public void writeResult(R queryResult, OutputStream output, TAPExecutionReport execReport, Thread thread) throws TAPException, InterruptedException{ try{ final long startTime = System.currentTimeMillis(); @@ -122,7 +124,7 @@ public abstract class SVFormat<R> implements OutputFormat<R> { writer.flush(); if (logFormatReport) - service.getLogger().info("JOB "+execReport.jobID+" WRITTEN\tResult formatted (in SV["+delimitStr+"] ; "+nbRows+" rows ; "+columns.length+" columns) in "+(System.currentTimeMillis()-startTime)+" ms !"); + service.getLogger().info("JOB " + execReport.jobID + " WRITTEN\tResult formatted (in SV[" + delimitStr + "] ; " + nbRows + " rows ; " + columns.length + " columns) in " + (System.currentTimeMillis() - startTime) + " ms !"); }catch(Exception ex){ service.getLogger().error("While formatting in (T/C)SV !", ex); @@ -148,7 +150,7 @@ public abstract class SVFormat<R> implements OutputFormat<R> { * @throws IOException If there is an error while writing the given field value in the given stream. * @throws TAPException If there is any other error (by default: never happen). */ - protected void writeFieldValue(final Object value, final DBColumn column, final PrintWriter writer) throws IOException, TAPException { + protected void writeFieldValue(final Object value, final DBColumn column, final PrintWriter writer) throws IOException, TAPException{ if (value != null){ if ((delimitStr && value instanceof String) || value.toString().contains(separator)){ writer.print('"'); diff --git a/src/tap/formatter/TextFormat.java b/src/tap/formatter/TextFormat.java index fc65fa71aec6f94c74249263ba5c8b8f77107919..9c5c73486ea6a506e802647ad805b9381c70dba8 100644 --- a/src/tap/formatter/TextFormat.java +++ b/src/tap/formatter/TextFormat.java @@ -30,7 +30,7 @@ import tap.ServiceConnection; import tap.TAPException; import tap.TAPExecutionReport; -public abstract class TextFormat<R> implements OutputFormat<R> { +public abstract class TextFormat< R > implements OutputFormat<R> { /** Indicates whether a format report (start and end date/time) must be printed in the log output. */ private boolean logFormatReport; @@ -46,16 +46,24 @@ public abstract class TextFormat<R> implements OutputFormat<R> { this.logFormatReport = logFormatReport; } - public String getMimeType() { return "text/plain"; } + public String getMimeType(){ + return "text/plain"; + } - public String getShortMimeType() { return "text"; } + public String getShortMimeType(){ + return "text"; + } - public String getDescription() { return null; } + public String getDescription(){ + return null; + } - public String getFileExtension() { return "txt"; } + public String getFileExtension(){ + return "txt"; + } @Override - public void writeResult(R queryResult, OutputStream output, TAPExecutionReport execReport, Thread thread) throws TAPException, InterruptedException { + public void writeResult(R queryResult, OutputStream output, TAPExecutionReport execReport, Thread thread) throws TAPException, InterruptedException{ try{ AsciiTable asciiTable = new AsciiTable('|'); @@ -78,7 +86,7 @@ public abstract class TextFormat<R> implements OutputFormat<R> { output.flush(); if (logFormatReport) - service.getLogger().info("JOB "+execReport.jobID+" WRITTEN\tResult formatted (in text ; "+nbRows+" rows ; "+((execReport != null && execReport.resultingColumns != null)?"?":execReport.resultingColumns.length)+" columns) in "+(System.currentTimeMillis()-startTime)+" ms !"); + service.getLogger().info("JOB " + execReport.jobID + " WRITTEN\tResult formatted (in text ; " + nbRows + " rows ; " + ((execReport != null && execReport.resultingColumns != null) ? "?" : execReport.resultingColumns.length) + " columns) in " + (System.currentTimeMillis() - startTime) + " ms !"); }catch(Exception ex){ service.getLogger().error("While formatting in text/plain !", ex); diff --git a/src/tap/formatter/VOTableFormat.java b/src/tap/formatter/VOTableFormat.java index c2df9c74be48941fc3003beda7a3dcce5efcafc1..e5b5625f2d281679f9e6efd6b103e8196db39070 100644 --- a/src/tap/formatter/VOTableFormat.java +++ b/src/tap/formatter/VOTableFormat.java @@ -63,7 +63,7 @@ import adql.db.DBColumn; * * @see ResultSet2VotableFormatter */ -public abstract class VOTableFormat<R> implements OutputFormat<R> { +public abstract class VOTableFormat< R > implements OutputFormat<R> { /** Indicates whether a format report (start and end date/time) must be printed in the log output. */ private boolean logFormatReport; @@ -86,7 +86,7 @@ public abstract class VOTableFormat<R> implements OutputFormat<R> { * * @see #VOTableFormat(ServiceConnection, boolean) */ - public VOTableFormat(final ServiceConnection<R> service) throws NullPointerException { + public VOTableFormat(final ServiceConnection<R> service) throws NullPointerException{ this(service, false); } @@ -98,20 +98,28 @@ public abstract class VOTableFormat<R> implements OutputFormat<R> { * * @throws NullPointerException If the given service connection is <code>null</code>. */ - public VOTableFormat(final ServiceConnection<R> service, final boolean logFormatReport) throws NullPointerException { + public VOTableFormat(final ServiceConnection<R> service, final boolean logFormatReport) throws NullPointerException{ if (service == null) throw new NullPointerException("The given service connection is NULL !"); this.service = service; this.logFormatReport = logFormatReport; } - public final String getMimeType() { return "text/xml"; } + public final String getMimeType(){ + return "text/xml"; + } - public final String getShortMimeType() { return "votable"; } + public final String getShortMimeType(){ + return "votable"; + } - public String getDescription() { return null; } + public String getDescription(){ + return null; + } - public String getFileExtension() { return "xml"; } + public String getFileExtension(){ + return "xml"; + } /** * <p>The skeleton of the resulting VOTable is written in this method:</p> @@ -129,7 +137,7 @@ public abstract class VOTableFormat<R> implements OutputFormat<R> { * * @see tap.formatter.OutputFormat#writeResult(Object, OutputStream, TAPExecutionReport) */ - public final void writeResult(final R queryResult, final OutputStream output, final TAPExecutionReport execReport, final Thread thread) throws TAPException, InterruptedException { + public final void writeResult(final R queryResult, final OutputStream output, final TAPExecutionReport execReport, final Thread thread) throws TAPException, InterruptedException{ try{ long start = System.currentTimeMillis(); @@ -152,7 +160,7 @@ public abstract class VOTableFormat<R> implements OutputFormat<R> { out.flush(); if (logFormatReport) - service.getLogger().info("JOB "+execReport.jobID+" WRITTEN\tResult formatted (in VOTable ; "+nbRows+" rows ; "+columns.length+" columns) in "+(System.currentTimeMillis()-start)+" ms !"); + service.getLogger().info("JOB " + execReport.jobID + " WRITTEN\tResult formatted (in VOTable ; " + nbRows + " rows ; " + columns.length + " columns) in " + (System.currentTimeMillis() - start) + " ms !"); }catch(IOException ioe){ throw new TAPException("Error while writing a query result in VOTable !", ioe); } @@ -172,7 +180,7 @@ public abstract class VOTableFormat<R> implements OutputFormat<R> { * @throws IOException If there is an error while writing the root node in the given Writer. * @throws TAPException If there is any other error (by default: never happen). */ - protected void writeHeader(final PrintWriter output, final TAPExecutionReport execReport) throws IOException, TAPException { + protected void writeHeader(final PrintWriter output, final TAPExecutionReport execReport) throws IOException, TAPException{ StringBuffer strBuf = new StringBuffer("<VOTABLE"); if (votTableVersion != null) strBuf.append(" version=\"").append(SavotWriter.encodeAttribute(votTableVersion)).append('\"'); @@ -191,8 +199,8 @@ public abstract class VOTableFormat<R> implements OutputFormat<R> { // INFO items: output.println("\t\t<INFO name=\"QUERY_STATUS\" value=\"OK\" />"); - output.println("\t\t<INFO name=\"PROVIDER\" value=\""+((service.getProviderName()==null)?"":SavotWriter.encodeAttribute(service.getProviderName()))+"\">"+((service.getProviderDescription()==null)?"":SavotWriter.encodeElement(service.getProviderDescription()))+"</INFO>"); - output.println("\t\t<INFO name=\"QUERY\"><![CDATA["+execReport.parameters.getQuery()+"]]></INFO>"); + output.println("\t\t<INFO name=\"PROVIDER\" value=\"" + ((service.getProviderName() == null) ? "" : SavotWriter.encodeAttribute(service.getProviderName())) + "\">" + ((service.getProviderDescription() == null) ? "" : SavotWriter.encodeElement(service.getProviderDescription())) + "</INFO>"); + output.println("\t\t<INFO name=\"QUERY\"><![CDATA[" + execReport.parameters.getQuery() + "]]></INFO>"); } /** @@ -223,7 +231,7 @@ public abstract class VOTableFormat<R> implements OutputFormat<R> { * @throws IOException If there is an error while writing the field metadata. * @throws TAPException If there is any other error (by default: never happen). */ - protected void writeFieldMeta(TAPColumn col, PrintWriter out) throws IOException, TAPException { + protected void writeFieldMeta(TAPColumn col, PrintWriter out) throws IOException, TAPException{ StringBuffer fieldline = new StringBuffer("\t\t\t"); fieldline.append("<FIELD ID=").append('"').append(SavotWriter.encodeAttribute(col.getADQLName())).append('"'); @@ -248,15 +256,15 @@ public abstract class VOTableFormat<R> implements OutputFormat<R> { else description = null; - if (nullVal != null || description != null) { + if (nullVal != null || description != null){ fieldline.append(">\n"); if (nullVal != null) - fieldline.append("<VALUES null=\""+nullVal+"\" />\n"); + fieldline.append("<VALUES null=\"" + nullVal + "\" />\n"); if (description != null) fieldline.append("<DESCRIPTION>").append(SavotWriter.encodeElement(description)).append("</DESCRIPTION>\n"); fieldline.append("</FIELD>"); out.println(fieldline); - } else { + }else{ fieldline.append("/>"); out.println(fieldline); } @@ -295,8 +303,8 @@ public abstract class VOTableFormat<R> implements OutputFormat<R> { * @throws IOException If there is an error while writing the given field value in the given stream. * @throws TAPException If there is any other error (by default: never happen). */ - protected void writeFieldValue(final Object value, final DBColumn column, final OutputStream output) throws IOException, TAPException { - String fieldValue = (value==null)?null:value.toString(); + protected void writeFieldValue(final Object value, final DBColumn column, final OutputStream output) throws IOException, TAPException{ + String fieldValue = (value == null) ? null : value.toString(); if (fieldValue == null && column instanceof TAPColumn) fieldValue = getNullValue(((TAPColumn)column).getVotType().datatype); if (fieldValue != null) @@ -323,11 +331,11 @@ public abstract class VOTableFormat<R> implements OutputFormat<R> { datatype = datatype.trim().toLowerCase(); if (datatype.equals("short")) - return ""+Short.MIN_VALUE; + return "" + Short.MIN_VALUE; else if (datatype.equals("int")) - return ""+Integer.MIN_VALUE; + return "" + Integer.MIN_VALUE; else if (datatype.equals("long")) - return ""+Long.MIN_VALUE; + return "" + Long.MIN_VALUE; else return null; } diff --git a/src/tap/log/DefaultTAPLog.java b/src/tap/log/DefaultTAPLog.java index d6458fa8ea20df0f40aea2acaee41a371e3741fb..62b6971bcef008cfa401467d91059598b8cd2be1 100644 --- a/src/tap/log/DefaultTAPLog.java +++ b/src/tap/log/DefaultTAPLog.java @@ -42,20 +42,20 @@ import uws.service.log.DefaultUWSLog; */ public class DefaultTAPLog extends DefaultUWSLog implements TAPLog { - public DefaultTAPLog(TAPFileManager fm) { + public DefaultTAPLog(TAPFileManager fm){ super(fm); } - public DefaultTAPLog(OutputStream output) { + public DefaultTAPLog(OutputStream output){ super(output); } - public DefaultTAPLog(PrintWriter writer) { + public DefaultTAPLog(PrintWriter writer){ super(writer); } public void queryFinished(final TAPExecutionReport report){ - StringBuffer buffer = new StringBuffer("QUERY END FOR "+report.jobID+""); + StringBuffer buffer = new StringBuffer("QUERY END FOR " + report.jobID + ""); buffer.append(" - success ? ").append(report.success); buffer.append(" - synchronous ? ").append(report.synchronous); buffer.append(" - total duration = ").append(report.getTotalDuration()).append("ms"); @@ -72,8 +72,8 @@ public class DefaultTAPLog extends DefaultUWSLog implements TAPLog { } public void dbActivity(final String message, final Throwable t){ - String msgType = (t == null) ? "[INFO] ": "[ERROR] "; - log(DBConnection.LOG_TYPE_DB_ACTIVITY, ((message==null)?null:(msgType+message)), t); + String msgType = (t == null) ? "[INFO] " : "[ERROR] "; + log(DBConnection.LOG_TYPE_DB_ACTIVITY, ((message == null) ? null : (msgType + message)), t); } public void dbInfo(final String message){ @@ -85,82 +85,82 @@ public class DefaultTAPLog extends DefaultUWSLog implements TAPLog { } @Override - public void tapMetadataFetched(TAPMetadata metadata) { + public void tapMetadataFetched(TAPMetadata metadata){ dbActivity("TAP metadata fetched from the database !"); } @Override - public void tapMetadataLoaded(TAPMetadata metadata) { + public void tapMetadataLoaded(TAPMetadata metadata){ dbActivity("TAP metadata loaded into the database !"); } @Override - public void connectionOpened(DBConnection<?> connection, String dbName) { + public void connectionOpened(DBConnection<?> connection, String dbName){ //dbActivity("A connection has been opened to the database \""+dbName+"\" !"); } @Override - public void connectionClosed(DBConnection<?> connection) { + public void connectionClosed(DBConnection<?> connection){ //dbActivity("A database connection has been closed !"); } @Override - public void transactionStarted(final DBConnection<?> connection) { + public void transactionStarted(final DBConnection<?> connection){ //dbActivity("A transaction has been started !"); } @Override - public void transactionCancelled(final DBConnection<?> connection) { + public void transactionCancelled(final DBConnection<?> connection){ //dbActivity("A transaction has been cancelled !"); } @Override - public void transactionEnded(final DBConnection<?> connection) { + public void transactionEnded(final DBConnection<?> connection){ //dbActivity("A transaction has been ended/commited !"); } @Override - public void schemaCreated(final DBConnection<?> connection, String schema) { - dbActivity("CREATE SCHEMA \""+schema+"\"\t"+connection.getID()); + public void schemaCreated(final DBConnection<?> connection, String schema){ + dbActivity("CREATE SCHEMA \"" + schema + "\"\t" + connection.getID()); } @Override - public void schemaDropped(final DBConnection<?> connection, String schema) { - dbActivity("DROP SCHEMA \""+schema+"\"\t"+connection.getID()); + public void schemaDropped(final DBConnection<?> connection, String schema){ + dbActivity("DROP SCHEMA \"" + schema + "\"\t" + connection.getID()); } protected final String getFullDBName(final TAPTable table){ - return (table.getSchema()!=null) ? (table.getSchema().getDBName()+".") : ""; + return (table.getSchema() != null) ? (table.getSchema().getDBName() + ".") : ""; } @Override - public void tableCreated(final DBConnection<?> connection, TAPTable table) { - dbActivity("CREATE TABLE \""+getFullDBName(table)+"\" (ADQL name: \""+table.getFullName()+"\")\t"+connection.getID()); + public void tableCreated(final DBConnection<?> connection, TAPTable table){ + dbActivity("CREATE TABLE \"" + getFullDBName(table) + "\" (ADQL name: \"" + table.getFullName() + "\")\t" + connection.getID()); } @Override - public void tableDropped(final DBConnection<?> connection, TAPTable table) { - dbActivity("DROP TABLE \""+getFullDBName(table)+"\" (ADQL name: \""+table.getFullName()+"\")\t"+connection.getID()); + public void tableDropped(final DBConnection<?> connection, TAPTable table){ + dbActivity("DROP TABLE \"" + getFullDBName(table) + "\" (ADQL name: \"" + table.getFullName() + "\")\t" + connection.getID()); } @Override - public void rowsInserted(final DBConnection<?> connection, TAPTable table, int nbInsertedRows) { - dbActivity("INSERT ROWS ("+((nbInsertedRows>0)?nbInsertedRows:"???")+") into \""+getFullDBName(table)+"\" (ADQL name: \""+table.getFullName()+"\")\t"+connection.getID()); + public void rowsInserted(final DBConnection<?> connection, TAPTable table, int nbInsertedRows){ + dbActivity("INSERT ROWS (" + ((nbInsertedRows > 0) ? nbInsertedRows : "???") + ") into \"" + getFullDBName(table) + "\" (ADQL name: \"" + table.getFullName() + "\")\t" + connection.getID()); } @Override - public void sqlQueryExecuting(final DBConnection<?> connection, String sql) { - dbActivity("EXECUTING SQL QUERY \t"+connection.getID()+"\n"+((sql == null)?"???":sql.replaceAll("\n", " ").replaceAll("\t", " ").replaceAll("\r", ""))); + public void sqlQueryExecuting(final DBConnection<?> connection, String sql){ + dbActivity("EXECUTING SQL QUERY \t" + connection.getID() + "\n" + ((sql == null) ? "???" : sql.replaceAll("\n", " ").replaceAll("\t", " ").replaceAll("\r", ""))); } @Override - public void sqlQueryError(final DBConnection<?> connection, String sql, Throwable t) { - dbActivity("EXECUTION ERROR\t"+connection.getID(), t); + public void sqlQueryError(final DBConnection<?> connection, String sql, Throwable t){ + dbActivity("EXECUTION ERROR\t" + connection.getID(), t); } @Override - public void sqlQueryExecuted(final DBConnection<?> connection, String sql) { - dbActivity("SUCCESSFULL END OF EXECUTION\t"+connection.getID()); + public void sqlQueryExecuted(final DBConnection<?> connection, String sql){ + dbActivity("SUCCESSFULL END OF EXECUTION\t" + connection.getID()); } } diff --git a/src/tap/metadata/TAPColumn.java b/src/tap/metadata/TAPColumn.java index 6f8f42a816dee98ae2c91cde49b3329a701097a0..94b69da94ddb6547dcac454a1043b132874e5b50 100644 --- a/src/tap/metadata/TAPColumn.java +++ b/src/tap/metadata/TAPColumn.java @@ -59,12 +59,11 @@ public class TAPColumn implements DBColumn { protected final ArrayList<TAPForeignKey> lstSources; - public TAPColumn(String columnName){ if (columnName == null || columnName.trim().length() == 0) throw new NullPointerException("Missing column name !"); int indPrefix = columnName.lastIndexOf('.'); - adqlName = (indPrefix >= 0)?columnName.substring(indPrefix+1).trim():columnName.trim(); + adqlName = (indPrefix >= 0) ? columnName.substring(indPrefix + 1).trim() : columnName.trim(); dbName = adqlName; lstTargets = new ArrayList<TAPForeignKey>(1); lstSources = new ArrayList<TAPForeignKey>(1); @@ -90,106 +89,106 @@ public class TAPColumn implements DBColumn { /** * @return The name. */ - public final String getName() { + public final String getName(){ return getADQLName(); } @Override - public final String getADQLName() { + public final String getADQLName(){ return adqlName; } @Override - public final String getDBName() { + public final String getDBName(){ return dbName; } public final void setDBName(String name){ - name = (name != null)?name.trim():name; - dbName = (name == null || name.length() == 0)?adqlName:name; + name = (name != null) ? name.trim() : name; + dbName = (name == null || name.length() == 0) ? adqlName : name; } /** * @return The table. */ - public final DBTable getTable() { + public final DBTable getTable(){ return table; } /** * @param table The table to set. */ - public final void setTable(DBTable table) { + public final void setTable(DBTable table){ this.table = table; } /** * @return The description. */ - public final String getDescription() { + public final String getDescription(){ return description; } /** * @param description The description to set. */ - public final void setDescription(String description) { + public final void setDescription(String description){ this.description = description; } /** * @return The unit. */ - public final String getUnit() { + public final String getUnit(){ return unit; } /** * @param unit The unit to set. */ - public final void setUnit(String unit) { + public final void setUnit(String unit){ this.unit = unit; } /** * @return The ucd. */ - public final String getUcd() { + public final String getUcd(){ return ucd; } /** * @param ucd The ucd to set. */ - public final void setUcd(String ucd) { + public final void setUcd(String ucd){ this.ucd = ucd; } /** * @return The utype. */ - public final String getUtype() { + public final String getUtype(){ return utype; } /** * @param utype The utype to set. */ - public final void setUtype(String utype) { + public final void setUtype(String utype){ this.utype = utype; } /** * @return The datatype. */ - public final String getDatatype() { + public final String getDatatype(){ return datatype; } /** * @return Array size (>0 or 2 special values: {@link TAPTypes#NO_SIZE} and {@link TAPTypes#STAR_SIZE}). */ - public final int getArraySize() { + public final int getArraySize(){ return size; } @@ -208,9 +207,9 @@ public class TAPColumn implements DBColumn { * @see TAPTypes#getVotType(String, int) * @see #setDefaultType() */ - public final void setDatatype(String datatype, int size) { + public final void setDatatype(String datatype, int size){ this.datatype = TAPTypes.getDBType(datatype); - this.size = (size <= 0 && size != TAPTypes.STAR_SIZE)?TAPTypes.NO_SIZE:size; + this.size = (size <= 0 && size != TAPTypes.STAR_SIZE) ? TAPTypes.NO_SIZE : size; if (this.datatype == null) setDefaultType(); @@ -258,47 +257,47 @@ public class TAPColumn implements DBColumn { /** * @return The principal. */ - public final boolean isPrincipal() { + public final boolean isPrincipal(){ return principal; } /** * @param principal The principal to set. */ - public final void setPrincipal(boolean principal) { + public final void setPrincipal(boolean principal){ this.principal = principal; } /** * @return The indexed. */ - public final boolean isIndexed() { + public final boolean isIndexed(){ return indexed; } /** * @param indexed The indexed to set. */ - public final void setIndexed(boolean indexed) { + public final void setIndexed(boolean indexed){ this.indexed = indexed; } /** * @return The std. */ - public final boolean isStd() { + public final boolean isStd(){ return std; } /** * @param std The std to set. */ - public final void setStd(boolean std) { + public final void setStd(boolean std){ this.std = std; } public Object getOtherData(){ - return otherData ; + return otherData; } public void setOtherData(Object data){ @@ -348,8 +347,8 @@ public class TAPColumn implements DBColumn { } public DBColumn copy(final String dbName, final String adqlName, final DBTable dbTable){ - TAPColumn copy = new TAPColumn((adqlName==null)?this.adqlName:adqlName, description, unit, ucd, utype); - copy.setDBName((dbName==null)?this.dbName:dbName); + TAPColumn copy = new TAPColumn((adqlName == null) ? this.adqlName : adqlName, description, unit, ucd, utype); + copy.setDBName((dbName == null) ? this.dbName : dbName); copy.setTable(dbTable); copy.setDatatype(datatype, size); @@ -375,7 +374,7 @@ public class TAPColumn implements DBColumn { @Override public boolean equals(Object obj){ - if (! (obj instanceof TAPColumn)) + if (!(obj instanceof TAPColumn)) return false; TAPColumn col = (TAPColumn)obj; @@ -384,7 +383,7 @@ public class TAPColumn implements DBColumn { @Override public String toString(){ - return ((table != null)?(table.getADQLName()+"."):"")+adqlName; + return ((table != null) ? (table.getADQLName() + ".") : "") + adqlName; } } diff --git a/src/tap/metadata/TAPForeignKey.java b/src/tap/metadata/TAPForeignKey.java index 1552c4a72f8e8c41e3b69f16361f6cfd042c98b2..64be07325140ab74caeaef4e67541bcda9d7f047 100644 --- a/src/tap/metadata/TAPForeignKey.java +++ b/src/tap/metadata/TAPForeignKey.java @@ -35,19 +35,18 @@ public class TAPForeignKey implements Iterable<Map.Entry<String,String>> { private String utype = null; - protected final Map<String, String> columnsAssoc; + protected final Map<String,String> columnsAssoc; protected Object otherData = null; - - public TAPForeignKey(String keyId, TAPTable fromTable, TAPTable targetTable, Map<String,String> columns) { + public TAPForeignKey(String keyId, TAPTable fromTable, TAPTable targetTable, Map<String,String> columns){ this.keyId = keyId; this.fromTable = fromTable; this.targetTable = targetTable; - columnsAssoc = new HashMap<String, String>(columns); + columnsAssoc = new HashMap<String,String>(columns); } - public TAPForeignKey(String keyId, TAPTable fromTable, TAPTable targetTable, Map<String, String> columns, String description, String utype) { + public TAPForeignKey(String keyId, TAPTable fromTable, TAPTable targetTable, Map<String,String> columns, String description, String utype){ this(keyId, fromTable, targetTable, columns); this.description = description; this.utype = utype; @@ -56,40 +55,40 @@ public class TAPForeignKey implements Iterable<Map.Entry<String,String>> { /** * @return The keyId. */ - public final String getKeyId() { + public final String getKeyId(){ return keyId; } /** * @return The description. */ - public final String getDescription() { + public final String getDescription(){ return description; } /** * @param description The description to set. */ - public final void setDescription(String description) { + public final void setDescription(String description){ this.description = description; } /** * @return The utype. */ - public final String getUtype() { + public final String getUtype(){ return utype; } /** * @param utype The utype to set. */ - public final void setUtype(String utype) { + public final void setUtype(String utype){ this.utype = utype; } public Object getOtherData(){ - return otherData ; + return otherData; } public void setOtherData(Object data){ @@ -99,14 +98,14 @@ public class TAPForeignKey implements Iterable<Map.Entry<String,String>> { /** * @return The fromTable. */ - public final TAPTable getFromTable() { + public final TAPTable getFromTable(){ return fromTable; } /** * @return The targetTable. */ - public final TAPTable getTargetTable() { + public final TAPTable getTargetTable(){ return targetTable; } @@ -123,7 +122,7 @@ public class TAPForeignKey implements Iterable<Map.Entry<String,String>> { } public final String getSource(String targetColumnName){ - for(Map.Entry<String, String> relation : this) + for(Map.Entry<String,String> relation : this) if (relation.getValue().equals(targetColumnName)) return relation.getKey(); return null; @@ -147,7 +146,7 @@ public class TAPForeignKey implements Iterable<Map.Entry<String,String>> { } @Override - public Iterator<Map.Entry<String, String>> iterator() { + public Iterator<Map.Entry<String,String>> iterator(){ return columnsAssoc.entrySet().iterator(); } diff --git a/src/tap/metadata/TAPMetadata.java b/src/tap/metadata/TAPMetadata.java index 023dc8ef8e96f82fdd2e4c8d10c28911a7507855..9dda1b99bbc6bae1d679ca65438c43795dcd49a3 100644 --- a/src/tap/metadata/TAPMetadata.java +++ b/src/tap/metadata/TAPMetadata.java @@ -43,11 +43,11 @@ public class TAPMetadata implements Iterable<TAPSchema>, VOSIResource, TAPResour public static final String RESOURCE_NAME = "tables"; - protected final Map<String, TAPSchema> schemas; + protected final Map<String,TAPSchema> schemas; protected String accessURL = getName(); public TAPMetadata(){ - schemas = new HashMap<String, TAPSchema>(); + schemas = new HashMap<String,TAPSchema>(); } public final void addSchema(TAPSchema s){ @@ -107,7 +107,7 @@ public class TAPMetadata implements Iterable<TAPSchema>, VOSIResource, TAPResour } @Override - public final Iterator<TAPSchema> iterator() { + public final Iterator<TAPSchema> iterator(){ return schemas.values().iterator(); } @@ -155,14 +155,14 @@ public class TAPMetadata implements Iterable<TAPSchema>, VOSIResource, TAPResour return nbTables; } - public static class TableIterator implements Iterator<TAPTable>{ + public static class TableIterator implements Iterator<TAPTable> { private Iterator<TAPSchema> it; private Iterator<TAPTable> itTables; public TableIterator(TAPMetadata tapSchema){ it = tapSchema.iterator(); - if(it.hasNext()) + if (it.hasNext()) itTables = it.next().iterator(); prepareNext(); @@ -179,12 +179,12 @@ public class TAPMetadata implements Iterable<TAPSchema>, VOSIResource, TAPResour } @Override - public boolean hasNext() { + public boolean hasNext(){ return itTables != null; } @Override - public TAPTable next() { + public TAPTable next(){ if (itTables == null) throw new NoSuchElementException("No more table in TAP_SCHEMA !"); else{ @@ -197,7 +197,7 @@ public class TAPMetadata implements Iterable<TAPSchema>, VOSIResource, TAPResour } @Override - public void remove() { + public void remove(){ if (itTables != null) itTables.remove(); else @@ -206,28 +206,42 @@ public class TAPMetadata implements Iterable<TAPSchema>, VOSIResource, TAPResour } @Override - public String getName() { return RESOURCE_NAME; } + public String getName(){ + return RESOURCE_NAME; + } @Override - public void setTAPBaseURL(String baseURL) { accessURL = ((baseURL==null)?"":(baseURL+"/"))+getName(); } + public void setTAPBaseURL(String baseURL){ + accessURL = ((baseURL == null) ? "" : (baseURL + "/")) + getName(); + } @Override - public String getAccessURL() { return accessURL; } + public String getAccessURL(){ + return accessURL; + } @Override - public String getCapability() { return Capabilities.getDefaultCapability(this); } + public String getCapability(){ + return Capabilities.getDefaultCapability(this); + } @Override - public String getStandardID() { return "ivo://ivoa.net/std/VOSI#tables"; } + public String getStandardID(){ + return "ivo://ivoa.net/std/VOSI#tables"; + } @Override - public void init(ServletConfig config) throws ServletException { ; } + public void init(ServletConfig config) throws ServletException{ + ; + } @Override - public void destroy() { ; } + public void destroy(){ + ; + } @Override - public boolean executeResource(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + public boolean executeResource(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ response.setContentType("application/xml"); PrintWriter writer = response.getWriter(); @@ -248,7 +262,7 @@ public class TAPMetadata implements Iterable<TAPSchema>, VOSIResource, TAPResour return false; } - private void writeSchema(TAPSchema s, PrintWriter writer) throws IOException { + private void writeSchema(TAPSchema s, PrintWriter writer) throws IOException{ final String prefix = "\t\t"; writer.println("\t<schema>"); @@ -262,10 +276,12 @@ public class TAPMetadata implements Iterable<TAPSchema>, VOSIResource, TAPResour writer.println("\t</schema>"); } - private void writeTable(TAPTable t, PrintWriter writer) throws IOException { + private void writeTable(TAPTable t, PrintWriter writer) throws IOException{ final String prefix = "\t\t\t"; - writer.print("\t\t<table type=\""); writer.print(t.getType().equalsIgnoreCase("table")?"base_table":t.getType()); writer.println("\">"); + writer.print("\t\t<table type=\""); + writer.print(t.getType().equalsIgnoreCase("table") ? "base_table" : t.getType()); + writer.println("\">"); writeAtt(prefix, "name", t.getFullName(), writer); writeAtt(prefix, "description", t.getDescription(), writer); @@ -282,10 +298,12 @@ public class TAPMetadata implements Iterable<TAPSchema>, VOSIResource, TAPResour writer.println("\t\t</table>"); } - private void writeColumn(TAPColumn c, PrintWriter writer) throws IOException { + private void writeColumn(TAPColumn c, PrintWriter writer) throws IOException{ final String prefix = "\t\t\t\t"; - writer.print("\t\t\t<column std=\""); writer.print(c.isStd()); writer.println("\">"); + writer.print("\t\t\t<column std=\""); + writer.print(c.isStd()); + writer.println("\">"); writeAtt(prefix, "name", c.getName(), writer); writeAtt(prefix, "description", c.getDescription(), writer); @@ -314,7 +332,7 @@ public class TAPMetadata implements Iterable<TAPSchema>, VOSIResource, TAPResour writer.println("\t\t\t</column>"); } - private void writeForeignKey(TAPForeignKey fk, PrintWriter writer) throws IOException { + private void writeForeignKey(TAPForeignKey fk, PrintWriter writer) throws IOException{ final String prefix = "\t\t\t\t"; writer.println("\t\t\t<foreignKey>"); @@ -323,18 +341,20 @@ public class TAPMetadata implements Iterable<TAPSchema>, VOSIResource, TAPResour writeAtt(prefix, "description", fk.getDescription(), writer); writeAtt(prefix, "utype", fk.getUtype(), writer); - final String prefix2 = prefix+"\t"; - for(Map.Entry<String, String> entry : fk){ - writer.print(prefix); writer.println("<fkColumn>"); + final String prefix2 = prefix + "\t"; + for(Map.Entry<String,String> entry : fk){ + writer.print(prefix); + writer.println("<fkColumn>"); writeAtt(prefix2, "fromColumn", entry.getKey(), writer); writeAtt(prefix2, "targetColumn", entry.getValue(), writer); - writer.print(prefix); writer.println("</fkColumn>"); + writer.print(prefix); + writer.println("</fkColumn>"); } writer.println("\t\t\t</foreignKey>"); } - private void writeAtt(String prefix, String attributeName, String attributeValue, PrintWriter writer) throws IOException { + private void writeAtt(String prefix, String attributeName, String attributeValue, PrintWriter writer) throws IOException{ if (attributeValue != null){ StringBuffer xml = new StringBuffer(prefix); xml.append('<').append(attributeName).append('>').append(attributeValue).append("</").append(attributeName).append('>'); diff --git a/src/tap/metadata/TAPSchema.java b/src/tap/metadata/TAPSchema.java index 142ba6b38dd18f00316296156f0e3a638e5d93f8..faced37e9c861593c1888c473f06c631743dc2c3 100644 --- a/src/tap/metadata/TAPSchema.java +++ b/src/tap/metadata/TAPSchema.java @@ -35,12 +35,12 @@ public class TAPSchema implements Iterable<TAPTable> { protected Object otherData = null; - protected final Map<String, TAPTable> tables; + protected final Map<String,TAPTable> tables; public TAPSchema(String schemaName){ adqlName = schemaName; dbName = adqlName; - tables = new HashMap<String, TAPTable>(); + tables = new HashMap<String,TAPTable>(); } public TAPSchema(String schemaName, String description){ @@ -56,7 +56,7 @@ public class TAPSchema implements Iterable<TAPTable> { /** * @return The name. */ - public final String getName() { + public final String getName(){ return getADQLName(); } @@ -64,40 +64,40 @@ public class TAPSchema implements Iterable<TAPTable> { return adqlName; } - public final String getDBName() { + public final String getDBName(){ return dbName; } public final void setDBName(String name){ - name = (name != null)?name.trim():name; - dbName = (name == null || name.length() == 0)?adqlName:name; + name = (name != null) ? name.trim() : name; + dbName = (name == null || name.length() == 0) ? adqlName : name; } /** * @return The description. */ - public final String getDescription() { + public final String getDescription(){ return description; } /** * @param description The description to set. */ - public final void setDescription(String description) { + public final void setDescription(String description){ this.description = description; } /** * @return The utype. */ - public final String getUtype() { + public final String getUtype(){ return utype; } /** * @param utype The utype to set. */ - public final void setUtype(String utype) { + public final void setUtype(String utype){ this.utype = utype; } @@ -169,9 +169,9 @@ public class TAPSchema implements Iterable<TAPTable> { } public final void removeAllTables(){ - Iterator<Map.Entry<String, TAPTable>> it = tables.entrySet().iterator(); + Iterator<Map.Entry<String,TAPTable>> it = tables.entrySet().iterator(); while(it.hasNext()){ - Map.Entry<String, TAPTable> entry = it.next(); + Map.Entry<String,TAPTable> entry = it.next(); it.remove(); entry.getValue().setSchema(null); entry.getValue().removeAllForeignKeys(); @@ -179,7 +179,7 @@ public class TAPSchema implements Iterable<TAPTable> { } @Override - public Iterator<TAPTable> iterator() { + public Iterator<TAPTable> iterator(){ return tables.values().iterator(); } diff --git a/src/tap/metadata/TAPTable.java b/src/tap/metadata/TAPTable.java index ff09e24018b34e528b970e76e18cce50997aef01..92fd803c37dc8cfb8630355c59110830e43c5d56 100644 --- a/src/tap/metadata/TAPTable.java +++ b/src/tap/metadata/TAPTable.java @@ -43,20 +43,19 @@ public class TAPTable implements DBTable { private String utype = null; - protected final Map<String, TAPColumn> columns; + protected final Map<String,TAPColumn> columns; protected final ArrayList<TAPForeignKey> foreignKeys; protected Object otherData = null; - public TAPTable(String tableName){ if (tableName == null || tableName.trim().length() == 0) throw new NullPointerException("Missing table name !"); int indPrefix = tableName.lastIndexOf('.'); - adqlName = (indPrefix >= 0)?tableName.substring(indPrefix+1).trim():tableName.trim(); + adqlName = (indPrefix >= 0) ? tableName.substring(indPrefix + 1).trim() : tableName.trim(); dbName = adqlName; - columns = new LinkedHashMap<String, TAPColumn>(); + columns = new LinkedHashMap<String,TAPColumn>(); foreignKeys = new ArrayList<TAPForeignKey>(); } @@ -73,7 +72,7 @@ public class TAPTable implements DBTable { public final String getFullName(){ if (schema != null) - return schema.getName()+"."+adqlName; + return schema.getName() + "." + adqlName; else return adqlName; } @@ -81,103 +80,103 @@ public class TAPTable implements DBTable { /** * @return The name. */ - public final String getName() { + public final String getName(){ return getADQLName(); } @Override - public final String getADQLName() { + public final String getADQLName(){ return adqlName; } @Override - public final String getDBName() { + public final String getDBName(){ return dbName; } public final void setDBName(String name){ - name = (name != null)?name.trim():name; - dbName = (name == null || name.length() == 0)?adqlName:name; + name = (name != null) ? name.trim() : name; + dbName = (name == null || name.length() == 0) ? adqlName : name; } @Override - public String getADQLCatalogName() { + public String getADQLCatalogName(){ return null; } @Override - public String getDBCatalogName() { + public String getDBCatalogName(){ return null; } @Override - public final String getADQLSchemaName() { + public final String getADQLSchemaName(){ return schema.getADQLName(); } @Override - public final String getDBSchemaName() { + public final String getDBSchemaName(){ return schema.getDBName(); } /** * @return The schema. */ - public final TAPSchema getSchema() { + public final TAPSchema getSchema(){ return schema; } /** * @param schema The schema to set. */ - protected final void setSchema(TAPSchema schema) { + protected final void setSchema(TAPSchema schema){ this.schema = schema; } /** * @return The type. */ - public final String getType() { + public final String getType(){ return type; } /** * @param type The type to set. */ - public final void setType(String type) { + public final void setType(String type){ this.type = type; } /** * @return The description. */ - public final String getDescription() { + public final String getDescription(){ return description; } /** * @param description The description to set. */ - public final void setDescription(String description) { + public final void setDescription(String description){ this.description = description; } /** * @return The utype. */ - public final String getUtype() { + public final String getUtype(){ return utype; } /** * @param utype The utype to set. */ - public final void setUtype(String utype) { + public final void setUtype(String utype){ this.utype = utype; } public Object getOtherData(){ - return otherData ; + return otherData; } public void setOtherData(Object data){ @@ -247,7 +246,7 @@ public class TAPTable implements DBTable { } @Override - public DBColumn getColumn(String colName, boolean byAdqlName) { + public DBColumn getColumn(String colName, boolean byAdqlName){ if (byAdqlName) return getColumn(colName); else{ @@ -269,7 +268,7 @@ public class TAPTable implements DBTable { return columns.get(columnName); } - public boolean hasColumn(String colName, boolean byAdqlName) { + public boolean hasColumn(String colName, boolean byAdqlName){ return (getColumn(colName, byAdqlName) != null); } @@ -308,41 +307,41 @@ public class TAPTable implements DBTable { } public final void removeAllColumns(){ - Iterator<Map.Entry<String, TAPColumn>> it = columns.entrySet().iterator(); + Iterator<Map.Entry<String,TAPColumn>> it = columns.entrySet().iterator(); while(it.hasNext()){ - Map.Entry<String, TAPColumn> entry = it.next(); + Map.Entry<String,TAPColumn> entry = it.next(); it.remove(); deleteColumnRelations(entry.getValue()); } } - public final void addForeignKey(TAPForeignKey key) throws Exception { + public final void addForeignKey(TAPForeignKey key) throws Exception{ if (key == null) return; String keyId = key.getKeyId(); - final String errorMsgPrefix = "Impossible to add the foreign key \""+keyId+"\" because "; + final String errorMsgPrefix = "Impossible to add the foreign key \"" + keyId + "\" because "; if (key.getFromTable() == null) - throw new Exception(errorMsgPrefix+"no source table is specified !"); + throw new Exception(errorMsgPrefix + "no source table is specified !"); if (!this.equals(key.getFromTable())) - throw new Exception(errorMsgPrefix+"the source table is not \""+getName()+"\""); + throw new Exception(errorMsgPrefix + "the source table is not \"" + getName() + "\""); if (key.getTargetTable() == null) - throw new Exception(errorMsgPrefix+"no target table is specified !"); + throw new Exception(errorMsgPrefix + "no target table is specified !"); if (key.isEmpty()) - throw new Exception(errorMsgPrefix+"it defines no relation !"); + throw new Exception(errorMsgPrefix + "it defines no relation !"); if (foreignKeys.add(key)){ try{ TAPTable targetTable = key.getTargetTable(); - for(Map.Entry<String, String> relation : key){ + for(Map.Entry<String,String> relation : key){ if (!hasColumn(relation.getKey())) - throw new Exception(errorMsgPrefix+"the source column \""+relation.getKey()+"\" doesn't exist in \""+getName()+"\" !"); + throw new Exception(errorMsgPrefix + "the source column \"" + relation.getKey() + "\" doesn't exist in \"" + getName() + "\" !"); else if (!targetTable.hasColumn(relation.getValue())) - throw new Exception(errorMsgPrefix+"the target column \""+relation.getValue()+"\" doesn't exist in \""+targetTable.getName()+"\" !"); + throw new Exception(errorMsgPrefix + "the target column \"" + relation.getValue() + "\" doesn't exist in \"" + targetTable.getName() + "\" !"); else{ getColumn(relation.getKey()).addTarget(key); targetTable.getColumn(relation.getValue()).addSource(key); @@ -355,13 +354,13 @@ public class TAPTable implements DBTable { } } - public TAPForeignKey addForeignKey(String keyId, TAPTable targetTable, Map<String, String> columns) throws Exception { + public TAPForeignKey addForeignKey(String keyId, TAPTable targetTable, Map<String,String> columns) throws Exception{ TAPForeignKey key = new TAPForeignKey(keyId, this, targetTable, columns); addForeignKey(key); return key; } - public TAPForeignKey addForeignKey(String keyId, TAPTable targetTable, Map<String, String> columns, String description, String utype) throws Exception { + public TAPForeignKey addForeignKey(String keyId, TAPTable targetTable, Map<String,String> columns, String description, String utype) throws Exception{ TAPForeignKey key = new TAPForeignKey(keyId, this, targetTable, columns, description, utype); addForeignKey(key); return key; @@ -392,34 +391,45 @@ public class TAPTable implements DBTable { } protected final void deleteRelations(TAPForeignKey key){ - for(Map.Entry<String, String> relation : key){ + for(Map.Entry<String,String> relation : key){ TAPColumn col = key.getFromTable().getColumn(relation.getKey()); - if (col != null) col.removeTarget(key); + if (col != null) + col.removeTarget(key); col = key.getTargetTable().getColumn(relation.getValue()); - if (col != null) col.removeSource(key); + if (col != null) + col.removeSource(key); } } @Override - public Iterator<DBColumn> iterator() { - return new Iterator<DBColumn>() { + public Iterator<DBColumn> iterator(){ + return new Iterator<DBColumn>(){ private final Iterator<TAPColumn> it = getColumns(); + @Override - public boolean hasNext() { return it.hasNext(); } + public boolean hasNext(){ + return it.hasNext(); + } + @Override - public DBColumn next() { return it.next(); } + public DBColumn next(){ + return it.next(); + } + @Override - public void remove() { it.remove(); } + public void remove(){ + it.remove(); + } }; } @Override public String toString(){ - return ((schema != null)?(schema.getName()+"."):"")+adqlName; + return ((schema != null) ? (schema.getName() + ".") : "") + adqlName; } - public static void main(String[] args) throws Exception { + public static void main(String[] args) throws Exception{ TAPSchema schema1 = new TAPSchema("monSchema1"); TAPSchema schema2 = new TAPSchema("monSchema2"); @@ -429,11 +439,11 @@ public class TAPTable implements DBTable { TAPTable t = schema2.addTable("Test"); t.addColumn("machin"); t.addColumn("truc"); - HashMap<String, String> mapCols = new HashMap<String, String>(); + HashMap<String,String> mapCols = new HashMap<String,String>(); mapCols.put("machin", "monMachin"); TAPForeignKey key = new TAPForeignKey("KeyID", t, tRef, mapCols); t.addForeignKey(key); - mapCols = new HashMap<String, String>(); + mapCols = new HashMap<String,String>(); mapCols.put("truc", "monMachin"); key = new TAPForeignKey("2ndKey", t, tRef, mapCols); t.addForeignKey(key); @@ -449,32 +459,32 @@ public class TAPTable implements DBTable { } public static void printSchema(TAPSchema schema){ - System.out.println("*** SCHEMA \""+schema.getName()+"\" ***"); + System.out.println("*** SCHEMA \"" + schema.getName() + "\" ***"); for(TAPTable t : schema) printTable(t); } public static void printTable(TAPTable t){ - System.out.println("TABLE: "+t+"\nNb Columns: "+t.getNbColumns()+"\nNb Relations: "+t.getNbForeignKeys()); + System.out.println("TABLE: " + t + "\nNb Columns: " + t.getNbColumns() + "\nNb Relations: " + t.getNbForeignKeys()); Iterator<TAPColumn> it = t.getColumns(); while(it.hasNext()){ TAPColumn col = it.next(); - System.out.print("\t- "+col+"( "); + System.out.print("\t- " + col + "( "); Iterator<TAPForeignKey> keys = col.getTargets(); while(keys.hasNext()) - for(Map.Entry<String, String> relation : keys.next()) - System.out.print(">"+relation.getKey()+"/"+relation.getValue()+" "); + for(Map.Entry<String,String> relation : keys.next()) + System.out.print(">" + relation.getKey() + "/" + relation.getValue() + " "); keys = col.getSources(); while(keys.hasNext()) - for(Map.Entry<String, String> relation : keys.next()) - System.out.print("<"+relation.getKey()+"/"+relation.getValue()+" "); + for(Map.Entry<String,String> relation : keys.next()) + System.out.print("<" + relation.getKey() + "/" + relation.getValue() + " "); System.out.println(")"); } } - public DBTable copy(final String dbName, final String adqlName) { - TAPTable copy = new TAPTable((adqlName==null)?this.adqlName:adqlName); - copy.setDBName((dbName==null)?this.dbName:dbName); + public DBTable copy(final String dbName, final String adqlName){ + TAPTable copy = new TAPTable((adqlName == null) ? this.adqlName : adqlName); + copy.setDBName((dbName == null) ? this.dbName : dbName); copy.setSchema(schema); Collection<TAPColumn> collColumns = columns.values(); for(TAPColumn col : collColumns) diff --git a/src/tap/metadata/TAPTypes.java b/src/tap/metadata/TAPTypes.java index ae446c618b7c8b2ddf134b47bb2f55045eb3a7ec..423b854ab6ca437107c7c4981312882ec5d52978 100644 --- a/src/tap/metadata/TAPTypes.java +++ b/src/tap/metadata/TAPTypes.java @@ -40,9 +40,9 @@ import java.util.Map.Entry; */ public final class TAPTypes { - private static final Map<String, VotType> dbTypes; - private static final Map<String, String> dbTypeAliases; - private static final Map<VotType, String> votTypes; + private static final Map<String,VotType> dbTypes; + private static final Map<String,String> dbTypeAliases; + private static final Map<VotType,String> votTypes; public static final String SMALLINT = "SMALLINT"; public static final String INTEGER = "INTEGER"; @@ -65,9 +65,9 @@ public final class TAPTypes { /** Means '*' (i.e. char(*)). */ public static final int STAR_SIZE = -12345; - static { - dbTypes = new HashMap<String, VotType>(14); - votTypes = new HashMap<VotType, String>(7); + static{ + dbTypes = new HashMap<String,VotType>(14); + votTypes = new HashMap<VotType,String>(7); VotType type = new VotType("short", 1, null); dbTypes.put(SMALLINT, type); @@ -121,7 +121,7 @@ public final class TAPTypes { dbTypes.put(REGION, type); votTypes.put(type, REGION); - dbTypeAliases = new HashMap<String, String>(8); + dbTypeAliases = new HashMap<String,String>(8); // PostgreSQL data types: dbTypeAliases.put("INT2", SMALLINT); dbTypeAliases.put("INT", INTEGER); @@ -306,49 +306,52 @@ public final class TAPTypes { return true; } - /** SELF TEST */ - public final static void main(final String[] args) throws Exception { + public final static void main(final String[] args) throws Exception{ System.out.println("***** DB TYPES *****"); Iterator<String> itDB = TAPTypes.getDBTypes(); while(itDB.hasNext()) - System.out.println("\t- "+itDB.next()); + System.out.println("\t- " + itDB.next()); System.out.println("\n***** DB TYPE ALIASES *****"); Iterator<Entry<String,String>> itAliases = TAPTypes.getDBTypeAliases(); while(itAliases.hasNext()){ - Entry<String, String> e = itAliases.next(); - System.out.println("\t- "+e.getKey()+" = "+e.getValue()); + Entry<String,String> e = itAliases.next(); + System.out.println("\t- " + e.getKey() + " = " + e.getValue()); } System.out.println("\n***** VOTABLE TYPES *****"); Iterator<VotType> itVot = TAPTypes.getVotTypes(); while(itVot.hasNext()) - System.out.println("\t- "+itVot.next()); - + System.out.println("\t- " + itVot.next()); byte[] buffer = new byte[1024]; int nbRead = 0; String type = null; System.out.print("\nDB Type ? "); - nbRead=System.in.read(buffer); type = new String(buffer, 0, nbRead); + nbRead = System.in.read(buffer); + type = new String(buffer, 0, nbRead); System.out.println(TAPTypes.getVotType(type)); int arraysize = 1; String xtype = null; VotType votType = null; System.out.print("\nVOTable datatype ? "); - nbRead=System.in.read(buffer); type = (new String(buffer, 0, nbRead)).trim(); + nbRead = System.in.read(buffer); + type = (new String(buffer, 0, nbRead)).trim(); System.out.print("VOTable arraysize ? "); - nbRead=System.in.read(buffer); + nbRead = System.in.read(buffer); try{ arraysize = Integer.parseInt((new String(buffer, 0, nbRead)).trim()); }catch(NumberFormatException nfe){ arraysize = STAR_SIZE; } System.out.print("VOTable xtype ? "); - nbRead=System.in.read(buffer); xtype = (new String(buffer, 0, nbRead)).trim(); if (xtype != null && xtype.length() == 0) xtype = null; + nbRead = System.in.read(buffer); + xtype = (new String(buffer, 0, nbRead)).trim(); + if (xtype != null && xtype.length() == 0) + xtype = null; votType = new VotType(type, arraysize, xtype); System.out.println(TAPTypes.getDBType(votType)); } diff --git a/src/tap/metadata/VotType.java b/src/tap/metadata/VotType.java index dfdff1bc10ca6d6ff9b5e69f104c640cf55e55e9..27daedea467e74a23c21191131225448154eac4f 100644 --- a/src/tap/metadata/VotType.java +++ b/src/tap/metadata/VotType.java @@ -35,7 +35,7 @@ import cds.savot.writer.SavotWriter; public final class VotType { public final String datatype; /** A negative or null value means "*" (that's to say: an undetermined arraysize). */ - public int arraysize; + public int arraysize; public final String xtype; /** @@ -52,7 +52,7 @@ public final class VotType { } @Override - public boolean equals(Object obj) { + public boolean equals(Object obj){ if (obj == null) return false; try{ @@ -63,12 +63,14 @@ public final class VotType { else return xtype.equalsIgnoreCase(vot.xtype); } - }catch(ClassCastException cce){ ; } + }catch(ClassCastException cce){ + ; + } return false; } @Override - public int hashCode() { + public int hashCode(){ return datatype.toLowerCase().hashCode(); } @@ -80,7 +82,7 @@ public final class VotType { if (arraysize == TAPTypes.STAR_SIZE) str.append(" arraysize=\"*\""); else if (arraysize != TAPTypes.NO_SIZE && arraysize > 0) - str.append(" arraysize=\"").append(SavotWriter.encodeAttribute(""+arraysize)).append('"'); + str.append(" arraysize=\"").append(SavotWriter.encodeAttribute("" + arraysize)).append('"'); if (xtype != null) str.append(" xtype=\"").append(SavotWriter.encodeAttribute(xtype)).append('"'); diff --git a/src/tap/parameters/FormatController.java b/src/tap/parameters/FormatController.java index d75f911dd8b1ae1ac4f8025bab9dd439e842b0b7..46f2d2fea72773f756ff2bee96075036eccb7060 100644 --- a/src/tap/parameters/FormatController.java +++ b/src/tap/parameters/FormatController.java @@ -28,7 +28,7 @@ import uws.UWSException; import uws.UWSExceptionFactory; import uws.job.parameters.InputParamController; -public class FormatController<R> implements InputParamController { +public class FormatController< R > implements InputParamController { protected final ServiceConnection<R> service; protected boolean allowModification = true; @@ -38,7 +38,7 @@ public class FormatController<R> implements InputParamController { } @Override - public final boolean allowModification() { + public final boolean allowModification(){ return allowModification; } @@ -47,12 +47,12 @@ public class FormatController<R> implements InputParamController { } @Override - public Object getDefault() { + public Object getDefault(){ return TAPJob.FORMAT_VOTABLE; } @Override - public Object check(Object format) throws UWSException { + public Object check(Object format) throws UWSException{ if (format == null) return null; @@ -62,21 +62,21 @@ public class FormatController<R> implements InputParamController { return getDefault(); if (service.getOutputFormat(strFormat) == null) - throw new UWSException(UWSException.BAD_REQUEST, "Unknown output format (="+strFormat+") ! This TAP service can format query results ONLY in the following formats:"+getAllowedFormats()+"."); + throw new UWSException(UWSException.BAD_REQUEST, "Unknown output format (=" + strFormat + ") ! This TAP service can format query results ONLY in the following formats:" + getAllowedFormats() + "."); else return strFormat; }else - throw UWSExceptionFactory.badFormat(null, TAPJob.PARAM_FORMAT, format.toString(), format.getClass().getName(), "A String equals to one of the following values: "+getAllowedFormats()+"."); + throw UWSExceptionFactory.badFormat(null, TAPJob.PARAM_FORMAT, format.toString(), format.getClass().getName(), "A String equals to one of the following values: " + getAllowedFormats() + "."); } public final String getAllowedFormats(){ Iterator<OutputFormat<R>> itFormats = service.getOutputFormats(); StringBuffer allowedFormats = new StringBuffer(); - int i=0; + int i = 0; OutputFormat<R> formatter; while(itFormats.hasNext()){ formatter = itFormats.next(); - allowedFormats.append((i==0)?"":", ").append(formatter.getMimeType()); + allowedFormats.append((i == 0) ? "" : ", ").append(formatter.getMimeType()); if (formatter.getShortMimeType() != null && formatter.getShortMimeType().length() > 0) allowedFormats.append(" (or ").append(formatter.getShortMimeType()).append(')'); i++; diff --git a/src/tap/parameters/MaxRecController.java b/src/tap/parameters/MaxRecController.java index 235b9af7be5683598a651c1153df01031d4934a3..54e7625387baa9a10f45802eafcf6b41235f231e 100644 --- a/src/tap/parameters/MaxRecController.java +++ b/src/tap/parameters/MaxRecController.java @@ -35,14 +35,13 @@ public class MaxRecController implements InputParamController { /** Indicates whether the output limit of jobs can be modified. */ protected boolean allowModification = true; - public MaxRecController(final ServiceConnection<?> service){ this.service = service; allowModification(allowModification); } @Override - public final Object getDefault() { + public final Object getDefault(){ if (service.getOutputLimit() != null && service.getOutputLimit().length >= 2 && service.getOutputLimitType() != null && service.getOutputLimitType().length == service.getOutputLimit().length){ if (service.getOutputLimit()[0] > 0 && service.getOutputLimitType()[0] == LimitUnit.rows) return service.getOutputLimit()[0]; @@ -59,7 +58,7 @@ public class MaxRecController implements InputParamController { } @Override - public Object check(Object value) throws UWSException { + public Object check(Object value) throws UWSException{ if (value == null) return null; @@ -72,15 +71,15 @@ public class MaxRecController implements InputParamController { try{ maxRec = Integer.parseInt(strValue); }catch(NumberFormatException nfe){ - throw UWSExceptionFactory.badFormat(null, TAPJob.PARAM_MAX_REC, strValue, null, "An integer value between "+TAPJob.UNLIMITED_MAX_REC+" and "+maxOutputLimit+" (Default value: "+defaultOutputLimit+")."); + throw UWSExceptionFactory.badFormat(null, TAPJob.PARAM_MAX_REC, strValue, null, "An integer value between " + TAPJob.UNLIMITED_MAX_REC + " and " + maxOutputLimit + " (Default value: " + defaultOutputLimit + ")."); } }else - throw UWSExceptionFactory.badFormat(null, TAPJob.PARAM_MAX_REC, null, value.getClass().getName(), "An integer value between "+TAPJob.UNLIMITED_MAX_REC+" and "+maxOutputLimit+" (Default value: "+defaultOutputLimit+")."); + throw UWSExceptionFactory.badFormat(null, TAPJob.PARAM_MAX_REC, null, value.getClass().getName(), "An integer value between " + TAPJob.UNLIMITED_MAX_REC + " and " + maxOutputLimit + " (Default value: " + defaultOutputLimit + ")."); if (maxRec < TAPJob.UNLIMITED_MAX_REC) maxRec = TAPJob.UNLIMITED_MAX_REC; else if (maxOutputLimit > TAPJob.UNLIMITED_MAX_REC && maxRec > maxOutputLimit) - throw new UWSException(UWSException.BAD_REQUEST, "The TAP limits the maxRec parameter (=output limit) to maximum "+maxOutputLimit+" rows !"); + throw new UWSException(UWSException.BAD_REQUEST, "The TAP limits the maxRec parameter (=output limit) to maximum " + maxOutputLimit + " rows !"); return maxRec; } @@ -93,7 +92,7 @@ public class MaxRecController implements InputParamController { * * @return <i>true</i> if the output limit can be modified, <i>false</i> otherwise. */ - public final boolean allowModification() { + public final boolean allowModification(){ return allowModification; } @@ -102,7 +101,7 @@ public class MaxRecController implements InputParamController { * * @param allowModification <i>true</i> if the output limit can be modified, <i>false</i> otherwise. */ - public final void allowModification(boolean allowModification) { + public final void allowModification(boolean allowModification){ this.allowModification = allowModification; } diff --git a/src/tap/parameters/TAPDestructionTimeController.java b/src/tap/parameters/TAPDestructionTimeController.java index 18f843b615362cf719004900fc4d1e849a739300..33444bdcf35ecae0b0515686f98552e69478f774 100644 --- a/src/tap/parameters/TAPDestructionTimeController.java +++ b/src/tap/parameters/TAPDestructionTimeController.java @@ -38,12 +38,12 @@ public class TAPDestructionTimeController implements InputParamController { protected final ServiceConnection<?> service; protected boolean allowModification = true; - public TAPDestructionTimeController(final ServiceConnection<?> service) { + public TAPDestructionTimeController(final ServiceConnection<?> service){ this.service = service; } @Override - public final boolean allowModification() { + public final boolean allowModification(){ return allowModification; } @@ -60,7 +60,7 @@ public class TAPDestructionTimeController implements InputParamController { } @Override - public final Object getDefault() { + public final Object getDefault(){ int defaultPeriod = getDefaultRetentionPeriod(); if (defaultPeriod > 0){ Calendar date = Calendar.getInstance(); @@ -97,7 +97,7 @@ public class TAPDestructionTimeController implements InputParamController { } @Override - public Object check(Object value) throws UWSException { + public Object check(Object value) throws UWSException{ if (value == null) return null; @@ -116,11 +116,9 @@ public class TAPDestructionTimeController implements InputParamController { Date maxDate = getMaxDestructionTime(); if (maxDate != null && date.after(maxDate)) - throw new UWSException(UWSException.BAD_REQUEST, "The TAP service limits the DESTRUCTION INTERVAL (since now) to "+getMaxRetentionPeriod()+" s !"); + throw new UWSException(UWSException.BAD_REQUEST, "The TAP service limits the DESTRUCTION INTERVAL (since now) to " + getMaxRetentionPeriod() + " s !"); return date; } - - } diff --git a/src/tap/parameters/TAPExecutionDurationController.java b/src/tap/parameters/TAPExecutionDurationController.java index fbccbec02e80cd44089e6d1fb010ca1a6a884e48..68f5797e6bb8860f3917d749ce4083da49fb0388 100644 --- a/src/tap/parameters/TAPExecutionDurationController.java +++ b/src/tap/parameters/TAPExecutionDurationController.java @@ -32,12 +32,12 @@ public class TAPExecutionDurationController implements InputParamController { protected final ServiceConnection<?> service; protected boolean allowModification = true; - public TAPExecutionDurationController(final ServiceConnection<?> service) { + public TAPExecutionDurationController(final ServiceConnection<?> service){ this.service = service; } @Override - public final boolean allowModification() { + public final boolean allowModification(){ return allowModification; } @@ -46,7 +46,7 @@ public class TAPExecutionDurationController implements InputParamController { } @Override - public final Object getDefault() { + public final Object getDefault(){ if (service.getExecutionDuration() != null && service.getExecutionDuration().length >= 2){ if (service.getExecutionDuration()[0] > 0) return service.getExecutionDuration()[0]; @@ -63,7 +63,7 @@ public class TAPExecutionDurationController implements InputParamController { } @Override - public Object check(Object value) throws UWSException { + public Object check(Object value) throws UWSException{ if (value == null) return null; @@ -76,19 +76,17 @@ public class TAPExecutionDurationController implements InputParamController { try{ duration = Long.parseLong((String)value); }catch(NumberFormatException nfe){ - throw UWSExceptionFactory.badFormat(null, TAPJob.PARAM_EXECUTION_DURATION, value.toString(), null, "A long value between "+TAPJob.UNLIMITED_DURATION+" and "+maxDuration+" (Default value: "+defaultDuration+")."); + throw UWSExceptionFactory.badFormat(null, TAPJob.PARAM_EXECUTION_DURATION, value.toString(), null, "A long value between " + TAPJob.UNLIMITED_DURATION + " and " + maxDuration + " (Default value: " + defaultDuration + ")."); } }else - throw UWSExceptionFactory.badFormat(null, TAPJob.PARAM_EXECUTION_DURATION, null, value.getClass().getName(), "A long value between "+TAPJob.UNLIMITED_DURATION+" and "+maxDuration+" (Default value: "+defaultDuration+")."); + throw UWSExceptionFactory.badFormat(null, TAPJob.PARAM_EXECUTION_DURATION, null, value.getClass().getName(), "A long value between " + TAPJob.UNLIMITED_DURATION + " and " + maxDuration + " (Default value: " + defaultDuration + ")."); if (duration < TAPJob.UNLIMITED_DURATION) duration = TAPJob.UNLIMITED_DURATION; else if (maxDuration > TAPJob.UNLIMITED_DURATION && duration > maxDuration) - throw new UWSException(UWSException.BAD_REQUEST, "The TAP service limits the execution duration to maximum "+maxDuration+" seconds !"); + throw new UWSException(UWSException.BAD_REQUEST, "The TAP service limits the execution duration to maximum " + maxDuration + " seconds !"); return duration; } - - } diff --git a/src/tap/parameters/TAPParameters.java b/src/tap/parameters/TAPParameters.java index 85f722b47d3035da2779039d0cf3ded774a379fc..f45c833ff840e87d28ac3c7a5e9a9a93f16a473b 100644 --- a/src/tap/parameters/TAPParameters.java +++ b/src/tap/parameters/TAPParameters.java @@ -56,7 +56,7 @@ public class TAPParameters extends UWSParameters { /** * All the TAP parameters. */ - protected static final String[] TAP_PARAMETERS = new String[]{TAPJob.PARAM_REQUEST, TAPJob.PARAM_LANGUAGE, TAPJob.PARAM_VERSION, TAPJob.PARAM_FORMAT, TAPJob.PARAM_QUERY, TAPJob.PARAM_MAX_REC, TAPJob.PARAM_UPLOAD}; + protected static final String[] TAP_PARAMETERS = new String[]{TAPJob.PARAM_REQUEST,TAPJob.PARAM_LANGUAGE,TAPJob.PARAM_VERSION,TAPJob.PARAM_FORMAT,TAPJob.PARAM_QUERY,TAPJob.PARAM_MAX_REC,TAPJob.PARAM_UPLOAD}; /** Part of HTTP content type header. */ public static final String MULTIPART = "multipart/"; @@ -64,23 +64,22 @@ public class TAPParameters extends UWSParameters { /** All the tables to upload. If NULL, there is no tables to upload. */ protected TableLoader[] tablesToUpload = null; - - @SuppressWarnings({ "unchecked" }) - public TAPParameters(final ServiceConnection<?> service) { + @SuppressWarnings({"unchecked"}) + public TAPParameters(final ServiceConnection<?> service){ this(service, (Collection)null, null); } - public TAPParameters(final ServiceConnection<?> service, final Collection<String> expectedAdditionalParams, final Map<String, InputParamController> inputParamControllers) { + public TAPParameters(final ServiceConnection<?> service, final Collection<String> expectedAdditionalParams, final Map<String,InputParamController> inputParamControllers){ super(expectedAdditionalParams, inputParamControllers); initDefaultTAPControllers(service); } - public TAPParameters(final HttpServletRequest request, final ServiceConnection<?> service) throws UWSException, TAPException { + public TAPParameters(final HttpServletRequest request, final ServiceConnection<?> service) throws UWSException, TAPException{ this(request, service, null, null); } @SuppressWarnings("unchecked") - public TAPParameters(final HttpServletRequest request, final ServiceConnection<?> service, final Collection<String> expectedAdditionalParams, final Map<String, InputParamController> inputParamControllers) throws UWSException, TAPException { + public TAPParameters(final HttpServletRequest request, final ServiceConnection<?> service, final Collection<String> expectedAdditionalParams, final Map<String,InputParamController> inputParamControllers) throws UWSException, TAPException{ this(service, expectedAdditionalParams, inputParamControllers); MultipartRequest multipart = null; @@ -91,10 +90,10 @@ public class TAPParameters extends UWSParameters { File uploadDir = service.getFileManager().getUploadDirectory(); try{ - multipart = new MultipartRequest(request, (uploadDir != null)?uploadDir.getAbsolutePath():null, service.getMaxUploadSize(), new FileRenamePolicy() { + multipart = new MultipartRequest(request, (uploadDir != null) ? uploadDir.getAbsolutePath() : null, service.getMaxUploadSize(), new FileRenamePolicy(){ @Override - public File rename(File file) { - return new File(file.getParentFile(), (new Date()).toString()+"_"+file.getName()); + public File rename(File file){ + return new File(file.getParentFile(), (new Date()).toString() + "_" + file.getName()); } }); Enumeration<String> e = multipart.getParameterNames(); @@ -110,7 +109,7 @@ public class TAPParameters extends UWSParameters { confError = "The maximum upload size (see ServiceConnection.getMaxUploadSize() must be positive !"; else if (uploadDir == null) confError = "Missing upload directory (see TAPFileManager.getUploadDirectory()) !"; - throw new TAPException("Incorrect Upload capability configuration ! "+confError, iae); + throw new TAPException("Incorrect Upload capability configuration ! " + confError, iae); } }// Classic HTTP parameters (GET or POST): @@ -129,21 +128,21 @@ public class TAPParameters extends UWSParameters { tablesToUpload = buildLoaders(uploadParam, multipart); } - public TAPParameters(final ServiceConnection<?> service, final Map<String, Object> params) throws UWSException, TAPException { + public TAPParameters(final ServiceConnection<?> service, final Map<String,Object> params) throws UWSException, TAPException{ this(service, params, null, null); } - public TAPParameters(final ServiceConnection<?> service, final Map<String, Object> params, final Collection<String> expectedAdditionalParams, final Map<String, InputParamController> inputParamControllers) throws UWSException, TAPException { + public TAPParameters(final ServiceConnection<?> service, final Map<String,Object> params, final Collection<String> expectedAdditionalParams, final Map<String,InputParamController> inputParamControllers) throws UWSException, TAPException{ super(params, expectedAdditionalParams, inputParamControllers); initDefaultTAPControllers(service); } @Override - protected final HashMap<String, InputParamController> getDefaultControllers() { - return new HashMap<String, InputParamController>(10); + protected final HashMap<String,InputParamController> getDefaultControllers(){ + return new HashMap<String,InputParamController>(10); } - protected <R> void initDefaultTAPControllers(final ServiceConnection<R> service){ + protected < R > void initDefaultTAPControllers(final ServiceConnection<R> service){ if (!mapParamControllers.containsKey(TAPJob.PARAM_EXECUTION_DURATION)) mapParamControllers.put(TAPJob.PARAM_EXECUTION_DURATION, new TAPExecutionDurationController(service)); @@ -151,7 +150,7 @@ public class TAPParameters extends UWSParameters { mapParamControllers.put(TAPJob.PARAM_DESTRUCTION_TIME, new TAPDestructionTimeController(service)); if (!mapParamControllers.containsKey(TAPJob.PARAM_REQUEST)) - mapParamControllers.put(TAPJob.PARAM_REQUEST, new StringParamController(TAPJob.PARAM_REQUEST, null, new String[]{TAPJob.REQUEST_DO_QUERY, TAPJob.REQUEST_GET_CAPABILITIES}, true)); + mapParamControllers.put(TAPJob.PARAM_REQUEST, new StringParamController(TAPJob.PARAM_REQUEST, null, new String[]{TAPJob.REQUEST_DO_QUERY,TAPJob.REQUEST_GET_CAPABILITIES}, true)); if (!mapParamControllers.containsKey(TAPJob.PARAM_LANGUAGE)) mapParamControllers.put(TAPJob.PARAM_LANGUAGE, new StringParamController(TAPJob.PARAM_LANGUAGE, TAPJob.LANG_ADQL, null, true)); @@ -173,7 +172,7 @@ public class TAPParameters extends UWSParameters { } @Override - protected String normalizeParamName(String name) { + protected String normalizeParamName(String name){ if (name != null && !name.trim().isEmpty()){ for(String tapParam : TAP_PARAMETERS){ if (name.equalsIgnoreCase(tapParam)) @@ -184,7 +183,7 @@ public class TAPParameters extends UWSParameters { } @Override - public String[] update(UWSParameters newParams) throws UWSException { + public String[] update(UWSParameters newParams) throws UWSException{ if (newParams != null && !(newParams instanceof TAPParameters)) throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, "Can not update a TAPParameters instance with only a UWSException !"); @@ -242,14 +241,14 @@ public class TAPParameters extends UWSParameters { params.put(TAPJob.PARAM_MAX_REC, maxRec); } return maxRec; - }catch(NumberFormatException nfe){ ; } + }catch(NumberFormatException nfe){ + ; + } } } return null; } - - /** * Utility method that determines whether the request contains multipart * content. @@ -259,15 +258,15 @@ public class TAPParameters extends UWSParameters { * @return <code>true</code> if the request is multipart; * <code>false</code> otherwise. */ - public static final boolean isMultipartContent(HttpServletRequest request) { - if (!"post".equals(request.getMethod().toLowerCase())) { + public static final boolean isMultipartContent(HttpServletRequest request){ + if (!"post".equals(request.getMethod().toLowerCase())){ return false; } String contentType = request.getContentType(); - if (contentType == null) { + if (contentType == null){ return false; } - if (contentType.toLowerCase().startsWith(MULTIPART)) { + if (contentType.toLowerCase().startsWith(MULTIPART)){ return true; } return false; @@ -283,14 +282,14 @@ public class TAPParameters extends UWSParameters { * * @throws TAPException If the syntax of the "upload" field is incorrect. */ - private TableLoader[] buildLoaders(final String upload, final MultipartRequest multipart) throws TAPException { + private TableLoader[] buildLoaders(final String upload, final MultipartRequest multipart) throws TAPException{ if (upload == null || upload.trim().isEmpty()) return new TableLoader[0]; String[] pairs = upload.split(";"); TableLoader[] loaders = new TableLoader[pairs.length]; - for(int i=0; i<pairs.length; i++){ + for(int i = 0; i < pairs.length; i++){ String[] table = pairs[i].split(","); if (table.length != 2) throw new TAPException("Bad syntax ! An UPLOAD parameter must contain a list of pairs separated by a ';'. Each pair is composed of 2 parts, a table name and a URI separated by a ','."); @@ -300,17 +299,17 @@ public class TAPParameters extends UWSParameters { return loaders; } - public void check() throws TAPException { + public void check() throws TAPException{ // Check that required parameters are not NON-NULL: String requestParam = getRequest(); if (requestParam == null) - throw new TAPException("The parameter \""+TAPJob.PARAM_REQUEST+"\" must be provided and its value must be equal to \""+TAPJob.REQUEST_DO_QUERY+"\" or \""+TAPJob.REQUEST_GET_CAPABILITIES+"\" !"); + throw new TAPException("The parameter \"" + TAPJob.PARAM_REQUEST + "\" must be provided and its value must be equal to \"" + TAPJob.REQUEST_DO_QUERY + "\" or \"" + TAPJob.REQUEST_GET_CAPABILITIES + "\" !"); if (requestParam.equals(TAPJob.REQUEST_DO_QUERY)){ if (get(TAPJob.PARAM_LANGUAGE) == null) - throw new TAPException("The parameter \""+TAPJob.PARAM_LANGUAGE+"\" must be provided if "+TAPJob.PARAM_REQUEST+"="+TAPJob.REQUEST_DO_QUERY+" !"); + throw new TAPException("The parameter \"" + TAPJob.PARAM_LANGUAGE + "\" must be provided if " + TAPJob.PARAM_REQUEST + "=" + TAPJob.REQUEST_DO_QUERY + " !"); else if (get(TAPJob.PARAM_QUERY) == null) - throw new TAPException("The parameter \""+TAPJob.PARAM_QUERY+"\" must be provided if "+TAPJob.PARAM_REQUEST+"="+TAPJob.REQUEST_DO_QUERY+" !"); + throw new TAPException("The parameter \"" + TAPJob.PARAM_QUERY + "\" must be provided if " + TAPJob.PARAM_REQUEST + "=" + TAPJob.REQUEST_DO_QUERY + " !"); } // Check the version if needed: @@ -334,7 +333,7 @@ public class TAPParameters extends UWSParameters { }*/ } - public static final void deleteUploadedTables(final TableLoader[] loaders) { + public static final void deleteUploadedTables(final TableLoader[] loaders){ if (loaders != null){ for(TableLoader loader : loaders) loader.deleteFile(); diff --git a/src/tap/resource/ASync.java b/src/tap/resource/ASync.java index 5e64fa65bcd853813486e3bd8467452b403493f8..38ba10cc2cb45fda3c76f05c31245cefd1a7b7bf 100644 --- a/src/tap/resource/ASync.java +++ b/src/tap/resource/ASync.java @@ -41,7 +41,7 @@ public class ASync implements TAPResource { protected final UWSService uws; @SuppressWarnings("unchecked") - public ASync(ServiceConnection service) throws UWSException, TAPException { + public ASync(ServiceConnection service) throws UWSException, TAPException{ this.service = service; uws = service.getFactory().createUWS(); @@ -65,7 +65,7 @@ public class ASync implements TAPResource { else if (report.length < 4) errorMsg = "Incorrect restoration report format ! => Impossible to know the restoration status !"; else if (report[0] != report[1]) - errorMsg = "FAILED restoration of the asynchronous jobs: "+report[0]+" on "+report[1]+" restored !"; + errorMsg = "FAILED restoration of the asynchronous jobs: " + report[0] + " on " + report[1] + " restored !"; else backupManager.setEnabled(true); @@ -78,23 +78,31 @@ public class ASync implements TAPResource { } @Override - public String getName() { return RESOURCE_NAME; } + public String getName(){ + return RESOURCE_NAME; + } @Override - public void setTAPBaseURL(String baseURL) { ; } + public void setTAPBaseURL(String baseURL){ + ; + } public final UWSService getUWS(){ return uws; } @Override - public void init(ServletConfig config) throws ServletException { ; } + public void init(ServletConfig config) throws ServletException{ + ; + } @Override - public void destroy() { ; } + public void destroy(){ + ; + } @Override - public boolean executeResource(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, TAPException, UWSException { + public boolean executeResource(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, TAPException, UWSException{ return uws.executeRequest(request, response); } diff --git a/src/tap/resource/Availability.java b/src/tap/resource/Availability.java index c712d5365bc4abf6473de68ffa62531324d2e58d..73832f8c6fb939ba0770769cfd2406a45fd3dcd1 100644 --- a/src/tap/resource/Availability.java +++ b/src/tap/resource/Availability.java @@ -40,34 +40,46 @@ public class Availability implements TAPResource, VOSIResource { this.service = service; } - public ServiceConnection<?> getService() { + public ServiceConnection<?> getService(){ return service; } - public final void setTAPBaseURL(String baseURL) { - accessURL = ((baseURL==null)?"":(baseURL+"/"))+getName(); + public final void setTAPBaseURL(String baseURL){ + accessURL = ((baseURL == null) ? "" : (baseURL + "/")) + getName(); } @Override - public final String getName() { return RESOURCE_NAME; } + public final String getName(){ + return RESOURCE_NAME; + } @Override - public final String getStandardID() { return "ivo://ivoa.net/std/VOSI#availability"; } + public final String getStandardID(){ + return "ivo://ivoa.net/std/VOSI#availability"; + } @Override - public final String getAccessURL() { return accessURL; } + public final String getAccessURL(){ + return accessURL; + } @Override - public String getCapability() { return Capabilities.getDefaultCapability(this); } + public String getCapability(){ + return Capabilities.getDefaultCapability(this); + } @Override - public void init(ServletConfig config) throws ServletException { ; } + public void init(ServletConfig config) throws ServletException{ + ; + } @Override - public void destroy() { ; } + public void destroy(){ + ; + } @Override - public boolean executeResource(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + public boolean executeResource(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ if (!request.getMethod().equalsIgnoreCase("GET")) // ERREUR 405 selon VOSI (cf p.4) response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "The AVAILABILITY resource is only accessible in HTTP-GET !"); @@ -75,7 +87,7 @@ public class Availability implements TAPResource, VOSIResource { String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; xml += "<availability xmlns=\"http://www.ivoa.net/xml/VOSIAvailability/v1.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.ivoa.net/xml/VOSIAvailability/v1.0 http://www.ivoa.net/xml/VOSIAvailability/v1.0\">\n"; - xml += "\t<available>"+service.isAvailable()+"</available>\n\t<note>"+service.getAvailability()+"</note>\n"; + xml += "\t<available>" + service.isAvailable() + "</available>\n\t<note>" + service.getAvailability() + "</note>\n"; xml += "</availability>"; PrintWriter pw = response.getWriter(); diff --git a/src/tap/resource/Capabilities.java b/src/tap/resource/Capabilities.java index 86c9c795384149f7f4af164c9588966de9c73d10..be6ff926f639ac43b5859f3aa9f94ff026f345f3 100644 --- a/src/tap/resource/Capabilities.java +++ b/src/tap/resource/Capabilities.java @@ -41,37 +41,43 @@ public class Capabilities implements TAPResource, VOSIResource { /** */ - public final void setTAPBaseURL(String baseURL) { - accessURL = ((baseURL==null)?"":(baseURL+"/"))+getName(); + public final void setTAPBaseURL(String baseURL){ + accessURL = ((baseURL == null) ? "" : (baseURL + "/")) + getName(); } @Override - public final String getName() { return RESOURCE_NAME; } + public final String getName(){ + return RESOURCE_NAME; + } @Override - public final String getStandardID() { return "ivo://ivoa.net/std/VOSI#capabilities"; } + public final String getStandardID(){ + return "ivo://ivoa.net/std/VOSI#capabilities"; + } @Override - public final String getAccessURL() { return accessURL; } + public final String getAccessURL(){ + return accessURL; + } @Override - public String getCapability() { + public String getCapability(){ return getDefaultCapability(this); } @Override - public void init(ServletConfig config) throws ServletException { + public void init(ServletConfig config) throws ServletException{ } @Override - public void destroy() { + public void destroy(){ // TODO Auto-generated method stub } @Override - public boolean executeResource(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + public boolean executeResource(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ response.setContentType("application/xml"); StringBuffer xml = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); @@ -106,11 +112,7 @@ public class Capabilities implements TAPResource, VOSIResource { } public static final String getDefaultCapability(VOSIResource res){ - return "\t<capability standardID=\""+res.getStandardID()+"\">\n" - + "\t\t<interface xsi:type=\"vs:ParamHTTP\" role=\"std\">\n" - + "\t\t\t<accessURL use=\"full\"> "+((res.getAccessURL()==null)?"":res.getAccessURL())+" </accessURL>\n" - + "\t\t</interface>\n" - + "\t</capability>"; + return "\t<capability standardID=\"" + res.getStandardID() + "\">\n" + "\t\t<interface xsi:type=\"vs:ParamHTTP\" role=\"std\">\n" + "\t\t\t<accessURL use=\"full\"> " + ((res.getAccessURL() == null) ? "" : res.getAccessURL()) + " </accessURL>\n" + "\t\t</interface>\n" + "\t</capability>"; } } diff --git a/src/tap/resource/Sync.java b/src/tap/resource/Sync.java index 5cd323a8425013f814e3ce378cdc01e73e63f76e..71be76f48da2c1312fe70a6497fd646a06603d25 100644 --- a/src/tap/resource/Sync.java +++ b/src/tap/resource/Sync.java @@ -48,21 +48,27 @@ public class Sync implements TAPResource { } @Override - public String getName() { return RESOURCE_NAME; } + public String getName(){ + return RESOURCE_NAME; + } @Override - public void setTAPBaseURL(String baseURL) { - accessURL = ((baseURL != null)?(baseURL+"/"):"")+getName(); + public void setTAPBaseURL(String baseURL){ + accessURL = ((baseURL != null) ? (baseURL + "/") : "") + getName(); } @Override - public void init(ServletConfig config) throws ServletException { ; } + public void init(ServletConfig config) throws ServletException{ + ; + } @Override - public void destroy() { ; } + public void destroy(){ + ; + } @Override - public boolean executeResource(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, TAPException, UWSException { + public boolean executeResource(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, TAPException, UWSException{ TAPParameters params = (TAPParameters)service.getFactory().createUWSParameters(request); params.check(); diff --git a/src/tap/resource/TAP.java b/src/tap/resource/TAP.java index a3d326d7e6ecf42d847e1cc1439ddde6fc9365d8..4855f3b69d7bb1f8daa4ff15b26ca64ab7e66329 100644 --- a/src/tap/resource/TAP.java +++ b/src/tap/resource/TAP.java @@ -39,7 +39,6 @@ import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; - import tap.ServiceConnection; import tap.TAPException; import tap.ServiceConnection.LimitUnit; @@ -56,13 +55,13 @@ import uws.service.UWSService; import uws.service.UWSUrl; import uws.service.error.ServiceErrorWriter; -public class TAP<R> implements VOSIResource { +public class TAP< R > implements VOSIResource { private static final long serialVersionUID = 1L; protected final ServiceConnection<R> service; - protected final Map<String, TAPResource> resources; + protected final Map<String,TAPResource> resources; protected String tapBaseURL = null; @@ -70,9 +69,9 @@ public class TAP<R> implements VOSIResource { protected ServiceErrorWriter errorWriter; - public TAP(ServiceConnection<R> serviceConnection) throws UWSException, TAPException { + public TAP(ServiceConnection<R> serviceConnection) throws UWSException, TAPException{ service = serviceConnection; - resources = new HashMap<String, TAPResource>(); + resources = new HashMap<String,TAPResource>(); errorWriter = new DefaultTAPErrorWriter(service); @@ -91,13 +90,13 @@ public class TAP<R> implements VOSIResource { if (service.uploadEnabled()){ DBConnection<?> dbConn = null; - try { + try{ dbConn = service.getFactory().createDBConnection("TAP(ServiceConnection)"); dbConn.dropSchema("TAP_UPLOAD"); dbConn.createSchema("TAP_UPLOAD"); - } catch (TAPException e) { + }catch(TAPException e){ throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, e, "Error while creating the schema TAP_UPLOAD !"); - } finally { + }finally{ if (dbConn != null) dbConn.close(); } @@ -117,38 +116,38 @@ public class TAP<R> implements VOSIResource { } public void setTAPBaseURL(HttpServletRequest request){ - setTAPBaseURL(request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+request.getServletPath()); + setTAPBaseURL(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + request.getServletPath()); } public final Availability getAvailability(){ - return (Availability) resources.get(Availability.RESOURCE_NAME); + return (Availability)resources.get(Availability.RESOURCE_NAME); } public final Capabilities getCapabilities(){ - return (Capabilities) resources.get(Capabilities.RESOURCE_NAME); + return (Capabilities)resources.get(Capabilities.RESOURCE_NAME); } public final Sync getSync(){ - return (Sync) resources.get(Sync.RESOURCE_NAME); + return (Sync)resources.get(Sync.RESOURCE_NAME); } public final ASync getASync(){ - return (ASync) resources.get(ASync.RESOURCE_NAME); + return (ASync)resources.get(ASync.RESOURCE_NAME); } public final TAPMetadata getTAPMetadata(){ - return (TAPMetadata) resources.get(TAPMetadata.RESOURCE_NAME); + return (TAPMetadata)resources.get(TAPMetadata.RESOURCE_NAME); } public final Iterator<TAPResource> getTAPResources(){ return resources.values().iterator(); } - public final ServiceErrorWriter getErrorWriter() { + public final ServiceErrorWriter getErrorWriter(){ return errorWriter; } - public final void setErrorWriter(ServiceErrorWriter errorWriter) { + public final void setErrorWriter(ServiceErrorWriter errorWriter){ if (errorWriter != null){ this.errorWriter = errorWriter; getUWS().setErrorWriter(errorWriter); @@ -156,13 +155,17 @@ public class TAP<R> implements VOSIResource { } @Override - public String getStandardID() { return "ivo://ivoa.net/std/TAP"; } + public String getStandardID(){ + return "ivo://ivoa.net/std/TAP"; + } @Override - public String getAccessURL() { return tapBaseURL; } + public String getAccessURL(){ + return tapBaseURL; + } @Override - public String getCapability() { + public String getCapability(){ StringBuffer xml = new StringBuffer(); xml.append("<capability standardID=\"").append(getStandardID()).append("\" xsi:type=\"tr:TableAccess\">\n"); @@ -265,27 +268,27 @@ public class TAP<R> implements VOSIResource { /** * @return The homePageURI. */ - public final String getHomePageURI() { + public final String getHomePageURI(){ return homePageURI; } public final void setHomePageURI(String uri){ - homePageURI = (uri!=null)?uri.trim():uri; + homePageURI = (uri != null) ? uri.trim() : uri; if (homePageURI != null && homePageURI.length() == 0) homePageURI = null; } - public void init(ServletConfig config) throws ServletException { + public void init(ServletConfig config) throws ServletException{ for(TAPResource res : resources.values()) res.init(config); } - public void destroy() { + public void destroy(){ for(TAPResource res : resources.values()) res.destroy(); } - public void executeRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + public void executeRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ response.setContentType("text/plain"); if (tapBaseURL == null) @@ -313,29 +316,29 @@ public class TAP<R> implements VOSIResource { if (res != null) res.executeResource(request, response); else - errorWriter.writeError("This TAP service does not have a resource named \""+resourceName+"\" !", ErrorType.TRANSIENT, HttpServletResponse.SC_NOT_FOUND, response, request, null, "Get a TAP resource"); + errorWriter.writeError("This TAP service does not have a resource named \"" + resourceName + "\" !", ErrorType.TRANSIENT, HttpServletResponse.SC_NOT_FOUND, response, request, null, "Get a TAP resource"); } service.getLogger().httpRequest(request, owner, resourceName, HttpServletResponse.SC_OK, "[OK]", null); response.flushBuffer(); }catch(IOException ioe){ - errorWriter.writeError(ioe, response, request, owner, (resourceName==null)?"Writing the TAP home page":("Executing the TAP resource "+resourceName)); + errorWriter.writeError(ioe, response, request, owner, (resourceName == null) ? "Writing the TAP home page" : ("Executing the TAP resource " + resourceName)); }catch(UWSException ue){ - errorWriter.writeError(ue, response, request, owner, (resourceName==null)?"Writing the TAP home page":("Executing the TAP resource "+resourceName)); + errorWriter.writeError(ue, response, request, owner, (resourceName == null) ? "Writing the TAP home page" : ("Executing the TAP resource " + resourceName)); }catch(TAPException te){ writeError(te, response); }catch(Throwable t){ - errorWriter.writeError(t, response, request, owner, (resourceName==null)?"Writing the TAP home page":("Executing the TAP resource "+resourceName)); + errorWriter.writeError(t, response, request, owner, (resourceName == null) ? "Writing the TAP home page" : ("Executing the TAP resource " + resourceName)); } } - public void writeHomePage(final PrintWriter writer, final JobOwner owner) throws IOException { + public void writeHomePage(final PrintWriter writer, final JobOwner owner) throws IOException{ // By default, list all available resources: if (homePageURI == null){ writer.println("<html><head><title>TAP HOME PAGE</title></head><body><h1 style=\"text-align: center\">TAP HOME PAGE</h1><h2>Available resources:</h2><ul>"); for(TAPResource res : resources.values()) - writer.println("<li><a href=\""+tapBaseURL+"/"+res.getName()+"\">"+res.getName()+"</a></li>"); + writer.println("<li><a href=\"" + tapBaseURL + "/" + res.getName() + "\">" + res.getName() + "</a></li>"); writer.println("</ul></body></html>"); } // or Display the specified home page: @@ -350,12 +353,12 @@ public class TAP<R> implements VOSIResource { throw new IOException("Incorrect TAP home page URI !"); byte[] buffer = new byte[255]; int nbReads = 0; - while((nbReads=input.read(buffer)) > 0) + while((nbReads = input.read(buffer)) > 0) writer.print(new String(buffer, 0, nbReads)); } } - public void writeError(TAPException ex, HttpServletResponse response) throws ServletException, IOException { + public void writeError(TAPException ex, HttpServletResponse response) throws ServletException, IOException{ service.getLogger().error(ex); response.reset(); response.setStatus(ex.getHttpErrorCode()); @@ -363,7 +366,7 @@ public class TAP<R> implements VOSIResource { writeError(ex, response.getWriter()); } - protected void writeError(TAPException ex, PrintWriter output) throws ServletException, IOException { + protected void writeError(TAPException ex, PrintWriter output) throws ServletException, IOException{ output.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); output.println("<VOTABLE xmlns=\"http://www.ivoa.net/xml/VOTable/v1.2\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.ivoa.net/xml/VOTable/v1.2\" version=\"1.2\">"); output.println("\t<RESOURCE type=\"results\">"); @@ -371,18 +374,21 @@ public class TAP<R> implements VOSIResource { // Print the error: output.println("\t\t<INFO name=\"QUERY_STATUS\" value=\"ERROR\">"); output.print("\t\t\t<![CDATA[ "); - if (ex.getExecutionStatus()!=null) - output.print("[WHILE "+ex.getExecutionStatus()+"] "); + if (ex.getExecutionStatus() != null) + output.print("[WHILE " + ex.getExecutionStatus() + "] "); output.print(ex.getMessage().replace('«', '\"').replace('»', '\"')); output.println("]]>\t\t</INFO>"); // Print the current date: DateFormat dateFormat = new SimpleDateFormat(UWSJob.DEFAULT_DATE_FORMAT); - output.print("\t\t<INFO name=\"DATE\" value=\""); output.print(dateFormat.format(new Date())); output.println("\" />"); + output.print("\t\t<INFO name=\"DATE\" value=\""); + output.print(dateFormat.format(new Date())); + output.println("\" />"); // Print the provider (if any): if (service.getProviderName() != null){ - output.print("\t\t<INFO name=\"PROVIDER\" value=\""); output.print(service.getProviderName()); + output.print("\t\t<INFO name=\"PROVIDER\" value=\""); + output.print(service.getProviderName()); if (service.getProviderDescription() != null){ output.print("\">\n\t\t\t<![CDATA["); output.print(service.getProviderDescription()); @@ -414,7 +420,7 @@ public class TAP<R> implements VOSIResource { public final boolean addResource(String resourceId, TAPResource newResource){ if (newResource == null) return false; - resources.put((resourceId==null)?newResource.getName():resourceId, newResource); + resources.put((resourceId == null) ? newResource.getName() : resourceId, newResource); return true; } diff --git a/src/tap/upload/LimitedSizeInputStream.java b/src/tap/upload/LimitedSizeInputStream.java index 5bb7572cb3fc488cc444b0066a0edd12d5feb2df..dd95527f390081201b96ffcfc597549cca557482 100644 --- a/src/tap/upload/LimitedSizeInputStream.java +++ b/src/tap/upload/LimitedSizeInputStream.java @@ -34,8 +34,7 @@ public final class LimitedSizeInputStream extends InputStream { private boolean exceed = false; - - public LimitedSizeInputStream(final InputStream stream, final long sizeLimit) throws NullPointerException { + public LimitedSizeInputStream(final InputStream stream, final long sizeLimit) throws NullPointerException{ if (stream == null) throw new NullPointerException("The given input stream is NULL !"); input = stream; @@ -45,7 +44,7 @@ public final class LimitedSizeInputStream extends InputStream { this.sizeLimit = sizeLimit; } - private void updateCounter(final long nbReads) throws ExceededSizeException { + private void updateCounter(final long nbReads) throws ExceededSizeException{ if (nbReads > 0){ counter += nbReads; if (counter > sizeLimit){ @@ -60,55 +59,55 @@ public final class LimitedSizeInputStream extends InputStream { } @Override - public int read() throws IOException { + public int read() throws IOException{ int read = input.read(); updateCounter(1); return read; } @Override - public int read(byte[] b) throws IOException { + public int read(byte[] b) throws IOException{ int nbRead = input.read(b); updateCounter(nbRead); return nbRead; } @Override - public int read(byte[] b, int off, int len) throws IOException { + public int read(byte[] b, int off, int len) throws IOException{ int nbRead = input.read(b, off, len); updateCounter(nbRead); return nbRead; } @Override - public long skip(long n) throws IOException { + public long skip(long n) throws IOException{ long nbSkipped = input.skip(n); updateCounter(nbSkipped); return nbSkipped; } @Override - public int available() throws IOException { + public int available() throws IOException{ return input.available(); } @Override - public void close() throws IOException { + public void close() throws IOException{ input.close(); } @Override - public synchronized void mark(int readlimit) throws UnsupportedOperationException { + public synchronized void mark(int readlimit) throws UnsupportedOperationException{ throw new UnsupportedOperationException("mark() not supported in a LimitedSizeInputStream !"); } @Override - public boolean markSupported() { + public boolean markSupported(){ return false; } @Override - public synchronized void reset() throws IOException, UnsupportedOperationException { + public synchronized void reset() throws IOException, UnsupportedOperationException{ throw new UnsupportedOperationException("mark() not supported in a LimitedSizeInputStream !"); } diff --git a/src/tap/upload/TableLoader.java b/src/tap/upload/TableLoader.java index 41cdb108d6eb7dcaae30f54fa6f0c0b96b4bc0d4..e8b050206347c3fc54eeee9f571f46abeddd82e9 100644 --- a/src/tap/upload/TableLoader.java +++ b/src/tap/upload/TableLoader.java @@ -59,7 +59,7 @@ public class TableLoader { if (multipart == null) throw new InvalidParameterException("The URI scheme \"param\" can be used ONLY IF the VOTable is provided inside the HTTP request (multipart/form-data) !"); else if (URI.length() <= PARAM_PREFIX.length()) - throw new InvalidParameterException("Incomplete URI ("+URI+"): empty parameter name !"); + throw new InvalidParameterException("Incomplete URI (" + URI + "): empty parameter name !"); url = null; param = URI.substring(PARAM_PREFIX.length()).trim(); @@ -72,7 +72,7 @@ public class TableLoader { } if (foundFile == null) - throw new InvalidParameterException("Incorrect file reference ("+URI+"): the parameter \""+param+"\" does not exist !"); + throw new InvalidParameterException("Incorrect file reference (" + URI + "): the parameter \"" + param + "\" does not exist !"); else file = foundFile; }else if (URI.matches(URL_REGEXP)){ @@ -84,17 +84,17 @@ public class TableLoader { throw new InvalidParameterException(mue.getMessage()); } }else - throw new InvalidParameterException("Invalid table URI: \""+URI+"\" !"); + throw new InvalidParameterException("Invalid table URI: \"" + URI + "\" !"); } - public InputStream openStream() throws IOException { + public InputStream openStream() throws IOException{ if (url != null) return url.openStream(); else return new FileInputStream(file); } - public boolean deleteFile() { + public boolean deleteFile(){ if (file != null && file.exists()) return file.delete(); else diff --git a/src/tap/upload/Uploader.java b/src/tap/upload/Uploader.java index f45f549af18098a8fcf16053a5f5653749a1fe4d..b453c8a3cf4adac3b0d1b4cdcdc449c33bd85306 100644 --- a/src/tap/upload/Uploader.java +++ b/src/tap/upload/Uploader.java @@ -56,7 +56,7 @@ public class Uploader { protected int nbRows = 0; - public Uploader(final ServiceConnection<?> service, final DBConnection<?> dbConn) throws TAPException { + public Uploader(final ServiceConnection<?> service, final DBConnection<?> dbConn) throws TAPException{ if (service == null) throw new NullPointerException("The given ServiceConnection is NULL !"); if (dbConn == null) @@ -82,7 +82,7 @@ public class Uploader { } } - public TAPSchema upload(final TableLoader[] loaders) throws TAPException { + public TAPSchema upload(final TableLoader[] loaders) throws TAPException{ // Begin a DB transaction: dbConn.startTransaction(); @@ -108,7 +108,7 @@ public class Uploader { FieldSet fields = resource.getFieldSet(0); // 1st STEP: Convert the VOTable metadata into DBTable: - TAPTable tapTable = fetchTableMeta(tableName, System.currentTimeMillis()+"", fields); + TAPTable tapTable = fetchTableMeta(tableName, System.currentTimeMillis() + "", fields); uploadSchema.addTable(tapTable); // 2nd STEP: Create the corresponding table in the database: @@ -128,21 +128,23 @@ public class Uploader { throw dbe; }catch(ExceededSizeException ese){ dbConn.cancelTransaction(); // ROLLBACK - throw new TAPException("Upload limit exceeded ! You can upload at most "+((nbBytesLimit > 0)?(nbBytesLimit+" bytes."):(nbRowsLimit+" rows."))); + throw new TAPException("Upload limit exceeded ! You can upload at most " + ((nbBytesLimit > 0) ? (nbBytesLimit + " bytes.") : (nbRowsLimit + " rows."))); }catch(IOException ioe){ dbConn.cancelTransaction(); // ROLLBACK - throw new TAPException("Error while reading the VOTable of \""+tableName+"\" !", ioe); + throw new TAPException("Error while reading the VOTable of \"" + tableName + "\" !", ioe); }catch(NullPointerException npe){ dbConn.cancelTransaction(); // ROLLBACK if (votable != null && votable instanceof LimitedSizeInputStream) - throw new TAPException("Upload limit exceeded ! You can upload at most "+((nbBytesLimit > 0)?(nbBytesLimit+" bytes."):(nbRowsLimit+" rows."))); + throw new TAPException("Upload limit exceeded ! You can upload at most " + ((nbBytesLimit > 0) ? (nbBytesLimit + " bytes.") : (nbRowsLimit + " rows."))); else throw new TAPException(npe); }finally{ try{ if (votable != null) votable.close(); - }catch(IOException ioe){;} + }catch(IOException ioe){ + ; + } } // Commit modifications: @@ -157,9 +159,9 @@ public class Uploader { private TAPTable fetchTableMeta(final String tableName, final String userId, final FieldSet fields){ TAPTable tapTable = new TAPTable(tableName); - tapTable.setDBName(tableName+"_"+userId); + tapTable.setDBName(tableName + "_" + userId); - for(int j=0 ; j<fields.getItemCount(); j++){ + for(int j = 0; j < fields.getItemCount(); j++){ SavotField field = (SavotField)fields.getItemAt(j); int arraysize = TAPTypes.NO_SIZE; if (field.getArraySize() == null || field.getArraySize().trim().isEmpty()) @@ -170,7 +172,7 @@ public class Uploader { try{ arraysize = Integer.parseInt(field.getArraySize()); }catch(NumberFormatException nfe){ - service.getLogger().warning("Invalid array-size in the uploaded table \""+tableName+"\" for the field \""+field.getName()+"\": \""+field.getArraySize()+"\" ! It will be considered as \"*\" !"); + service.getLogger().warning("Invalid array-size in the uploaded table \"" + tableName + "\" for the field \"" + field.getName() + "\": \"" + field.getArraySize() + "\" ! It will be considered as \"*\" !"); } } tapTable.addColumn(field.getName(), field.getDescription(), field.getUnit(), field.getUcd(), field.getUtype(), new VotType(field.getDataType(), arraysize, field.getXtype()), false, false, false); @@ -179,7 +181,7 @@ public class Uploader { return tapTable; } - private int loadTable(final TAPTable tapTable, final FieldSet fields, final SavotBinary binary) throws TAPException, ExceededSizeException { + private int loadTable(final TAPTable tapTable, final FieldSet fields, final SavotBinary binary) throws TAPException, ExceededSizeException{ // Read the raw binary data: DataBinaryReader reader = null; try{ @@ -193,20 +195,22 @@ public class Uploader { }catch(ExceededSizeException ese){ throw ese; }catch(IOException se){ - throw new TAPException("Error while reading the binary data of the VOTable of \""+tapTable.getADQLName()+"\" !", se); + throw new TAPException("Error while reading the binary data of the VOTable of \"" + tapTable.getADQLName() + "\" !", se); }finally{ try{ if (reader != null) reader.close(); - }catch(IOException ioe){;} + }catch(IOException ioe){ + ; + } } return nbRows; } - private int loadTable(final TAPTable tapTable, final FieldSet fields, final SavotTableData data) throws TAPException, ExceededSizeException { + private int loadTable(final TAPTable tapTable, final FieldSet fields, final SavotTableData data) throws TAPException, ExceededSizeException{ TRSet rows = data.getTRs(); - for(int i=0; i<rows.getItemCount(); i++){ + for(int i = 0; i < rows.getItemCount(); i++){ if (nbRowsLimit > 0 && nbRows >= nbRowsLimit) throw new ExceededSizeException(); dbConn.insertRow((SavotTR)rows.getItemAt(i), tapTable); diff --git a/src/uws/AcceptHeader.java b/src/uws/AcceptHeader.java index b4074434f51cf6b277b96b2a425d963a04114aa8..f12ed18e0381826a93165864675799173e9cc257 100644 --- a/src/uws/AcceptHeader.java +++ b/src/uws/AcceptHeader.java @@ -39,42 +39,40 @@ import java.util.Map.Entry; public class AcceptHeader { /** Quality for each extracted MIME type. */ - private Map<String, Float> mMimeTypes; + private Map<String,Float> mMimeTypes; /** Association between a quality and a list of MIME types. */ - private Map<Float, List<String>> mSortedMimeTypes; - + private Map<Float,List<String>> mSortedMimeTypes; /** * Parses the given value of the Accept field of HTTP request header. * * @param acceptS The list of MIME types to parse. */ - public AcceptHeader(String acceptS) { + public AcceptHeader(String acceptS){ mMimeTypes = new HashMap<String,Float>(); // List of MIME-types String[] mimeTypes = acceptS.split(","); - for (String mimeType : Arrays.asList(mimeTypes)) { + for(String mimeType : Arrays.asList(mimeTypes)){ // Get quality Float quality = new Float(1); String[] split = mimeType.split(";"); - if (split.length > 1) { + if (split.length > 1){ String[] qualitySplit = split[1].split("="); quality = Float.parseFloat(qualitySplit[1]); } mMimeTypes.put(split[0], quality); } // Sort mimeTypes by requested quality - mSortedMimeTypes = new HashMap<Float, List<String>>(); - Set<Entry<String, Float>> mimeTypesES = mMimeTypes.entrySet(); - for (Entry<String, Float> mimeType : mimeTypesES) { - if (!mSortedMimeTypes.containsKey(mimeType.getValue())) { + mSortedMimeTypes = new HashMap<Float,List<String>>(); + Set<Entry<String,Float>> mimeTypesES = mMimeTypes.entrySet(); + for(Entry<String,Float> mimeType : mimeTypesES){ + if (!mSortedMimeTypes.containsKey(mimeType.getValue())){ List<String> mimeTypesL = new ArrayList<String>(); mimeTypesL.add(mimeType.getKey()); mSortedMimeTypes.put(mimeType.getValue(), mimeTypesL); - } else { - mSortedMimeTypes.get(mimeType.getValue()).add( - mimeType.getKey()); + }else{ + mSortedMimeTypes.get(mimeType.getValue()).add(mimeType.getKey()); } } } @@ -84,7 +82,7 @@ public class AcceptHeader { * * @return Extracted MIME types and their quality. */ - public final Map<String, Float> getMimeTypes() { + public final Map<String,Float> getMimeTypes(){ return mMimeTypes; } @@ -93,7 +91,7 @@ public class AcceptHeader { * * @param mimeTypes MIME types and their quality. */ - public final void setMimeTypes(Map<String, Float> mimeTypes) { + public final void setMimeTypes(Map<String,Float> mimeTypes){ mMimeTypes = mimeTypes; } @@ -104,31 +102,29 @@ public class AcceptHeader { * or <i>text/xml</i> or <i>application/json</i> * or <i>* /*</i>. */ - public String getPreferredMimeType() { - if (mSortedMimeTypes.size() == 0) { + public String getPreferredMimeType(){ + if (mSortedMimeTypes.size() == 0){ return "*/*"; } Float[] qualities = mSortedMimeTypes.keySet().toArray(new Float[0]); Arrays.sort(qualities, Collections.reverseOrder()); String choosenMimeType = null; - for (Float key : Arrays.asList(qualities)) { + for(Float key : Arrays.asList(qualities)){ List<String> mimeTypes = mSortedMimeTypes.get(key); String htmlMimeType = null; - for (String mimeType : mimeTypes) { - if (mimeType.equals("application/xhtml+xml") - || mimeType.equals("text/html")) { + for(String mimeType : mimeTypes){ + if (mimeType.equals("application/xhtml+xml") || mimeType.equals("text/html")){ htmlMimeType = mimeType; break; } - if (mimeType.equals("text/xml") - || mimeType.equals("application/json")) { + if (mimeType.equals("text/xml") || mimeType.equals("application/json")){ choosenMimeType = mimeType; } } - if (htmlMimeType != null) { + if (htmlMimeType != null){ return htmlMimeType; } - if (choosenMimeType != null) { + if (choosenMimeType != null){ return choosenMimeType; } } @@ -145,7 +141,7 @@ public class AcceptHeader { Arrays.sort(qualities, Collections.reverseOrder()); ArrayList<String> orderedMimeTypes = new ArrayList<String>(); - for(int i=0; i<qualities.length; i++){ + for(int i = 0; i < qualities.length; i++){ List<String> mimeTypes = mSortedMimeTypes.get(qualities[i]); if (mimeTypes != null) orderedMimeTypes.addAll(mimeTypes); diff --git a/src/uws/COPYING.LESSER.txt b/src/uws/COPYING.LESSER.txt deleted file mode 100644 index 65c5ca88a67c30becee01c5a8816d964b03862f9..0000000000000000000000000000000000000000 --- a/src/uws/COPYING.LESSER.txt +++ /dev/null @@ -1,165 +0,0 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - - This version of the GNU Lesser General Public License incorporates -the terms and conditions of version 3 of the GNU General Public -License, supplemented by the additional permissions listed below. - - 0. Additional Definitions. - - As used herein, "this License" refers to version 3 of the GNU Lesser -General Public License, and the "GNU GPL" refers to version 3 of the GNU -General Public License. - - "The Library" refers to a covered work governed by this License, -other than an Application or a Combined Work as defined below. - - An "Application" is any work that makes use of an interface provided -by the Library, but which is not otherwise based on the Library. -Defining a subclass of a class defined by the Library is deemed a mode -of using an interface provided by the Library. - - A "Combined Work" is a work produced by combining or linking an -Application with the Library. The particular version of the Library -with which the Combined Work was made is also called the "Linked -Version". - - The "Minimal Corresponding Source" for a Combined Work means the -Corresponding Source for the Combined Work, excluding any source code -for portions of the Combined Work that, considered in isolation, are -based on the Application, and not on the Linked Version. - - The "Corresponding Application Code" for a Combined Work means the -object code and/or source code for the Application, including any data -and utility programs needed for reproducing the Combined Work from the -Application, but excluding the System Libraries of the Combined Work. - - 1. Exception to Section 3 of the GNU GPL. - - You may convey a covered work under sections 3 and 4 of this License -without being bound by section 3 of the GNU GPL. - - 2. Conveying Modified Versions. - - If you modify a copy of the Library, and, in your modifications, a -facility refers to a function or data to be supplied by an Application -that uses the facility (other than as an argument passed when the -facility is invoked), then you may convey a copy of the modified -version: - - a) under this License, provided that you make a good faith effort to - ensure that, in the event an Application does not supply the - function or data, the facility still operates, and performs - whatever part of its purpose remains meaningful, or - - b) under the GNU GPL, with none of the additional permissions of - this License applicable to that copy. - - 3. Object Code Incorporating Material from Library Header Files. - - The object code form of an Application may incorporate material from -a header file that is part of the Library. You may convey such object -code under terms of your choice, provided that, if the incorporated -material is not limited to numerical parameters, data structure -layouts and accessors, or small macros, inline functions and templates -(ten or fewer lines in length), you do both of the following: - - a) Give prominent notice with each copy of the object code that the - Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the object code with a copy of the GNU GPL and this license - document. - - 4. Combined Works. - - You may convey a Combined Work under terms of your choice that, -taken together, effectively do not restrict modification of the -portions of the Library contained in the Combined Work and reverse -engineering for debugging such modifications, if you also do each of -the following: - - a) Give prominent notice with each copy of the Combined Work that - the Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the Combined Work with a copy of the GNU GPL and this license - document. - - c) For a Combined Work that displays copyright notices during - execution, include the copyright notice for the Library among - these notices, as well as a reference directing the user to the - copies of the GNU GPL and this license document. - - d) Do one of the following: - - 0) Convey the Minimal Corresponding Source under the terms of this - License, and the Corresponding Application Code in a form - suitable for, and under terms that permit, the user to - recombine or relink the Application with a modified version of - the Linked Version to produce a modified Combined Work, in the - manner specified by section 6 of the GNU GPL for conveying - Corresponding Source. - - 1) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (a) uses at run time - a copy of the Library already present on the user's computer - system, and (b) will operate properly with a modified version - of the Library that is interface-compatible with the Linked - Version. - - e) Provide Installation Information, but only if you would otherwise - be required to provide such information under section 6 of the - GNU GPL, and only to the extent that such information is - necessary to install and execute a modified version of the - Combined Work produced by recombining or relinking the - Application with a modified version of the Linked Version. (If - you use option 4d0, the Installation Information must accompany - the Minimal Corresponding Source and Corresponding Application - Code. If you use option 4d1, you must provide the Installation - Information in the manner specified by section 6 of the GNU GPL - for conveying Corresponding Source.) - - 5. Combined Libraries. - - You may place library facilities that are a work based on the -Library side by side in a single library together with other library -facilities that are not Applications and are not covered by this -License, and convey such a combined library under terms of your -choice, if you do both of the following: - - a) Accompany the combined library with a copy of the same work based - on the Library, uncombined with any other library facilities, - conveyed under the terms of this License. - - b) Give prominent notice with the combined library that part of it - is a work based on the Library, and explaining where to find the - accompanying uncombined form of the same work. - - 6. Revised Versions of the GNU Lesser General Public License. - - The Free Software Foundation may publish revised and/or new versions -of the GNU Lesser General Public License from time to time. Such new -versions will be similar in spirit to the present version, but may -differ in detail to address new problems or concerns. - - Each version is given a distinguishing version number. If the -Library as you received it specifies that a certain numbered version -of the GNU Lesser General Public License "or any later version" -applies to it, you have the option of following the terms and -conditions either of that published version or of any later version -published by the Free Software Foundation. If the Library as you -received it does not specify a version number of the GNU Lesser -General Public License, you may choose any version of the GNU Lesser -General Public License ever published by the Free Software Foundation. - - If the Library as you received it specifies that a proxy can decide -whether future versions of the GNU Lesser General Public License shall -apply, that proxy's public statement of acceptance of any version is -permanent authorization for you to choose that version for the -Library. diff --git a/src/uws/UWSExceptionFactory.java b/src/uws/UWSExceptionFactory.java index 36f1f3247fb76eedf185d3b0c6873f619e236e59..c2812736eccedb340ef7cfbc5d252a79aed5f8b5 100644 --- a/src/uws/UWSExceptionFactory.java +++ b/src/uws/UWSExceptionFactory.java @@ -36,116 +36,177 @@ public final class UWSExceptionFactory { /** * NO INSTANCE OF THIS CLASS MUST BE CREATED ! */ - private UWSExceptionFactory() { ; } + private UWSExceptionFactory(){ + ; + } /** * If the given message is returned ONLY IF it is not NULL AND not empty. * @param consequence A message to test. * @return The given message if it is not NULL and not an empty string. */ - private final static String appendMessage(final String consequence){ return ((consequence == null || consequence.trim().length() > 0) ? "" : " => "+consequence); } + private final static String appendMessage(final String consequence){ + return ((consequence == null || consequence.trim().length() > 0) ? "" : " => " + consequence); + } + + public final static UWSException missingJobListName(){ + return missingJobListName(null); + } - public final static UWSException missingJobListName(){ return missingJobListName(null); } public final static UWSException missingJobListName(final String consequence){ return new UWSException(UWSException.BAD_REQUEST, "Missing job list name !" + appendMessage(consequence)); } - public final static UWSException incorrectJobListName(final String jlName){ return incorrectJobListName(jlName, null); } + public final static UWSException incorrectJobListName(final String jlName){ + return incorrectJobListName(jlName, null); + } + public final static UWSException incorrectJobListName(final String jlName, final String consequence){ - return new UWSException(UWSException.NOT_FOUND, "Incorrect job list name ! The jobs list "+jlName+" does not exist." + appendMessage(consequence)); + return new UWSException(UWSException.NOT_FOUND, "Incorrect job list name ! The jobs list " + jlName + " does not exist." + appendMessage(consequence)); + } + + public final static UWSException missingJobID(){ + return missingJobID(null); } - public final static UWSException missingJobID(){ return missingJobID(null); } public final static UWSException missingJobID(final String consequence){ return new UWSException(UWSException.BAD_REQUEST, "Missing job ID !" + appendMessage(consequence)); } - public final static UWSException incorrectJobID(String jobListName, String jobID){ return incorrectJobID(jobListName, jobID, null); } + public final static UWSException incorrectJobID(String jobListName, String jobID){ + return incorrectJobID(jobListName, jobID, null); + } + public final static UWSException incorrectJobID(final String jobListName, final String jobID, final String consequence){ - return new UWSException(UWSException.NOT_FOUND, "Incorrect job ID ! The job "+jobID+" does not exist in the jobs list "+jobListName + appendMessage(consequence)); + return new UWSException(UWSException.NOT_FOUND, "Incorrect job ID ! The job " + jobID + " does not exist in the jobs list " + jobListName + appendMessage(consequence)); + } + + public final static UWSException missingSerializer(final String mimeTypes){ + return missingSerializer(null); } - public final static UWSException missingSerializer(final String mimeTypes){ return missingSerializer(null); } public final static UWSException missingSerializer(final String mimeTypes, final String consequence){ - return new UWSException(UWSException.INTERNAL_SERVER_ERROR, "Missing UWS serializer for the MIME types: "+mimeTypes+" !" + appendMessage(consequence)); + return new UWSException(UWSException.INTERNAL_SERVER_ERROR, "Missing UWS serializer for the MIME types: " + mimeTypes + " !" + appendMessage(consequence)); + } + + public final static UWSException incorrectJobParameter(final String jobID, final String paramName){ + return incorrectJobParameter(jobID, paramName, null); } - public final static UWSException incorrectJobParameter(final String jobID, final String paramName){ return incorrectJobParameter(jobID, paramName, null); } public final static UWSException incorrectJobParameter(final String jobID, final String paramName, final String consequence){ - return new UWSException(UWSException.NOT_FOUND, "Incorrect job parameter ! The parameter "+paramName+" does not exist in the job "+jobID+"." + appendMessage(consequence)); + return new UWSException(UWSException.NOT_FOUND, "Incorrect job parameter ! The parameter " + paramName + " does not exist in the job " + jobID + "." + appendMessage(consequence)); + } + + public final static UWSException incorrectJobResult(final String jobID, final String resultID){ + return incorrectJobResult(jobID, resultID, null); } - public final static UWSException incorrectJobResult(final String jobID, final String resultID){ return incorrectJobResult(jobID, resultID, null); } public final static UWSException incorrectJobResult(final String jobID, final String resultID, final String consequence){ - return new UWSException(UWSException.NOT_FOUND, "Incorrect result ID ! There is no result "+resultID+" in the job "+jobID+"." + appendMessage(consequence)); + return new UWSException(UWSException.NOT_FOUND, "Incorrect result ID ! There is no result " + resultID + " in the job " + jobID + "." + appendMessage(consequence)); + } + + public final static UWSException noErrorSummary(final String jobID){ + return noErrorSummary(jobID, null); } - public final static UWSException noErrorSummary(final String jobID){ return noErrorSummary(jobID, null); } public final static UWSException noErrorSummary(final String jobID, final String consequence){ - return new UWSException(UWSException.NOT_FOUND, "There is no error summary in the job "+jobID+" !"+appendMessage(consequence)); + return new UWSException(UWSException.NOT_FOUND, "There is no error summary in the job " + jobID + " !" + appendMessage(consequence)); + } + + public final static UWSException incorrectPhaseTransition(final String jobID, final ExecutionPhase fromPhase, final ExecutionPhase toPhase){ + return incorrectPhaseTransition(jobID, fromPhase, toPhase, null); } - public final static UWSException incorrectPhaseTransition(final String jobID, final ExecutionPhase fromPhase, final ExecutionPhase toPhase){ return incorrectPhaseTransition(jobID, fromPhase, toPhase, null); } public final static UWSException incorrectPhaseTransition(final String jobID, final ExecutionPhase fromPhase, final ExecutionPhase toPhase, final String consequence){ - return new UWSException(UWSException.BAD_REQUEST, "Incorrect phase transition ! => the job "+jobID+" is in the phase "+fromPhase+". It can not go to "+toPhase+"."+appendMessage(consequence)); + return new UWSException(UWSException.BAD_REQUEST, "Incorrect phase transition ! => the job " + jobID + " is in the phase " + fromPhase + ". It can not go to " + toPhase + "." + appendMessage(consequence)); + } + + public final static UWSException missingOutputStream(){ + return missingOutputStream(null); } - public final static UWSException missingOutputStream(){ return missingOutputStream(null); } public final static UWSException missingOutputStream(final String consequence){ - return new UWSException(UWSException.INTERNAL_SERVER_ERROR, "Missing output stream !"+appendMessage(consequence)); + return new UWSException(UWSException.INTERNAL_SERVER_ERROR, "Missing output stream !" + appendMessage(consequence)); + } + + public final static UWSException incorrectSerialization(final String serializationValue, final String serializationTarget){ + return incorrectSerialization(serializationValue, serializationTarget, null); } - public final static UWSException incorrectSerialization(final String serializationValue, final String serializationTarget){ return incorrectSerialization(serializationValue, serializationTarget, null); } public final static UWSException incorrectSerialization(final String serializationValue, final String serializationTarget, final String consequence){ - return new UWSException(UWSException.INTERNAL_SERVER_ERROR, "Incorrect serialization value (="+serializationValue+") ! => impossible to serialize "+serializationTarget+"."+appendMessage(consequence)); + return new UWSException(UWSException.INTERNAL_SERVER_ERROR, "Incorrect serialization value (=" + serializationValue + ") ! => impossible to serialize " + serializationTarget + "." + appendMessage(consequence)); + } + + public final static UWSException readPermissionDenied(final JobOwner user, final boolean jobList, final String containerName){ + return readPermissionDenied(user, jobList, containerName, null); } - public final static UWSException readPermissionDenied(final JobOwner user, final boolean jobList, final String containerName){ return readPermissionDenied(user, jobList, containerName, null); } public final static UWSException readPermissionDenied(final JobOwner user, final boolean jobList, final String containerName, final String consequence){ - return new UWSException(UWSException.PERMISSION_DENIED, user.getID()+((user.getPseudo()==null)?"":(" (alias "+user.getPseudo()+")"))+" is not allowed to read the content of the "+(jobList?"jobs list":"job")+" \""+containerName+"\" !"+appendMessage(consequence)); + return new UWSException(UWSException.PERMISSION_DENIED, user.getID() + ((user.getPseudo() == null) ? "" : (" (alias " + user.getPseudo() + ")")) + " is not allowed to read the content of the " + (jobList ? "jobs list" : "job") + " \"" + containerName + "\" !" + appendMessage(consequence)); + } + + public final static UWSException writePermissionDenied(final JobOwner user, final boolean jobList, final String containerName){ + return writePermissionDenied(user, jobList, containerName, null); } - public final static UWSException writePermissionDenied(final JobOwner user, final boolean jobList, final String containerName){ return writePermissionDenied(user, jobList, containerName, null); } public final static UWSException writePermissionDenied(final JobOwner user, final boolean jobList, final String containerName, final String consequence){ - return new UWSException(UWSException.PERMISSION_DENIED, user.getID()+((user.getPseudo()==null)?"":(" (alias "+user.getPseudo()+")"))+" is not allowed to update the content of the "+(jobList?"jobs list":"job")+" \""+containerName+"\" !"+appendMessage(consequence)); + return new UWSException(UWSException.PERMISSION_DENIED, user.getID() + ((user.getPseudo() == null) ? "" : (" (alias " + user.getPseudo() + ")")) + " is not allowed to update the content of the " + (jobList ? "jobs list" : "job") + " \"" + containerName + "\" !" + appendMessage(consequence)); + } + + public final static UWSException executePermissionDenied(final JobOwner user, final String jobID){ + return executePermissionDenied(user, jobID, null); } - public final static UWSException executePermissionDenied(final JobOwner user, final String jobID){ return executePermissionDenied(user, jobID, null); } public final static UWSException executePermissionDenied(final JobOwner user, final String jobID, final String consequence){ - return new UWSException(UWSException.PERMISSION_DENIED, user.getID()+((user.getPseudo()==null)?"":(" (alias "+user.getPseudo()+")"))+" is not allowed to execute/abort the job \""+jobID+"\" !"+appendMessage(consequence)); + return new UWSException(UWSException.PERMISSION_DENIED, user.getID() + ((user.getPseudo() == null) ? "" : (" (alias " + user.getPseudo() + ")")) + " is not allowed to execute/abort the job \"" + jobID + "\" !" + appendMessage(consequence)); + } + + public final static UWSException restoreJobImpossible(final Throwable t, final String cause){ + return restoreJobImpossible(t, cause, null); } - public final static UWSException restoreJobImpossible(final Throwable t, final String cause){ return restoreJobImpossible(t, cause, null); } public final static UWSException restoreJobImpossible(final Throwable t, final String cause, final String consequence){ - return new UWSException(UWSException.INTERNAL_SERVER_ERROR, t, ((cause == null)?"":cause)+" Impossible to restore a job from the backup file(s)."+appendMessage(consequence)); + return new UWSException(UWSException.INTERNAL_SERVER_ERROR, t, ((cause == null) ? "" : cause) + " Impossible to restore a job from the backup file(s)." + appendMessage(consequence)); + } + + public final static UWSException restoreUserImpossible(final String cause){ + return restoreUserImpossible(null, cause, null); + } + + public final static UWSException restoreUserImpossible(final Throwable t, final String cause){ + return restoreUserImpossible(t, cause, null); } - public final static UWSException restoreUserImpossible(final String cause){ return restoreUserImpossible(null, cause, null); } - public final static UWSException restoreUserImpossible(final Throwable t, final String cause){ return restoreUserImpossible(t, cause, null); } public final static UWSException restoreUserImpossible(final Throwable t, final String cause, final String consequence){ - return new UWSException(UWSException.INTERNAL_SERVER_ERROR, t, ((cause == null)?"":cause)+" Impossible to restore a user from the backup file(s)."+appendMessage(consequence)); + return new UWSException(UWSException.INTERNAL_SERVER_ERROR, t, ((cause == null) ? "" : cause) + " Impossible to restore a user from the backup file(s)." + appendMessage(consequence)); + } + + public final static UWSException jobModificationForbidden(final String jobId, final ExecutionPhase phase, final String parameter){ + return jobModificationForbidden(jobId, phase, parameter, null); } - public final static UWSException jobModificationForbidden(final String jobId, final ExecutionPhase phase, final String parameter){ return jobModificationForbidden(jobId, phase, parameter, null); } public final static UWSException jobModificationForbidden(final String jobId, final ExecutionPhase phase, final String parameter, final String consequence){ if (parameter != null && !parameter.trim().isEmpty()) - return new UWSException(UWSException.NOT_ALLOWED, "Impossible to change the parameter \""+parameter+"\" of the job "+jobId+((phase != null)?(" (phase: "+phase+")"):"")+" !"+appendMessage(consequence)); + return new UWSException(UWSException.NOT_ALLOWED, "Impossible to change the parameter \"" + parameter + "\" of the job " + jobId + ((phase != null) ? (" (phase: " + phase + ")") : "") + " !" + appendMessage(consequence)); else - return new UWSException(UWSException.NOT_ALLOWED, "Impossible to change the parameters of the job "+jobId+((phase != null)?(" (phase: "+phase+")"):"")+" !"+appendMessage(consequence)); + return new UWSException(UWSException.NOT_ALLOWED, "Impossible to change the parameters of the job " + jobId + ((phase != null) ? (" (phase: " + phase + ")") : "") + " !" + appendMessage(consequence)); + } + + public final static UWSException badFormat(final String jobId, final String paramName, final String paramValue, final String valueClass, final String expectedFormat){ + return badFormat(jobId, paramName, paramValue, valueClass, expectedFormat, null); } - public final static UWSException badFormat(final String jobId, final String paramName, final String paramValue, final String valueClass, final String expectedFormat){ return badFormat(jobId, paramName, paramValue, valueClass, expectedFormat, null); } public final static UWSException badFormat(final String jobId, final String paramName, final String paramValue, final String valueClass, final String expectedFormat, final String consequence){ - String strExpected = ((expectedFormat != null && !expectedFormat.trim().isEmpty())?(" Expected: "+expectedFormat):""); - String strClass = ((valueClass != null && !valueClass.trim().isEmpty())?(" {an instance of "+valueClass+"}"):""); + String strExpected = ((expectedFormat != null && !expectedFormat.trim().isEmpty()) ? (" Expected: " + expectedFormat) : ""); + String strClass = ((valueClass != null && !valueClass.trim().isEmpty()) ? (" {an instance of " + valueClass + "}") : ""); if (paramName != null && !paramName.trim().isEmpty()){ if (jobId != null && !jobId.trim().isEmpty()) - return new UWSException(UWSException.BAD_REQUEST, "Bad format for the parameter "+paramName.toUpperCase()+" of the job "+jobId+": \""+paramValue+"\""+strClass+"."+strExpected+appendMessage(consequence)); + return new UWSException(UWSException.BAD_REQUEST, "Bad format for the parameter " + paramName.toUpperCase() + " of the job " + jobId + ": \"" + paramValue + "\"" + strClass + "." + strExpected + appendMessage(consequence)); else - return new UWSException(UWSException.BAD_REQUEST, "Bad format for "+paramName+": \""+paramValue+"\""+strClass+"."+strExpected+appendMessage(consequence)); + return new UWSException(UWSException.BAD_REQUEST, "Bad format for " + paramName + ": \"" + paramValue + "\"" + strClass + "." + strExpected + appendMessage(consequence)); }else - return new UWSException(UWSException.BAD_REQUEST, "Bad format: \""+paramValue+"\""+strClass+"."+strExpected+appendMessage(consequence)); + return new UWSException(UWSException.BAD_REQUEST, "Bad format: \"" + paramValue + "\"" + strClass + "." + strExpected + appendMessage(consequence)); } } diff --git a/src/uws/UWSToolBox.java b/src/uws/UWSToolBox.java index 9e32680c7fabc8f3aaa792c5ea2fe79dea0b37e6..f6dc4f55373acd251c029d468050ac11427129d8 100644 --- a/src/uws/UWSToolBox.java +++ b/src/uws/UWSToolBox.java @@ -57,7 +57,9 @@ public class UWSToolBox { private static UWSLog defaultLogger = null; /** <b>THIS CLASS CAN'T BE INSTANTIATED !</b> */ - private UWSToolBox() { ; } + private UWSToolBox(){ + ; + } /** * <p>Lets building the absolute URL of any resource available in the root server, from a relative URL.</p> @@ -81,12 +83,12 @@ public class UWSToolBox { if (serverPath == null || req == null) return null; - try { + try{ if (serverPath.length() > 0 && serverPath.charAt(0) != '/') - serverPath = "/"+serverPath; + serverPath = "/" + serverPath; - return new URL(req.getRequestURL().substring(0, req.getRequestURL().lastIndexOf(req.getContextPath())+req.getContextPath().length())+serverPath); - } catch (MalformedURLException e) { + return new URL(req.getRequestURL().substring(0, req.getRequestURL().lastIndexOf(req.getContextPath()) + req.getContextPath().length()) + serverPath); + }catch(MalformedURLException e){ return null; } } @@ -119,7 +121,7 @@ public class UWSToolBox { * @return The corresponding map of string. */ @SuppressWarnings("unchecked") - public static final HashMap<String,String> getParamsMap(HttpServletRequest req) { + public static final HashMap<String,String> getParamsMap(HttpServletRequest req){ HashMap<String,String> params = new HashMap<String,String>(req.getParameterMap().size()); Enumeration<String> e = req.getParameterNames(); @@ -137,25 +139,27 @@ public class UWSToolBox { * @param parameters A Map of parameters. * @return The corresponding query part of an HTTP-GET URL (all keys have been set in upper case). */ - public final static String getQueryPart(Map<String, String> parameters){ + public final static String getQueryPart(Map<String,String> parameters){ if (parameters == null || parameters.isEmpty()) return ""; StringBuffer queryPart = new StringBuffer(); - for(Map.Entry<String,String> e:parameters.entrySet()){ + for(Map.Entry<String,String> e : parameters.entrySet()){ String key = e.getKey(); String val = e.getValue(); - if (key != null) key = key.trim().toUpperCase(); - if (val != null) val = val.trim(); + if (key != null) + key = key.trim().toUpperCase(); + if (val != null) + val = val.trim(); - if(key != null && !key.isEmpty() && val != null && !val.isEmpty()){ - queryPart.append(e.getKey()+"="+val); + if (key != null && !key.isEmpty() && val != null && !val.isEmpty()){ + queryPart.append(e.getKey() + "=" + val); queryPart.append("&"); } } - return queryPart.substring(0, queryPart.length()-1); + return queryPart.substring(0, queryPart.length() - 1); } /** @@ -164,11 +168,11 @@ public class UWSToolBox { * @param queryPart A query part of a HTTP-GET URL. * @return The corresponding map of parameters (all keys have been set in lower case). */ - public final static Map<String, String> getParameters(String queryPart){ + public final static Map<String,String> getParameters(String queryPart){ HashMap<String,String> parameters = new HashMap<String,String>(); if (queryPart != null){ - queryPart = queryPart.substring(queryPart.indexOf("?")+1).trim(); + queryPart = queryPart.substring(queryPart.indexOf("?") + 1).trim(); if (!queryPart.isEmpty()){ String[] keyValues = queryPart.split("&"); for(String item : keyValues){ @@ -208,7 +212,7 @@ public class UWSToolBox { public static final void clearDirectory(File directory){ if (directory != null && directory.exists() && directory.isDirectory() && directory.canWrite()){ File[] files = directory.listFiles(); - for(int i=0; i<files.length; i++) + for(int i = 0; i < files.length; i++) files[i].delete(); } } @@ -226,9 +230,9 @@ public class UWSToolBox { * * @throws IOException If there is an error while opening the output stream or while copying. */ - public static final void write(final InputStream input, final String mimeType, final long contentSize, final HttpServletResponse response) throws IOException { + public static final void write(final InputStream input, final String mimeType, final long contentSize, final HttpServletResponse response) throws IOException{ ServletOutputStream output = null; - try { + try{ // Set the HTTP content type: if (mimeType != null) response.setContentType(mimeType); @@ -241,7 +245,7 @@ public class UWSToolBox { output = response.getOutputStream(); byte[] buffer = new byte[1024]; int length; - while((length=input.read(buffer))>0) + while((length = input.read(buffer)) > 0) output.print(new String(buffer, 0, length)); }finally{ if (output != null) @@ -268,10 +272,10 @@ public class UWSToolBox { return false; PrintWriter pw = new PrintWriter(output); - pw.println("Date: "+(new Date()).toString()); - pw.println("Job: "+job.getJobId()); - pw.println("Type: "+error.getType()); - pw.println("Message: "+error.getMessage()); + pw.println("Date: " + (new Date()).toString()); + pw.println("Job: " + job.getJobId()); + pw.println("Type: " + error.getType()); + pw.println("Message: " + error.getMessage()); pw.println("Stack Trace:"); printStackTrace(ex, pw); pw.close(); @@ -287,12 +291,12 @@ public class UWSToolBox { * * @throws IOException If there is an error while printing the stack trace. */ - public static final void printStackTrace(final Throwable ex, final PrintWriter pw) throws IOException { - pw.println(ex.getClass().getName()+": "+ex.getMessage()); + public static final void printStackTrace(final Throwable ex, final PrintWriter pw) throws IOException{ + pw.println(ex.getClass().getName() + ": " + ex.getMessage()); StackTraceElement[] elements = ex.getStackTrace(); - for(int i=0; i<elements.length; i++) - pw.println("\tat "+elements[i].toString()); + for(int i = 0; i < elements.length; i++) + pw.println("\tat " + elements[i].toString()); if (ex.getCause() != null){ pw.print("Caused by: "); @@ -314,9 +318,9 @@ public class UWSToolBox { * @see #printURL(UWSUrl, java.io.OutputStream) */ public static final void printURL(UWSUrl url){ - try { + try{ printURL(url, System.out); - } catch (IOException e) { + }catch(IOException e){ e.printStackTrace(); } } @@ -329,7 +333,7 @@ public class UWSToolBox { * * @throws IOException If there is an error while writing in the given stream. */ - public static final void printURL(UWSUrl url, java.io.OutputStream output) throws IOException { + public static final void printURL(UWSUrl url, java.io.OutputStream output) throws IOException{ StringBuffer toPrint = new StringBuffer(); toPrint.append("***** UWS_URL (").append(url.getBaseURI()).append(") *****"); toPrint.append("\nRequest URL: ").append(url.getRequestURL()); @@ -351,10 +355,10 @@ public class UWSToolBox { /* MIME TYPE */ /* ********* */ /** List of file extensions whose the MIME type is known (see {@link #mimeTypes}). */ - protected static final String[] fileExts = new String[]{"", "vot", "json", "json", "csv", "tsv", "txt", "xml", "xml", "pdf", "ai", "eps", "ps", "html", "zip", "gzip", "gz", "tar", "gif", "jpeg", "jpg", "png", "bmp"}; + protected static final String[] fileExts = new String[]{"","vot","json","json","csv","tsv","txt","xml","xml","pdf","ai","eps","ps","html","zip","gzip","gz","tar","gif","jpeg","jpg","png","bmp"}; /** List of known MIME types (see {@link #fileExts}). */ - protected static final String[] mimeTypes = new String[]{"application/octet-stream", "application/x-votable+xml", "application/json", "text/json", "text/csv", "text/tab-separated-values", "text/plain", "application/xml", "text/xml", "application/pdf", "application/postscript", "application/postscript", "application/postscript", "text/html", "application/zip", "application/x-gzip", "application/x-tar", "image/gif", "image/jpeg", "image/jpeg", "image/png", "image/x-portable-bitmap"}; + protected static final String[] mimeTypes = new String[]{"application/octet-stream","application/x-votable+xml","application/json","text/json","text/csv","text/tab-separated-values","text/plain","application/xml","text/xml","application/pdf","application/postscript","application/postscript","application/postscript","text/html","application/zip","application/x-gzip","application/x-tar","image/gif","image/jpeg","image/jpeg","image/png","image/x-portable-bitmap"}; /** * Gets the MIME type corresponding to the given file extension. @@ -371,7 +375,7 @@ public class UWSToolBox { if (fileExtension.length() > 0 && fileExtension.charAt(0) == '.') fileExtension = fileExtension.substring(1).trim(); - for(int i=0; i<fileExts.length; i++) + for(int i = 0; i < fileExts.length; i++) if (fileExtension.equalsIgnoreCase(fileExts[i])) return mimeTypes[i]; @@ -391,7 +395,7 @@ public class UWSToolBox { mimeType = mimeType.trim(); - for(int i=0; i<mimeTypes.length; i++) + for(int i = 0; i < mimeTypes.length; i++) if (mimeType.equalsIgnoreCase(mimeTypes[i])) return fileExts[i]; diff --git a/src/uws/job/ErrorSummary.java b/src/uws/job/ErrorSummary.java index b42368e35cd6af849abbffaacf96ee375a825435..cc2c983434dea58939f652afdedf746f10634961 100644 --- a/src/uws/job/ErrorSummary.java +++ b/src/uws/job/ErrorSummary.java @@ -44,7 +44,6 @@ public class ErrorSummary extends SerializableUWSObject { /** <i>[Optional]</i> The URI/URL toward the file which contains a more detailed description of the error (i.e. an Exception stack trace). */ protected String details = null; - /* CONSTRUCTORS */ /** * <p>Builds an error summary from an Exception.</p> @@ -58,7 +57,7 @@ public class ErrorSummary extends SerializableUWSObject { * @see ErrorSummary#ErrorSummary(String, ErrorType, String) */ public ErrorSummary(Exception ex, ErrorType errorType, String detailedMsgURI){ - this(((ex==null)?null:ex.getMessage()), errorType, detailedMsgURI); + this(((ex == null) ? null : ex.getMessage()), errorType, detailedMsgURI); } /** @@ -82,9 +81,9 @@ public class ErrorSummary extends SerializableUWSObject { * @param detailedMsgURI <i>null</i> or the URI/URL at which a detailed error message is given (different from {jobs}/(job-id)/error). */ public ErrorSummary(String msg, ErrorType errorType, String detailedMsgURI){ - message = (msg==null)?"{No error message}":msg; - type = (errorType==null)?ErrorType.FATAL:errorType; - details = (detailedMsgURI == null || detailedMsgURI.trim().length() == 0)?null:detailedMsgURI.trim(); + message = (msg == null) ? "{No error message}" : msg; + type = (errorType == null) ? ErrorType.FATAL : errorType; + details = (detailedMsgURI == null || detailedMsgURI.trim().length() == 0) ? null : detailedMsgURI.trim(); } /* ******* */ @@ -95,7 +94,7 @@ public class ErrorSummary extends SerializableUWSObject { * * @return A short error message. */ - public final String getMessage() { + public final String getMessage(){ return message; } @@ -106,7 +105,7 @@ public class ErrorSummary extends SerializableUWSObject { * * @see ErrorType */ - public final ErrorType getType() { + public final ErrorType getType(){ return type; } @@ -116,7 +115,7 @@ public class ErrorSummary extends SerializableUWSObject { * * @return <i>true</i> if there are more details, <i>false</i> otherwise. */ - public final boolean hasDetail() { + public final boolean hasDetail(){ return details != null; } @@ -125,7 +124,7 @@ public class ErrorSummary extends SerializableUWSObject { * * @return The error details. */ - public final String getDetails() { + public final String getDetails(){ return details; } @@ -133,12 +132,12 @@ public class ErrorSummary extends SerializableUWSObject { /* INHERITED METHODS */ /* ***************** */ @Override - public String serialize(UWSSerializer serializer, JobOwner owner) throws UWSException { + public String serialize(UWSSerializer serializer, JobOwner owner) throws UWSException{ return serializer.getErrorSummary(this, true); } @Override public String toString(){ - return "ERROR_SUMMARY {type: "+type.name()+"; message: \""+message+"\"; details: "+(hasDetail()?details:"none")+"}"; + return "ERROR_SUMMARY {type: " + type.name() + "; message: \"" + message + "\"; details: " + (hasDetail() ? details : "none") + "}"; } } diff --git a/src/uws/job/ErrorType.java b/src/uws/job/ErrorType.java index a8cf06cae746c64d654f8c9d04728259ed8fc227..7ee038c277ed02bdf82e282df0138371698012ba 100644 --- a/src/uws/job/ErrorType.java +++ b/src/uws/job/ErrorType.java @@ -27,6 +27,6 @@ package uws.job; * @author Grégory Mantelet (CDS) * @version 09/2010 */ -public enum ErrorType { +public enum ErrorType{ FATAL, TRANSIENT } diff --git a/src/uws/job/ExecutionPhase.java b/src/uws/job/ExecutionPhase.java index 9cdf4c685e95278c9e1d3819bc09b2fa6fd3e277..d803f829c6d71c21cd2e0ea182721901f14198fc 100644 --- a/src/uws/job/ExecutionPhase.java +++ b/src/uws/job/ExecutionPhase.java @@ -59,11 +59,11 @@ package uws.job; * @author Grégory Mantelet (CDS) * @version 02/2011 */ -public enum ExecutionPhase { +public enum ExecutionPhase{ PENDING, QUEUED, EXECUTING, COMPLETED, ERROR, ABORTED, UNKNOWN, HELD, SUSPENDED; public static final String getStr(ExecutionPhase ph){ - return (ph==null)?ExecutionPhase.UNKNOWN.name():ph.name(); + return (ph == null) ? ExecutionPhase.UNKNOWN.name() : ph.name(); } public static final ExecutionPhase getPhase(String phStr){ @@ -75,4 +75,3 @@ public enum ExecutionPhase { } } - diff --git a/src/uws/job/JobList.java b/src/uws/job/JobList.java index 76926373a45524f8c4b47fd328ce8e31a87a28ac..9c10ee54fcea4eaa28a5e6b9ad1f3b2ae1c2f3a3 100644 --- a/src/uws/job/JobList.java +++ b/src/uws/job/JobList.java @@ -110,10 +110,10 @@ public class JobList extends SerializableUWSObject implements Iterable<UWSJob> { private final String name; /** <b>[Required]</b> List of jobs. */ - protected final Map<String, UWSJob> jobsList; + protected final Map<String,UWSJob> jobsList; /** <b>[Required]</b> List of jobs per owner. */ - protected final Map<JobOwner, Map<String, UWSJob>> ownerJobs; + protected final Map<JobOwner,Map<String,UWSJob>> ownerJobs; /** The destruction manager to use to take into account the destructionTime field of contained jobs. */ private DestructionManager destructionManager = null; @@ -136,7 +136,7 @@ public class JobList extends SerializableUWSObject implements Iterable<UWSJob> { * * @see #JobList(String, ExecutionManager) */ - public JobList(String jobListName) throws UWSException { + public JobList(String jobListName) throws UWSException{ this(jobListName, new DefaultExecutionManager(), new DefaultDestructionManager()); } @@ -148,7 +148,7 @@ public class JobList extends SerializableUWSObject implements Iterable<UWSJob> { * * @throws UWSException If the given name is <i>null</i> or empty, or if the given execution manager is <i>null</i>. */ - public JobList(String jobListName, ExecutionManager executionManager) throws UWSException { + public JobList(String jobListName, ExecutionManager executionManager) throws UWSException{ this(jobListName, executionManager, new DefaultDestructionManager()); } @@ -160,7 +160,7 @@ public class JobList extends SerializableUWSObject implements Iterable<UWSJob> { * * @throws UWSException If the given name is <i>null</i> or empty, or if the given destruction manager is <i>null</i>. */ - public JobList(String jobListName, DestructionManager destructionManager) throws UWSException { + public JobList(String jobListName, DestructionManager destructionManager) throws UWSException{ this(jobListName, new DefaultExecutionManager(), destructionManager); } @@ -173,7 +173,7 @@ public class JobList extends SerializableUWSObject implements Iterable<UWSJob> { * * @throws UWSException If the given name is <i>null</i> or empty, or if the given execution or destruction manager is <i>null</i>. */ - public JobList(String jobListName, ExecutionManager executionManager, DestructionManager destructionManager) throws UWSException { + public JobList(String jobListName, ExecutionManager executionManager, DestructionManager destructionManager) throws UWSException{ if (jobListName == null) throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, "Missing job list name ! => Impossible to build the job list."); else{ @@ -184,7 +184,7 @@ public class JobList extends SerializableUWSObject implements Iterable<UWSJob> { name = jobListName; jobsList = new LinkedHashMap<String,UWSJob>(); - ownerJobs = new LinkedHashMap<JobOwner, Map<String, UWSJob>>(); + ownerJobs = new LinkedHashMap<JobOwner,Map<String,UWSJob>>(); if (executionManager == null) throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, "Missing execution manager ! => Impossible to build the job list."); @@ -219,7 +219,7 @@ public class JobList extends SerializableUWSObject implements Iterable<UWSJob> { * * @throws IllegalStateException If this jobs list is already associated with a UWS (different from the given one) and contains some jobs. */ - public final void setUWS(UWS newUws) throws IllegalStateException { + public final void setUWS(UWS newUws) throws IllegalStateException{ if (newUws == null) return; else if (newUws.equals(uws)) @@ -227,7 +227,7 @@ public class JobList extends SerializableUWSObject implements Iterable<UWSJob> { else if (uws == null || getNbJobs() == 0) uws = newUws; else - throw new IllegalStateException("This jobs list (here: "+getName()+") is already associated with a UWS and contains some jobs (size="+getNbJobs()+"). A job list can not be part of several UWS instances and can not be moved into another UWS if not empty !"); + throw new IllegalStateException("This jobs list (here: " + getName() + ") is already associated with a UWS and contains some jobs (size=" + getNbJobs() + "). A job list can not be part of several UWS instances and can not be moved into another UWS if not empty !"); } /** @@ -302,7 +302,7 @@ public class JobList extends SerializableUWSObject implements Iterable<UWSJob> { * @see ExecutionManager#remove(UWSJob) * @see ExecutionManager#execute(UWSJob) */ - public synchronized final void setExecutionManager(final ExecutionManager manager) throws UWSException { + public synchronized final void setExecutionManager(final ExecutionManager manager) throws UWSException{ if (manager == null) return; @@ -325,7 +325,7 @@ public class JobList extends SerializableUWSObject implements Iterable<UWSJob> { * @see UWSService#getUrlInterpreter() * @see UWSUrl#listJobs(String) */ - public UWSUrl getUrl() { + public UWSUrl getUrl(){ if (uws == null || uws.getUrlInterpreter() == null) return null; else @@ -362,7 +362,7 @@ public class JobList extends SerializableUWSObject implements Iterable<UWSJob> { * * @throws UWSException If the given user is not allowed to read the content of this jobs list or to read the specified job. */ - public UWSJob getJob(String jobID, JobOwner user) throws UWSException { + public UWSJob getJob(String jobID, JobOwner user) throws UWSException{ if (user != null && !user.hasReadPermission(this)) throw UWSExceptionFactory.readPermissionDenied(user, true, getName()); @@ -399,7 +399,7 @@ public class JobList extends SerializableUWSObject implements Iterable<UWSJob> { * or a NullIterator if the specified owner/user has no job * or an iterator on all the jobs if <i>ownerId</i> is <i>null</i>. */ - public Iterator<UWSJob> getJobs(JobOwner user) { + public Iterator<UWSJob> getJobs(JobOwner user){ if (user == null) return iterator(); else{ @@ -407,10 +407,18 @@ public class JobList extends SerializableUWSObject implements Iterable<UWSJob> { return ownerJobs.get(user).values().iterator(); else return new Iterator<UWSJob>(){ - public boolean hasNext() { return false; } - public UWSJob next() { return null; } - public void remove() {;} - }; + public boolean hasNext(){ + return false; + } + + public UWSJob next(){ + return null; + } + + public void remove(){ + ; + } + }; } } @@ -419,7 +427,7 @@ public class JobList extends SerializableUWSObject implements Iterable<UWSJob> { * * @see java.lang.Iterable#iterator() */ - public final Iterator<UWSJob> iterator() { + public final Iterator<UWSJob> iterator(){ return jobsList.values().iterator(); } @@ -481,7 +489,7 @@ public class JobList extends SerializableUWSObject implements Iterable<UWSJob> { */ public final ArrayList<UWSJob> searchJobs(String runID){ ArrayList<UWSJob> foundJobs = new ArrayList<UWSJob>(); - runID = (runID != null)?runID.trim():runID; + runID = (runID != null) ? runID.trim() : runID; if (runID != null && !runID.isEmpty()){ for(UWSJob job : this) @@ -509,7 +517,7 @@ public class JobList extends SerializableUWSObject implements Iterable<UWSJob> { * @see DestructionManager#update(UWSJob) * @see UWSJob#applyPhaseParam(JobOwner) */ - public synchronized String addNewJob(final UWSJob j) throws UWSException { + public synchronized String addNewJob(final UWSJob j) throws UWSException{ if (j == null || jobsList.containsKey(j.getJobId())){ return null; }else{ @@ -528,7 +536,7 @@ public class JobList extends SerializableUWSObject implements Iterable<UWSJob> { if (owner != null){ // Index also this job in function of its owner: if (!ownerJobs.containsKey(owner)) - ownerJobs.put(owner, new LinkedHashMap<String, UWSJob>()); + ownerJobs.put(owner, new LinkedHashMap<String,UWSJob>()); ownerJobs.get(owner).put(j.getJobId(), j); } @@ -547,8 +555,8 @@ public class JobList extends SerializableUWSObject implements Iterable<UWSJob> { getLogger().jobCreated(j); return j.getJobId(); - }catch (IllegalStateException e){ - throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, e, "Impossible to add the job "+j.getJobId()+" into the jobs list "+getName()+" !"); + }catch(IllegalStateException e){ + throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, e, "Impossible to add the job " + j.getJobId() + " into the jobs list " + getName() + " !"); } } } @@ -578,7 +586,7 @@ public class JobList extends SerializableUWSObject implements Iterable<UWSJob> { */ protected UWSJob removeJob(final String jobId){ // Remove the specified job: - UWSJob removedJob = (jobId==null)?null:jobsList.remove(jobId); + UWSJob removedJob = (jobId == null) ? null : jobsList.remove(jobId); if (removedJob != null){ // Delete completely their association: @@ -649,7 +657,7 @@ public class JobList extends SerializableUWSObject implements Iterable<UWSJob> { * * @throws UWSException If the given user is not allowed to update the content of this jobs list or to destroy the specified job. */ - public boolean destroyJob(final String jobId, final JobOwner user) throws UWSException { + public boolean destroyJob(final String jobId, final JobOwner user) throws UWSException{ if (user != null){ if (!user.hasWritePermission(this)) throw UWSExceptionFactory.writePermissionDenied(user, true, getName()); @@ -692,7 +700,7 @@ public class JobList extends SerializableUWSObject implements Iterable<UWSJob> { * @see #clear() * @see #destroyJob(String) */ - public synchronized void clear(JobOwner owner) throws UWSException { + public synchronized void clear(JobOwner owner) throws UWSException{ if (owner == null) clear(); else if (!owner.hasWritePermission(this)) @@ -711,7 +719,7 @@ public class JobList extends SerializableUWSObject implements Iterable<UWSJob> { /* INHERITED METHODS */ /* ***************** */ @Override - public String serialize(UWSSerializer serializer, JobOwner user) throws UWSException { + public String serialize(UWSSerializer serializer, JobOwner user) throws UWSException{ if (user != null && !user.hasReadPermission(this)) throw UWSExceptionFactory.readPermissionDenied(user, true, getName()); @@ -720,8 +728,7 @@ public class JobList extends SerializableUWSObject implements Iterable<UWSJob> { @Override public String toString(){ - return "JOB_LIST {name: \""+getName()+"\"; nbJobs: "+jobsList.size()+"}"; + return "JOB_LIST {name: \"" + getName() + "\"; nbJobs: " + jobsList.size() + "}"; } } - diff --git a/src/uws/job/JobPhase.java b/src/uws/job/JobPhase.java index 26ac2c5892a45229f12a21d9bf98711d725f9c5e..cf0a270fb25dc19c1cd85013e6fbeea434fafc36 100644 --- a/src/uws/job/JobPhase.java +++ b/src/uws/job/JobPhase.java @@ -43,7 +43,6 @@ public class JobPhase implements Serializable { /** The job whose the current phase is represented by this class. */ protected final UWSJob job; - /** * Builds the phase manager of the given job. * @@ -51,7 +50,7 @@ public class JobPhase implements Serializable { * * @throws UWSException If the given job is <i>null</i>. */ - public JobPhase(UWSJob j) throws UWSException { + public JobPhase(UWSJob j) throws UWSException{ if (j == null) throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, "Missing job instance ! => impossible to build a JobPhase instance."); job = j; @@ -84,7 +83,7 @@ public class JobPhase implements Serializable { * * @see #setPhase(ExecutionPhase, boolean) */ - public final void setPhase(ExecutionPhase p) throws UWSException { + public final void setPhase(ExecutionPhase p) throws UWSException{ setPhase(p, false); } @@ -106,31 +105,40 @@ public class JobPhase implements Serializable { * @see #setSuspendedPhase(boolean) * @see #setUnknownPhase(boolean) */ - public void setPhase(ExecutionPhase p, boolean force) throws UWSException { + public void setPhase(ExecutionPhase p, boolean force) throws UWSException{ if (p == null) throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, "Incorrect phase ! => The phase of a job can not be set to NULL !"); // Check that the given phase follows the imposed phases order: switch(p){ - case PENDING: - setPendingPhase(force); break; - case QUEUED: - setQueuedPhase(force); break; - case EXECUTING: - setExecutingPhase(force); break; - case COMPLETED: - setCompletedPhase(force); break; - case ABORTED: - setAbortedPhase(force); break; - case ERROR: - setErrorPhase(force); break; - case HELD: - setHeldPhase(force); break; - case SUSPENDED: - setSuspendedPhase(force); break; - case UNKNOWN: - default: - setUnknownPhase(force); break; + case PENDING: + setPendingPhase(force); + break; + case QUEUED: + setQueuedPhase(force); + break; + case EXECUTING: + setExecutingPhase(force); + break; + case COMPLETED: + setCompletedPhase(force); + break; + case ABORTED: + setAbortedPhase(force); + break; + case ERROR: + setErrorPhase(force); + break; + case HELD: + setHeldPhase(force); + break; + case SUSPENDED: + setSuspendedPhase(force); + break; + case UNKNOWN: + default: + setUnknownPhase(force); + break; } } @@ -141,7 +149,7 @@ public class JobPhase implements Serializable { * * @throws UWSException If this phase transition is forbidden <i>(by default: IF force=false AND currentPhase != PENDING or UNKNOWN)</i>. */ - protected void setPendingPhase(boolean force) throws UWSException { + protected void setPendingPhase(boolean force) throws UWSException{ if (!force && phase != ExecutionPhase.PENDING && phase != ExecutionPhase.UNKNOWN) throw UWSExceptionFactory.incorrectPhaseTransition(job.getJobId(), phase, ExecutionPhase.PENDING); @@ -155,7 +163,7 @@ public class JobPhase implements Serializable { * * @throws UWSException If this phase transition is forbidden <i>(by default: IF force=false AND currentPhase != QUEUED or HELD or PENDING or UNKNOWN)</i>. */ - protected void setQueuedPhase(boolean force) throws UWSException { + protected void setQueuedPhase(boolean force) throws UWSException{ if (force) phase = ExecutionPhase.QUEUED; else{ @@ -173,10 +181,10 @@ public class JobPhase implements Serializable { * * @throws UWSException If this phase transition is forbidden <i>(by default: IF force=false AND currentPhase != EXECUTING or SUSPENDED or QUEUED or UNKNOWN)</i>. */ - protected void setExecutingPhase(boolean force) throws UWSException { + protected void setExecutingPhase(boolean force) throws UWSException{ if (force) phase = ExecutionPhase.EXECUTING; - else { + else{ if (phase != ExecutionPhase.EXECUTING && phase != ExecutionPhase.SUSPENDED && phase != ExecutionPhase.PENDING && phase != ExecutionPhase.QUEUED && phase != ExecutionPhase.UNKNOWN) throw UWSExceptionFactory.incorrectPhaseTransition(job.getJobId(), phase, ExecutionPhase.EXECUTING); @@ -191,10 +199,10 @@ public class JobPhase implements Serializable { * * @throws UWSException If this phase transition is forbidden <i>(by default: IF force=false AND currentPhase != COMPLETED or EXECUTING or UNKNOWN)</i>. */ - protected void setCompletedPhase(boolean force) throws UWSException { + protected void setCompletedPhase(boolean force) throws UWSException{ if (force) phase = ExecutionPhase.COMPLETED; - else { + else{ if (phase != ExecutionPhase.COMPLETED && phase != ExecutionPhase.EXECUTING && phase != ExecutionPhase.UNKNOWN) throw UWSExceptionFactory.incorrectPhaseTransition(job.getJobId(), phase, ExecutionPhase.COMPLETED); @@ -209,7 +217,7 @@ public class JobPhase implements Serializable { * * @throws UWSException If this phase transition is forbidden <i>(by default: IF force=false AND currentPhase = COMPLETED or ERROR)</i>. */ - protected void setAbortedPhase(boolean force) throws UWSException { + protected void setAbortedPhase(boolean force) throws UWSException{ if (force) phase = ExecutionPhase.ABORTED; else{ @@ -227,7 +235,7 @@ public class JobPhase implements Serializable { * * @throws UWSException If this phase transition is forbidden <i>(by default: IF force=false AND currentPhase = COMPLETED or ABORTED)</i>. */ - protected void setErrorPhase(boolean force) throws UWSException { + protected void setErrorPhase(boolean force) throws UWSException{ if (force) phase = ExecutionPhase.ERROR; else{ @@ -245,7 +253,7 @@ public class JobPhase implements Serializable { * * @throws UWSException If this phase transition is forbidden <i>(by default: IF force=false AND currentPhase != HELD or PENDING or UNKNOWN)</i>. */ - protected void setHeldPhase(boolean force) throws UWSException { + protected void setHeldPhase(boolean force) throws UWSException{ if (!force && phase != ExecutionPhase.HELD && phase != ExecutionPhase.PENDING && phase != ExecutionPhase.UNKNOWN) throw UWSExceptionFactory.incorrectPhaseTransition(job.getJobId(), phase, ExecutionPhase.HELD); phase = ExecutionPhase.HELD; @@ -258,7 +266,7 @@ public class JobPhase implements Serializable { * * @throws UWSException By default, never ! */ - protected void setSuspendedPhase(boolean force) throws UWSException { + protected void setSuspendedPhase(boolean force) throws UWSException{ phase = ExecutionPhase.SUSPENDED; } @@ -269,7 +277,7 @@ public class JobPhase implements Serializable { * * @throws UWSException By default, never ! */ - protected void setUnknownPhase(boolean force) throws UWSException { + protected void setUnknownPhase(boolean force) throws UWSException{ phase = ExecutionPhase.UNKNOWN; } @@ -308,7 +316,7 @@ public class JobPhase implements Serializable { } @Override - public String toString() { + public String toString(){ return ExecutionPhase.getStr(phase); } } diff --git a/src/uws/job/JobThread.java b/src/uws/job/JobThread.java index adb942ea44dd433201ec743f3f0d3f78f854b6c5..0b80bd60c1be6fc663e1dbcd5d394ab5c842a1e0 100644 --- a/src/uws/job/JobThread.java +++ b/src/uws/job/JobThread.java @@ -89,7 +89,7 @@ public abstract class JobThread extends Thread { * * @see #getDefaultTaskDescription(UWSJob) */ - public JobThread(UWSJob j) throws UWSException { + public JobThread(UWSJob j) throws UWSException{ this(j, getDefaultTaskDescription(j)); } @@ -102,7 +102,7 @@ public abstract class JobThread extends Thread { * * @throws UWSException If the given job or the given file manager is null. */ - public JobThread(UWSJob j, String task) throws UWSException { + public JobThread(UWSJob j, String task) throws UWSException{ super(tg, j.getJobId()); if (j == null) throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, "Missing job instance ! => impossible to build a JobThread instance."); @@ -119,12 +119,12 @@ public abstract class JobThread extends Thread { protected final static String getDefaultTaskDescription(final UWSJob job){ // Describe the task of this thread: String task = ""; - task = "Executing the job "+job.getJobId(); + task = "Executing the job " + job.getJobId(); if (job.getJobList() != null && job.getJobList().getName() != null && !job.getJobList().getName().trim().isEmpty()){ JobList jl = job.getJobList(); - task += " (JobList: "+job.getJobList().getName(); + task += " (JobList: " + job.getJobList().getName(); if (jl.getUWS() != null && jl.getUWS().getName() != null && !jl.getUWS().getName().trim().isEmpty()) - task += ", UWS: "+jl.getUWS().getName(); + task += ", UWS: " + jl.getUWS().getName(); task += ")"; } return task; @@ -171,7 +171,7 @@ public abstract class JobThread extends Thread { * * @throws UWSException If there is an error while changing the execution phase. */ - private final void complete() throws UWSException { + private final void complete() throws UWSException{ if (isInterrupted()) job.abort(); else{ @@ -191,7 +191,7 @@ public abstract class JobThread extends Thread { * * @see {@link UWSJob#error(ErrorSummary)} */ - public void setError(final ErrorSummary error) throws UWSException { + public void setError(final ErrorSummary error) throws UWSException{ job.error(error); } @@ -212,12 +212,12 @@ public abstract class JobThread extends Thread { * * {@link UWSToolBox#writeErrorFile(Exception, ErrorSummary, UWSJob, OutputStream)} */ - public void setError(final UWSException ue) throws UWSException { + public void setError(final UWSException ue) throws UWSException{ if (ue == null) return; try{ - ErrorSummary error = new ErrorSummary(ue, ue.getUWSErrorType(), job.getUrl()+"/"+UWSJob.PARAM_ERROR_SUMMARY+"/details"); + ErrorSummary error = new ErrorSummary(ue, ue.getUWSErrorType(), job.getUrl() + "/" + UWSJob.PARAM_ERROR_SUMMARY + "/details"); OutputStream output = getFileManager().getErrorOutput(error, job); UWSToolBox.writeErrorFile(ue, error, job, output); @@ -225,7 +225,7 @@ public abstract class JobThread extends Thread { setError(error); }catch(IOException ioe){ - job.getLogger().error("The stack trace of a UWSException (job ID: "+job.getJobId()+" ; error message: \""+ue.getMessage()+"\") had not been written !", ioe); + job.getLogger().error("The stack trace of a UWSException (job ID: " + job.getJobId() + " ; error message: \"" + ue.getMessage() + "\") had not been written !", ioe); setError(new ErrorSummary(ue.getMessage(), ue.getUWSErrorType())); } } @@ -246,7 +246,7 @@ public abstract class JobThread extends Thread { int resultCount = 0; do{ resultCount++; - resultName = Result.DEFAULT_RESULT_NAME+"_"+resultCount; + resultName = Result.DEFAULT_RESULT_NAME + "_" + resultCount; }while(job.getResult(resultName) != null); } @@ -276,7 +276,7 @@ public abstract class JobThread extends Thread { * * @see UWSJob#addResult(Result) */ - public void publishResult(final Result result) throws UWSException { + public void publishResult(final Result result) throws UWSException{ job.addResult(result); } @@ -292,7 +292,7 @@ public abstract class JobThread extends Thread { * @throws IOException If there is an error while creating the file or the output stream. * @throws UWSException If an error occurs in the {@link UWSFileManager#getResultOutput(Result, UWSJob)}. */ - public OutputStream getResultOutput(final Result resultToWrite) throws IOException, UWSException { + public OutputStream getResultOutput(final Result resultToWrite) throws IOException, UWSException{ return getFileManager().getResultOutput(resultToWrite, job); } @@ -307,7 +307,7 @@ public abstract class JobThread extends Thread { * * @see {@link UWSFileManager#getResultSize(Result, UWSJob)} */ - public long getResultSize(final Result result) throws IOException { + public long getResultSize(final Result result) throws IOException{ return getFileManager().getResultSize(result, job); } @@ -353,7 +353,7 @@ public abstract class JobThread extends Thread { * @see UWSToolBox#publishErrorSummary(UWSJob, String, ErrorType) */ @Override - public final void run() { + public final void run(){ if (!job.getPhaseManager().isExecuting()) return; else{ @@ -393,7 +393,7 @@ public abstract class JobThread extends Thread { else lastError = new UWSException(UWSException.INTERNAL_SERVER_ERROR, t, ErrorType.FATAL); - }finally { + }finally{ finished = true; // Publish the error if any has occurred: @@ -401,18 +401,18 @@ public abstract class JobThread extends Thread { // Log the error: job.getLogger().threadInterrupted(this, taskDescription, lastError); // Set the error into the job: - try { + try{ setError(lastError); - } catch (UWSException ue) { + }catch(UWSException ue){ try{ - job.getLogger().error("[JobThread] LEVEL 1 -> Problem in JobThread.setError(UWSException), while setting the execution error of the job "+job.getJobId(), ue); - setError(new ErrorSummary((lastError.getCause() != null)?lastError.getCause().getMessage():lastError.getMessage(), lastError.getUWSErrorType())); + job.getLogger().error("[JobThread] LEVEL 1 -> Problem in JobThread.setError(UWSException), while setting the execution error of the job " + job.getJobId(), ue); + setError(new ErrorSummary((lastError.getCause() != null) ? lastError.getCause().getMessage() : lastError.getMessage(), lastError.getUWSErrorType())); }catch(UWSException ue2){ - job.getLogger().error("[JobThread] LEVEL 2 -> Problem in JobThread.setError(ErrorSummary), while setting the execution error of the job "+job.getJobId(), ue2); - try { + job.getLogger().error("[JobThread] LEVEL 2 -> Problem in JobThread.setError(ErrorSummary), while setting the execution error of the job " + job.getJobId(), ue2); + try{ setError(new ErrorSummary(lastError.getMessage(), ErrorType.FATAL)); - } catch (UWSException ue3){ - job.getLogger().error("[JobThread] LEVEL 3 -> Problem in JobThread.setError(ErrorSummary), while setting the execution error of the job "+job.getJobId(), ue3); + }catch(UWSException ue3){ + job.getLogger().error("[JobThread] LEVEL 3 -> Problem in JobThread.setError(ErrorSummary), while setting the execution error of the job " + job.getJobId(), ue3); } } } diff --git a/src/uws/job/Result.java b/src/uws/job/Result.java index e23ef83464691190aed5b173443cb311636515c5..1361bac8fb86e5b5d91f8d0c9d899a9c14bb0dae 100644 --- a/src/uws/job/Result.java +++ b/src/uws/job/Result.java @@ -102,7 +102,7 @@ public class Result extends SerializableUWSObject { if (name != null) id = name; redirection = isRedirectionUrl(resultUrl, id, job); - href = redirection ? resultUrl :getDefaultUrl(name, job); + href = redirection ? resultUrl : getDefaultUrl(name, job); } /** @@ -149,7 +149,7 @@ public class Result extends SerializableUWSObject { if (url == null) return null; else{ - url.setAttributes(new String[]{UWSJob.PARAM_RESULTS, id}); + url.setAttributes(new String[]{UWSJob.PARAM_RESULTS,id}); return url.toString(); } } @@ -185,7 +185,7 @@ public class Result extends SerializableUWSObject { * * @return The result id or name. */ - public final String getId() { + public final String getId(){ return id; } @@ -194,7 +194,7 @@ public class Result extends SerializableUWSObject { * * @return The result file URL. */ - public final String getHref() { + public final String getHref(){ return href; } @@ -213,7 +213,7 @@ public class Result extends SerializableUWSObject { * * @return The result type. */ - public final String getType() { + public final String getType(){ return type; } @@ -222,7 +222,7 @@ public class Result extends SerializableUWSObject { * * @return The MIME Type. */ - public final String getMimeType() { + public final String getMimeType(){ return mimeType; } @@ -231,7 +231,7 @@ public class Result extends SerializableUWSObject { * * @param mimeType The MIME type to set. */ - public final void setMimeType(String mimeType) { + public final void setMimeType(String mimeType){ this.mimeType = mimeType; } @@ -240,7 +240,7 @@ public class Result extends SerializableUWSObject { * * @return Result file size (in bytes). */ - public final long getSize() { + public final long getSize(){ return size; } @@ -249,7 +249,7 @@ public class Result extends SerializableUWSObject { * * @return size Result file size (in bytes). */ - public final void setSize(long size) { + public final void setSize(long size){ this.size = size; } @@ -257,12 +257,12 @@ public class Result extends SerializableUWSObject { /* INHERITED METHODS */ /* ***************** */ @Override - public String serialize(UWSSerializer serializer, JobOwner owner) throws UWSException { + public String serialize(UWSSerializer serializer, JobOwner owner) throws UWSException{ return serializer.getResult(this, true); } @Override public String toString(){ - return "RESULT {id: "+id+"; type: \""+((type==null)?"?":type)+"\"; href: "+((href==null)?"none":href)+"; mimeType: "+((mimeType==null)?"none":mimeType)+"}"; + return "RESULT {id: " + id + "; type: \"" + ((type == null) ? "?" : type) + "\"; href: " + ((href == null) ? "none" : href) + "; mimeType: " + ((mimeType == null) ? "none" : mimeType) + "}"; } } diff --git a/src/uws/job/SerializableUWSObject.java b/src/uws/job/SerializableUWSObject.java index a3e1c4ec3b71abc580b7ab040ee19e0452f9c93c..3fc7c493be3a0ad5783089f27232821b16401a29 100644 --- a/src/uws/job/SerializableUWSObject.java +++ b/src/uws/job/SerializableUWSObject.java @@ -53,7 +53,7 @@ public abstract class SerializableUWSObject implements Serializable { * * @see #serialize(UWSSerializer, String) */ - public String serialize(UWSSerializer serializer) throws UWSException { + public String serialize(UWSSerializer serializer) throws UWSException{ return serialize(serializer, null); } @@ -80,7 +80,7 @@ public abstract class SerializableUWSObject implements Serializable { * * @see #serialize(ServletOutputStream, UWSSerializer, String) */ - public void serialize(ServletOutputStream output, UWSSerializer serializer) throws UWSException { + public void serialize(ServletOutputStream output, UWSSerializer serializer) throws UWSException{ serialize(output, serializer, null); } @@ -98,9 +98,9 @@ public abstract class SerializableUWSObject implements Serializable { * * @see #serialize(UWSSerializer, String) */ - public void serialize(ServletOutputStream output, UWSSerializer serializer, JobOwner owner) throws UWSException { + public void serialize(ServletOutputStream output, UWSSerializer serializer, JobOwner owner) throws UWSException{ if (output == null) - throw UWSExceptionFactory.missingOutputStream("impossible to serialize {"+toString()+"}."); + throw UWSExceptionFactory.missingOutputStream("impossible to serialize {" + toString() + "}."); try{ String serialization = serialize(serializer, owner); @@ -108,9 +108,9 @@ public abstract class SerializableUWSObject implements Serializable { output.print(serialization); output.flush(); }else - throw UWSExceptionFactory.incorrectSerialization("NULL", "{"+toString()+"}"); + throw UWSExceptionFactory.incorrectSerialization("NULL", "{" + toString() + "}"); }catch(IOException ex){ - throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, ex, "IOException => impossible to serialize {"+toString()+"} !"); + throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, ex, "IOException => impossible to serialize {" + toString() + "} !"); } } } diff --git a/src/uws/job/UWSJob.java b/src/uws/job/UWSJob.java index cf2a4b2f9cf6041aa9e7db6de15bf2519ac2f732..babceb8f3f62bbdad258e920d4d01dd55ca89f0d 100644 --- a/src/uws/job/UWSJob.java +++ b/src/uws/job/UWSJob.java @@ -277,7 +277,7 @@ public class UWSJob extends SerializableUWSObject { protected Map<String, Object> additionalParameters;*/ /** This is a list of all results of this job. */ - protected Map<String, Result> results; + protected Map<String,Result> results; /** List of all input parameters (UWS standard and non-standard parameters). */ protected final UWSParameters inputParams; @@ -309,7 +309,7 @@ public class UWSJob extends SerializableUWSObject { * * @see UWSJob#AbstractJob(String, Map) */ - public UWSJob(final UWSParameters params) throws UWSException { + public UWSJob(final UWSParameters params) throws UWSException{ this(null, params); } @@ -327,13 +327,13 @@ public class UWSJob extends SerializableUWSObject { * @see #loadDefaultParams(Map) * @see #loadAdditionalParams() */ - public UWSJob(JobOwner owner, final UWSParameters params) throws UWSException { + public UWSJob(JobOwner owner, final UWSParameters params) throws UWSException{ this.owner = owner; phase = new JobPhase(this); //additionalParameters = new HashMap<String,Object>(); - results = new HashMap<String, Result>(); + results = new HashMap<String,Result>(); /*Map<String,Object> others = loadDefaultParams(lstParam); if (others != null){ @@ -368,7 +368,7 @@ public class UWSJob extends SerializableUWSObject { * * @throws UWSException If the given ID is <i>null</i> or if another error occurs while building this job. */ - public UWSJob(final String jobID, final JobOwner owner, final UWSParameters params, final long quote, final long startTime, final long endTime, final List<Result> results, final ErrorSummary error) throws UWSException { + public UWSJob(final String jobID, final JobOwner owner, final UWSParameters params, final long quote, final long startTime, final long endTime, final List<Result> results, final ErrorSummary error) throws UWSException{ if (jobID == null) throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, "Missing job ID => impossible to build a Job without a valid ID !"); @@ -384,7 +384,7 @@ public class UWSJob extends SerializableUWSObject { if (endTime > 0) this.endTime = new Date(endTime); - this.results = new HashMap<String, Result>(); + this.results = new HashMap<String,Result>(); if (results != null){ for(Result r : results){ if (r != null) @@ -432,11 +432,11 @@ public class UWSJob extends SerializableUWSObject { * * @return A unique job identifier. */ - protected String generateJobId() throws UWSException { - String generatedId = System.currentTimeMillis()+"A"; + protected String generateJobId() throws UWSException{ + String generatedId = System.currentTimeMillis() + "A"; if (lastId != null){ while(lastId.equals(generatedId)) - generatedId = generatedId.substring(0, generatedId.length()-1)+(char)(generatedId.charAt(generatedId.length()-1)+1); + generatedId = generatedId.substring(0, generatedId.length() - 1) + (char)(generatedId.charAt(generatedId.length() - 1) + 1); } lastId = generatedId; return generatedId; @@ -638,7 +638,7 @@ public class UWSJob extends SerializableUWSObject { * @see #start() * @see #abort() */ - public void applyPhaseParam(final JobOwner user) throws UWSException { + public void applyPhaseParam(final JobOwner user) throws UWSException{ synchronized(inputParams){ if (inputParams.hasInputPhase()){ String inputPhase = inputParams.getInputPhase(); @@ -719,7 +719,7 @@ public class UWSJob extends SerializableUWSObject { * * @see JobPhase#getPhase() */ - public final ExecutionPhase getPhase() { + public final ExecutionPhase getPhase(){ return phase.getPhase(); } @@ -739,7 +739,7 @@ public class UWSJob extends SerializableUWSObject { * * @see #setPhase(ExecutionPhase, boolean) */ - public final void setPhase(ExecutionPhase p) throws UWSException { + public final void setPhase(ExecutionPhase p) throws UWSException{ setPhase(p, false); } @@ -763,7 +763,7 @@ public class UWSJob extends SerializableUWSObject { * @see ExecutionManager#remove(UWSJob) * @see #notifyObservers(ExecutionPhase) */ - public final void setPhase(ExecutionPhase p, boolean force) throws UWSException { + public final void setPhase(ExecutionPhase p, boolean force) throws UWSException{ synchronized(phase){ ExecutionPhase oldPhase = phase.getPhase(); phase.setPhase(p, force); @@ -808,7 +808,7 @@ public class UWSJob extends SerializableUWSObject { * * @return The start time of the execution of this job. */ - public final Date getStartTime() { + public final Date getStartTime(){ return startTime; } @@ -826,7 +826,7 @@ public class UWSJob extends SerializableUWSObject { * * @return The end time of the execution of this job. */ - public final Date getEndTime() { + public final Date getEndTime(){ return endTime; } @@ -839,8 +839,7 @@ public class UWSJob extends SerializableUWSObject { endTime = newDateTime; // Save the owner jobs list: - if (phase.isFinished() && owner != null - && getJobList() != null && getJobList().getUWS() != null && getJobList().getUWS().getBackupManager() != null) + if (phase.isFinished() && owner != null && getJobList() != null && getJobList().getUWS() != null && getJobList().getUWS().getBackupManager() != null) getJobList().getUWS().getBackupManager().saveOwner(owner); // Log the end of this job: @@ -854,7 +853,7 @@ public class UWSJob extends SerializableUWSObject { * * @see UWSParameters#getExecutionDuration() */ - public final long getExecutionDuration() { + public final long getExecutionDuration(){ return inputParams.getExecutionDuration(); } @@ -867,11 +866,13 @@ public class UWSJob extends SerializableUWSObject { * * @see UWSParameters#set(String, Object) */ - public final void setExecutionDuration(long executionDuration) { + public final void setExecutionDuration(long executionDuration){ if (phase.isJobUpdatable()){ try{ inputParams.set(PARAM_EXECUTION_DURATION, executionDuration); - }catch(UWSException ue){ ; } + }catch(UWSException ue){ + ; + } } } @@ -882,7 +883,7 @@ public class UWSJob extends SerializableUWSObject { * * @see UWSParameters#getDestructionTime() */ - public final Date getDestructionTime() { + public final Date getDestructionTime(){ return inputParams.getDestructionTime(); } @@ -897,13 +898,15 @@ public class UWSJob extends SerializableUWSObject { * @see JobList#updateDestruction(UWSJob) * @see UWSParameters#set(String, Object) */ - public final void setDestructionTime(Date destructionTime) { + public final void setDestructionTime(Date destructionTime){ if (phase.isJobUpdatable()){ try{ inputParams.set(PARAM_DESTRUCTION_TIME, destructionTime); if (myJobList != null) myJobList.updateDestruction(this); - }catch(UWSException ue){ ; } + }catch(UWSException ue){ + ; + } } } @@ -912,7 +915,7 @@ public class UWSJob extends SerializableUWSObject { * * @return A summary of the error. */ - public final ErrorSummary getErrorSummary() { + public final ErrorSummary getErrorSummary(){ return errorSummary; } @@ -928,7 +931,7 @@ public class UWSJob extends SerializableUWSObject { * * @see #isFinished() */ - public final void setErrorSummary(ErrorSummary errorSummary) throws UWSException { + public final void setErrorSummary(ErrorSummary errorSummary) throws UWSException{ if (!isFinished()) this.errorSummary = errorSummary; else @@ -940,7 +943,7 @@ public class UWSJob extends SerializableUWSObject { * * @return The job ID (unique). */ - public final String getJobId() { + public final String getJobId(){ return jobId; } @@ -954,7 +957,7 @@ public class UWSJob extends SerializableUWSObject { * * @see UWSParameters#getRunId() */ - public final String getRunId() { + public final String getRunId(){ return inputParams.getRunId(); } @@ -971,7 +974,9 @@ public class UWSJob extends SerializableUWSObject { if (!phase.isFinished()){ try{ inputParams.set(PARAM_RUN_ID, name); - }catch(UWSException ue){ ; } + }catch(UWSException ue){ + ; + } } } @@ -980,7 +985,7 @@ public class UWSJob extends SerializableUWSObject { * * @return The owner. */ - public final JobOwner getOwner() { + public final JobOwner getOwner(){ return owner; } @@ -989,7 +994,7 @@ public class UWSJob extends SerializableUWSObject { * * @return The estimated duration of the job execution (in seconds). */ - public final long getQuote() { + public final long getQuote(){ return quote; } @@ -1075,7 +1080,7 @@ public class UWSJob extends SerializableUWSObject { * * @see #addOrUpdateParameters(Map) */ - public boolean addOrUpdateParameters(UWSParameters params) throws UWSException { + public boolean addOrUpdateParameters(UWSParameters params) throws UWSException{ return addOrUpdateParameters(params, null); } @@ -1100,7 +1105,7 @@ public class UWSJob extends SerializableUWSObject { * @see #loadAdditionalParams() * @see #applyPhaseParam() */ - public boolean addOrUpdateParameters(UWSParameters params, final JobOwner user) throws UWSException { + public boolean addOrUpdateParameters(UWSParameters params, final JobOwner user) throws UWSException{ // Forbids the update if the user has not the required permission: if (user != null && !user.equals(owner) && !user.hasWritePermission(this)) throw UWSExceptionFactory.writePermissionDenied(user, false, getJobId()); @@ -1147,7 +1152,7 @@ public class UWSJob extends SerializableUWSObject { * * @return An iterator on the results list. */ - public final Iterator<Result> getResults() { + public final Iterator<Result> getResults(){ return results.values().iterator(); } @@ -1184,7 +1189,7 @@ public class UWSJob extends SerializableUWSObject { * * @see #isFinished() */ - public boolean addResult(Result res) throws UWSException { + public boolean addResult(Result res) throws UWSException{ if (res == null) return false; else if (isFinished()) @@ -1233,7 +1238,7 @@ public class UWSJob extends SerializableUWSObject { * @see JobList#removeJob(String) * @see JobList#getJob(String) */ - protected final void setJobList(final JobList jobList) throws IllegalStateException { + protected final void setJobList(final JobList jobList) throws IllegalStateException{ if (jobList == null) return; else if (myJobList != null && jobList.equals(myJobList)) @@ -1243,7 +1248,7 @@ public class UWSJob extends SerializableUWSObject { myJobList.removeJob(jobId); myJobList = jobList; }else - throw new IllegalStateException("Impossible to move a job (here: "+jobId+") from a jobs list (here: "+((myJobList==null)?"null":myJobList.getName())+") to another (here: "+((jobList==null)?"null":jobList.getName())+") if the job is not PENDING !"); + throw new IllegalStateException("Impossible to move a job (here: " + jobId + ") from a jobs list (here: " + ((myJobList == null) ? "null" : myJobList.getName()) + ") to another (here: " + ((jobList == null) ? "null" : jobList.getName()) + ") if the job is not PENDING !"); } /** @@ -1289,8 +1294,8 @@ public class UWSJob extends SerializableUWSObject { * * @throws UWSException */ - public final void start() throws UWSException { - start( getJobList() != null ); + public final void start() throws UWSException{ + start(getJobList() != null); } /** @@ -1309,7 +1314,7 @@ public class UWSJob extends SerializableUWSObject { * @see #isFinished() * @see #startTime */ - public void start(boolean useManager) throws UWSException { + public void start(boolean useManager) throws UWSException{ // This job must know its jobs list and this jobs list must know its UWS: if (myJobList == null || myJobList.getUWS() == null) throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, "A UWSJob can not start if it is not part of a job list or if its job list is not part of a UWS."); @@ -1344,20 +1349,21 @@ public class UWSJob extends SerializableUWSObject { protected final class JobTimeOut extends Thread { public JobTimeOut(){ - super(JobThread.tg, "TimeOut_"+jobId); + super(JobThread.tg, "TimeOut_" + jobId); } + @Override public void run(){ long maxDuration = getExecutionDuration(); if (thread != null && thread.isAlive() && maxDuration != UNLIMITED_DURATION && maxDuration > 0){ try{ - thread.join(maxDuration*1000); + thread.join(maxDuration * 1000); if (!isFinished()) UWSJob.this.abort(); }catch(InterruptedException ie){ - getLogger().error("Unexpected InterruptedException while waiting the end of the execution of the job \""+jobId+"\" (thread ID: "+thread.getId()+") !", ie); - }catch (UWSException ue){ - getLogger().error("Unexpected UWSException while waiting the end of the execution of the job \""+jobId+"\" (thread ID: "+thread.getId()+") !", ue); + getLogger().error("Unexpected InterruptedException while waiting the end of the execution of the job \"" + jobId + "\" (thread ID: " + thread.getId() + ") !", ie); + }catch(UWSException ue){ + getLogger().error("Unexpected UWSException while waiting the end of the execution of the job \"" + jobId + "\" (thread ID: " + thread.getId() + ") !", ue); } } } @@ -1404,7 +1410,7 @@ public class UWSJob extends SerializableUWSObject { * @see #setPhase(ExecutionPhase) * @see #setEndTime(Date) */ - public void abort() throws UWSException { + public void abort() throws UWSException{ // Interrupt the corresponding thread: stop(); @@ -1438,7 +1444,7 @@ public class UWSJob extends SerializableUWSObject { * @see #setPhase(ExecutionPhase) * @see #setEndTime(Date) */ - public void error(ErrorSummary error) throws UWSException { + public void error(ErrorSummary error) throws UWSException{ // Interrupt the corresponding thread: stop(); @@ -1476,7 +1482,7 @@ public class UWSJob extends SerializableUWSObject { try{ thread.join(waitForStop); }catch(InterruptedException ie){ - getLogger().error("Unexpected InterruptedException while waiting the end of the execution of the job \""+jobId+"\" (thread ID: "+thread.getId()+") !", ie); + getLogger().error("Unexpected InterruptedException while waiting the end of the execution of the job \"" + jobId + "\" (thread ID: " + thread.getId() + ") !", ie); } } } @@ -1501,10 +1507,10 @@ public class UWSJob extends SerializableUWSObject { public void clearResources(){ // If still running, abort/stop the job: if (isRunning()){ - try { + try{ abort(); - } catch (UWSException e) { - getLogger().error("Impossible to abort the job"+jobId+" => trying to stop it...", e); + }catch(UWSException e){ + getLogger().error("Impossible to abort the job" + jobId + " => trying to stop it...", e); stop(); } } @@ -1514,7 +1520,7 @@ public class UWSJob extends SerializableUWSObject { if (getJobList() != null) getJobList().getExecutionManager().remove(this); }catch(UWSException ue){ - getLogger().error("Impossible to remove the job "+jobId+" from its execution manager !", ue); + getLogger().error("Impossible to remove the job " + jobId + " from its execution manager !", ue); } thread = null; @@ -1524,7 +1530,7 @@ public class UWSJob extends SerializableUWSObject { try{ getFileManager().deleteResult(r, this); }catch(IOException ioe){ - getLogger().error("Impossible to delete the file associated with the result '"+r.getId()+"' of the job "+jobId+" !", ioe); + getLogger().error("Impossible to delete the file associated with the result '" + r.getId() + "' of the job " + jobId + " !", ioe); } } @@ -1533,7 +1539,7 @@ public class UWSJob extends SerializableUWSObject { try{ getFileManager().deleteError(errorSummary, this); }catch(IOException ioe){ - getLogger().error("Impossible to delete the file associated with the error '"+errorSummary.message+"' of the job "+jobId+" !", ioe); + getLogger().error("Impossible to delete the file associated with the error '" + errorSummary.message + "' of the job " + jobId + " !", ioe); } } } @@ -1598,18 +1604,18 @@ public class UWSJob extends SerializableUWSObject { * @param oldPhase The former phase of this job. * @throws UWSException If at least one observer can not have been updated. */ - public final void notifyObservers(ExecutionPhase oldPhase) { - int i=0; + public final void notifyObservers(ExecutionPhase oldPhase){ + int i = 0; JobObserver observer = null; String errors = null; - while(i<observers.size()){ + while(i < observers.size()){ // Gets the observer: - if (i==0 && observer == null) + if (i == 0 && observer == null) observer = observers.get(i); else if (observer.equals(observers.get(i))){ i++; - if (i<observers.size()) + if (i < observers.size()) observer = observers.get(i); else return; @@ -1618,13 +1624,15 @@ public class UWSJob extends SerializableUWSObject { try{ observer.update(this, oldPhase, getPhase()); }catch(UWSException ex){ - if (errors == null) errors = "\t* "+ex.getMessage(); - else errors += "\n\t* "+ex.getMessage(); + if (errors == null) + errors = "\t* " + ex.getMessage(); + else + errors += "\n\t* " + ex.getMessage(); } } if (errors != null) - getLogger().error("Some observers of \""+jobId+"\" can not have been updated:\n"+errors); + getLogger().error("Some observers of \"" + jobId + "\" can not have been updated:\n" + errors); } /* **************** */ @@ -1640,14 +1648,14 @@ public class UWSJob extends SerializableUWSObject { * @return The error which interrupts the thread or <i>null</i> if there was no error or if the job is still running. */ public final UWSException getWorkError(){ - return (thread==null && !thread.isAlive())?null:thread.getError(); + return (thread == null && !thread.isAlive()) ? null : thread.getError(); } /* ************* */ /* SERIALIZATION */ /* ************* */ @Override - public String serialize(UWSSerializer serializer, JobOwner user) throws UWSException { + public String serialize(UWSSerializer serializer, JobOwner user) throws UWSException{ if (user != null && !user.equals(getOwner()) && !user.hasReadPermission(this)) throw UWSExceptionFactory.readPermissionDenied(user, false, getJobId()); @@ -1666,7 +1674,7 @@ public class UWSJob extends SerializableUWSObject { * * @see UWSSerializer#getJob(UWSJob, String[], boolean) */ - public String serialize(String[] attributes, UWSSerializer serializer) throws UWSException { + public String serialize(String[] attributes, UWSSerializer serializer) throws UWSException{ return serializer.getJob(this, attributes, true); } @@ -1681,15 +1689,15 @@ public class UWSJob extends SerializableUWSObject { * * @see #serialize(String[], UWSSerializer) */ - public void serialize(ServletOutputStream output, String[] attributes, UWSSerializer serializer) throws UWSException { + public void serialize(ServletOutputStream output, String[] attributes, UWSSerializer serializer) throws UWSException{ String errorMsgPart = null; - if (attributes==null || attributes.length <= 0) - errorMsgPart = "the job "+toString(); + if (attributes == null || attributes.length <= 0) + errorMsgPart = "the job " + toString(); else - errorMsgPart = "the given attribute \""+errorMsgPart+"\" of {"+toString()+"}"; + errorMsgPart = "the given attribute \"" + errorMsgPart + "\" of {" + toString() + "}"; if (output == null) - throw UWSExceptionFactory.missingOutputStream("impossible to serialize "+errorMsgPart+"."); + throw UWSExceptionFactory.missingOutputStream("impossible to serialize " + errorMsgPart + "."); try{ String serialization = serialize(attributes, serializer); @@ -1700,17 +1708,17 @@ public class UWSJob extends SerializableUWSObject { output.flush(); } }catch(IOException ex){ - throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, ex, "IOException => impossible to serialize "+errorMsgPart+"."); + throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, ex, "IOException => impossible to serialize " + errorMsgPart + "."); } } @Override public String toString(){ - return "JOB {jobId: "+jobId+"; phase: "+phase+"; runId: "+getRunId()+"; ownerId: "+owner+"; executionDuration: "+getExecutionDuration()+"; destructionTime: "+getDestructionTime()+"; quote: "+quote+"; NbResults: "+results.size()+"; "+((errorSummary!=null)?errorSummary.toString():"No error")+" }"; + return "JOB {jobId: " + jobId + "; phase: " + phase + "; runId: " + getRunId() + "; ownerId: " + owner + "; executionDuration: " + getExecutionDuration() + "; destructionTime: " + getDestructionTime() + "; quote: " + quote + "; NbResults: " + results.size() + "; " + ((errorSummary != null) ? errorSummary.toString() : "No error") + " }"; } @Override - public int hashCode() { + public int hashCode(){ return jobId.hashCode(); } @@ -1722,7 +1730,7 @@ public class UWSJob extends SerializableUWSObject { * @see java.lang.Object#equals(java.lang.Object) */ @Override - public boolean equals(Object anotherJob) { + public boolean equals(Object anotherJob){ if (anotherJob instanceof UWSJob) return jobId.equals(((UWSJob)anotherJob).jobId); else diff --git a/src/uws/job/manager/AbstractQueuedExecutionManager.java b/src/uws/job/manager/AbstractQueuedExecutionManager.java index 0d8f76395d75a6ad4358bc2e03fb97f8f6f5e23d..a2e1d4082504debb196779d716f43293605f2b88 100644 --- a/src/uws/job/manager/AbstractQueuedExecutionManager.java +++ b/src/uws/job/manager/AbstractQueuedExecutionManager.java @@ -50,14 +50,13 @@ public abstract class AbstractQueuedExecutionManager implements ExecutionManager private static final long serialVersionUID = 1L; /** List of running jobs. */ - protected Map<String, UWSJob> runningJobs; + protected Map<String,UWSJob> runningJobs; /** List of queued jobs. */ protected Vector<UWSJob> queuedJobs; protected final UWSLog logger; - /* ************ */ /* CONSTRUCTORS */ /* ************ */ @@ -65,9 +64,9 @@ public abstract class AbstractQueuedExecutionManager implements ExecutionManager * Builds an execution manager without queue. */ protected AbstractQueuedExecutionManager(final UWSLog logger){ - runningJobs = new LinkedHashMap<String, UWSJob>(); + runningJobs = new LinkedHashMap<String,UWSJob>(); queuedJobs = new Vector<UWSJob>(0, 10); - this.logger = (logger == null)?UWSToolBox.getDefaultLogger():logger; + this.logger = (logger == null) ? UWSToolBox.getDefaultLogger() : logger; } /* ***************** */ @@ -124,7 +123,7 @@ public abstract class AbstractQueuedExecutionManager implements ExecutionManager * * @see uws.job.manager.ExecutionManager#refresh() */ - public synchronized final void refresh() throws UWSException { + public synchronized final void refresh() throws UWSException{ // Return immediately if no queue: if (!hasQueue()) return; @@ -132,11 +131,11 @@ public abstract class AbstractQueuedExecutionManager implements ExecutionManager String allMsg = null; // the concatenation of all errors which may occur // Start the first job of the queue while it can be executed: - while (!queuedJobs.isEmpty() && isReadyForExecution(queuedJobs.firstElement())){ + while(!queuedJobs.isEmpty() && isReadyForExecution(queuedJobs.firstElement())){ try{ - startJob( queuedJobs.remove(0) ); + startJob(queuedJobs.remove(0)); }catch(UWSException ue){ - allMsg = ((allMsg == null)?"ERRORS THAT OCCURED WHILE REFRESHING THE EXECUTION MANAGER:":allMsg)+"\n\t- "+ue.getMessage(); + allMsg = ((allMsg == null) ? "ERRORS THAT OCCURED WHILE REFRESHING THE EXECUTION MANAGER:" : allMsg) + "\n\t- " + ue.getMessage(); } } @@ -155,7 +154,7 @@ public abstract class AbstractQueuedExecutionManager implements ExecutionManager * * @see UWSJob#start(boolean) */ - protected void startJob(final UWSJob jobToStartNow) throws UWSException { + protected void startJob(final UWSJob jobToStartNow) throws UWSException{ if (jobToStartNow != null){ jobToStartNow.start(false); queuedJobs.remove(jobToStartNow); @@ -178,7 +177,7 @@ public abstract class AbstractQueuedExecutionManager implements ExecutionManager * * @see uws.job.manager.ExecutionManager#execute(AbstractJob) */ - public synchronized final ExecutionPhase execute(final UWSJob jobToExecute) throws UWSException { + public synchronized final ExecutionPhase execute(final UWSJob jobToExecute) throws UWSException{ if (jobToExecute == null) return null; @@ -217,7 +216,7 @@ public abstract class AbstractQueuedExecutionManager implements ExecutionManager * * @see uws.job.manager.ExecutionManager#remove(uws.job.UWSJob) */ - public final synchronized void remove(final UWSJob jobToRemove) throws UWSException { + public final synchronized void remove(final UWSJob jobToRemove) throws UWSException{ if (jobToRemove != null){ runningJobs.remove(jobToRemove.getJobId()); queuedJobs.remove(jobToRemove); diff --git a/src/uws/job/manager/DefaultDestructionManager.java b/src/uws/job/manager/DefaultDestructionManager.java index 649da6b4f2558a7749ec2b2cf2fe05b32169802a..24bff3e6e1ae765a08ef33f8f9a65b50e0056d34 100644 --- a/src/uws/job/manager/DefaultDestructionManager.java +++ b/src/uws/job/manager/DefaultDestructionManager.java @@ -120,11 +120,11 @@ public class DefaultDestructionManager implements DestructionManager { } public final String getNextJobToDestroy(){ - return (currentJob==null)?null:currentJob.getJobId(); + return (currentJob == null) ? null : currentJob.getJobId(); } public final int getNbJobsToDestroy(){ - return jobsToDestroy.size()+(isRunning()?1:0); + return jobsToDestroy.size() + (isRunning() ? 1 : 0); } /** @@ -174,9 +174,9 @@ public class DefaultDestructionManager implements DestructionManager { if (currentJob != null){ timDestruction = new Timer(); currentDate = currentJob.getDestructionTime(); - timDestruction.schedule(new TimerTask() { + timDestruction.schedule(new TimerTask(){ @Override - public void run() { + public void run(){ destroyJob(currentJob); } }, currentDate); @@ -242,7 +242,7 @@ public class DefaultDestructionManager implements DestructionManager { private static final long serialVersionUID = 1L; @Override - public int compare(UWSJob job1, UWSJob job2) { + public int compare(UWSJob job1, UWSJob job2){ if (job1 == null && job2 == null) return 0; diff --git a/src/uws/job/manager/DefaultExecutionManager.java b/src/uws/job/manager/DefaultExecutionManager.java index 12bb724790a1d4554f04b5e996d6eac30756f77f..e00bda0af82d9ef37c49eb428b8156ba306e9979 100644 --- a/src/uws/job/manager/DefaultExecutionManager.java +++ b/src/uws/job/manager/DefaultExecutionManager.java @@ -42,11 +42,10 @@ public class DefaultExecutionManager implements ExecutionManager { private static final long serialVersionUID = 1L; /** List of running jobs. */ - protected Map<String, UWSJob> runningJobs; - + protected Map<String,UWSJob> runningJobs; public DefaultExecutionManager(){ - runningJobs = new LinkedHashMap<String, UWSJob>(10); + runningJobs = new LinkedHashMap<String,UWSJob>(10); } /* ******* */ @@ -67,15 +66,21 @@ public class DefaultExecutionManager implements ExecutionManager { * @see uws.job.manager.ExecutionManager#getQueuedJobs() */ public final Iterator<UWSJob> getQueuedJobs(){ - return new Iterator<UWSJob>() { + return new Iterator<UWSJob>(){ @Override - public boolean hasNext() { return false; } + public boolean hasNext(){ + return false; + } @Override - public UWSJob next() { return null; } + public UWSJob next(){ + return null; + } @Override - public void remove() { ; } + public void remove(){ + ; + } }; } @@ -84,16 +89,20 @@ public class DefaultExecutionManager implements ExecutionManager { * * @see uws.job.manager.ExecutionManager#getNbQueuedJobs() */ - public final int getNbQueuedJobs(){ return 0; } + public final int getNbQueuedJobs(){ + return 0; + } /** * Does nothing in its implementation. * * @see uws.job.manager.ExecutionManager#refresh() */ - public final void refresh() throws UWSException { ; } + public final void refresh() throws UWSException{ + ; + } - public synchronized ExecutionPhase execute(final UWSJob jobToExecute) throws UWSException { + public synchronized ExecutionPhase execute(final UWSJob jobToExecute) throws UWSException{ if (jobToExecute == null) return null; @@ -107,7 +116,7 @@ public class DefaultExecutionManager implements ExecutionManager { throw UWSExceptionFactory.incorrectPhaseTransition(jobToExecute.getJobId(), jobToExecute.getPhase(), ExecutionPhase.EXECUTING); // Otherwise start it: - } else { + }else{ jobToExecute.start(false); runningJobs.put(jobToExecute.getJobId(), jobToExecute); } @@ -115,7 +124,7 @@ public class DefaultExecutionManager implements ExecutionManager { return jobToExecute.getPhase(); } - public synchronized void remove(final UWSJob jobToRemove) throws UWSException { + public synchronized void remove(final UWSJob jobToRemove) throws UWSException{ if (jobToRemove != null) runningJobs.remove(jobToRemove.getJobId()); } diff --git a/src/uws/job/manager/QueuedExecutionManager.java b/src/uws/job/manager/QueuedExecutionManager.java index af1d3c0fe26d2be702c7f7a8ebe68b78eea9a665..9fd9de413af0de36bcbf935f32607e80a6e11112 100644 --- a/src/uws/job/manager/QueuedExecutionManager.java +++ b/src/uws/job/manager/QueuedExecutionManager.java @@ -41,7 +41,6 @@ public class QueuedExecutionManager extends AbstractQueuedExecutionManager { /** The value of {@link #nbMaxRunningJobs} which indicates that there is no queue. */ public final static int NO_QUEUE = Integer.MAX_VALUE; - /* ************ */ /* CONSTRUCTORS */ /* ************ */ @@ -60,16 +59,16 @@ public class QueuedExecutionManager extends AbstractQueuedExecutionManager { * @param logger The object to user to log some messages (error, info, debug). * @param maxRunningJobs The maximum number of running jobs (must be > 0 to have a queue). */ - public QueuedExecutionManager(final UWSLog logger, int maxRunningJobs) { + public QueuedExecutionManager(final UWSLog logger, int maxRunningJobs){ this(logger); - nbMaxRunningJobs = (maxRunningJobs <= 0)?NO_QUEUE:maxRunningJobs; + nbMaxRunningJobs = (maxRunningJobs <= 0) ? NO_QUEUE : maxRunningJobs; } /* ***************** */ /* GETTERS & SETTERS */ /* ***************** */ - public final void setNoQueue() { + public final void setNoQueue(){ nbMaxRunningJobs = NO_QUEUE; try{ refresh(); @@ -99,13 +98,13 @@ public class QueuedExecutionManager extends AbstractQueuedExecutionManager { * * @see #refresh() */ - public void setMaxRunningJobs(int maxRunningJobs) throws UWSException { - nbMaxRunningJobs = (maxRunningJobs <= 0)?NO_QUEUE:maxRunningJobs; + public void setMaxRunningJobs(int maxRunningJobs) throws UWSException{ + nbMaxRunningJobs = (maxRunningJobs <= 0) ? NO_QUEUE : maxRunningJobs; refresh(); } @Override - public final boolean isReadyForExecution(final UWSJob jobToExecute) { + public final boolean isReadyForExecution(final UWSJob jobToExecute){ if (!hasQueue()) return true; else diff --git a/src/uws/job/parameters/DestructionTimeController.java b/src/uws/job/parameters/DestructionTimeController.java index d5a202c448c0ecc87b63efe660a3c9346cb3eea0..103b64ce0e5510516ee6e21153c0e7affe7750d9 100644 --- a/src/uws/job/parameters/DestructionTimeController.java +++ b/src/uws/job/parameters/DestructionTimeController.java @@ -60,15 +60,11 @@ public class DestructionTimeController implements InputParamController, Serializ * * @see Calendar */ - public static enum DateField { - SECOND (Calendar.SECOND), - MINUTE (Calendar.MINUTE), - HOUR (Calendar.HOUR), - DAY (Calendar.DAY_OF_MONTH), - MONTH (Calendar.MONTH), - YEAR (Calendar.YEAR); + public static enum DateField{ + SECOND(Calendar.SECOND), MINUTE(Calendar.MINUTE), HOUR(Calendar.HOUR), DAY(Calendar.DAY_OF_MONTH), MONTH(Calendar.MONTH), YEAR(Calendar.YEAR); private final int index; + private DateField(int fieldIndex){ index = fieldIndex; } @@ -99,7 +95,7 @@ public class DestructionTimeController implements InputParamController, Serializ protected boolean allowModification = true; @Override - public Object check(Object value) throws UWSException { + public Object check(Object value) throws UWSException{ if (value == null) return null; @@ -118,13 +114,13 @@ public class DestructionTimeController implements InputParamController, Serializ Date maxDate = getMaxDestructionTime(); if (maxDate != null && date.after(maxDate)) - throw new UWSException(UWSException.BAD_REQUEST, "The UWS limits "+((defaultInterval > NO_INTERVAL)?("the DESTRUCTION INTERVAL (since now) to "+maxInterval+" "+maxIntervalField.name().toLowerCase()+"s"):("the DESTRUCTION TIME to "+maxDate))+" !"); + throw new UWSException(UWSException.BAD_REQUEST, "The UWS limits " + ((defaultInterval > NO_INTERVAL) ? ("the DESTRUCTION INTERVAL (since now) to " + maxInterval + " " + maxIntervalField.name().toLowerCase() + "s") : ("the DESTRUCTION TIME to " + maxDate)) + " !"); return date; } @Override - public Object getDefault() { + public Object getDefault(){ return getDefaultDestructionTime(); } @@ -136,7 +132,7 @@ public class DestructionTimeController implements InputParamController, Serializ * * @return The default destruction time (<i>null</i> means that jobs may stay forever). */ - public final Date getDefaultDestructionTime() { + public final Date getDefaultDestructionTime(){ if (defaultInterval > NO_INTERVAL){ Calendar date = Calendar.getInstance(); try{ @@ -160,7 +156,7 @@ public class DestructionTimeController implements InputParamController, Serializ * * @param defaultDestructionTime The default destruction time to set (<i>null</i> means jobs may stay forever). */ - public final void setDefaultDestructionTime(Date defaultDestructionTime) { + public final void setDefaultDestructionTime(Date defaultDestructionTime){ this.defaultTime = defaultDestructionTime; defaultInterval = NO_INTERVAL; defaultIntervalField = null; @@ -173,7 +169,7 @@ public class DestructionTimeController implements InputParamController, Serializ * * @return The default destruction interval. */ - public final int getDefaultDestructionInterval() { + public final int getDefaultDestructionInterval(){ return defaultInterval; } @@ -182,7 +178,7 @@ public class DestructionTimeController implements InputParamController, Serializ * * @return The default interval field. */ - public final DateField getDefaultIntervalField() { + public final DateField getDefaultIntervalField(){ return defaultIntervalField; } @@ -199,7 +195,7 @@ public class DestructionTimeController implements InputParamController, Serializ * * @see #setDefaultDestructionInterval(int, DateField) */ - public final void setDefaultDestructionInterval(int defaultDestructionInterval) { + public final void setDefaultDestructionInterval(int defaultDestructionInterval){ setDefaultDestructionInterval(defaultDestructionInterval, DateField.MINUTE); } @@ -215,7 +211,7 @@ public class DestructionTimeController implements InputParamController, Serializ * @param defaultDestructionInterval The default destruction interval ({@link #NO_INTERVAL}, 0 or a negative value mean the job may stay forever). * @param timeField The unit of the interval (<i>null</i> means the job may stay forever). */ - public final void setDefaultDestructionInterval(int defaultDestructionInterval, DateField timeField) { + public final void setDefaultDestructionInterval(int defaultDestructionInterval, DateField timeField){ if (defaultDestructionInterval <= 0 || timeField == null){ defaultIntervalField = null; defaultInterval = NO_INTERVAL; @@ -231,7 +227,7 @@ public class DestructionTimeController implements InputParamController, Serializ * * @return The maximum destruction time (<i>null</i> means that jobs may stay forever). */ - public final Date getMaxDestructionTime() { + public final Date getMaxDestructionTime(){ if (maxInterval > NO_INTERVAL){ Calendar date = Calendar.getInstance(); try{ @@ -255,7 +251,7 @@ public class DestructionTimeController implements InputParamController, Serializ * * @param maxDestructionTime The maximum destruction time to set (<i>null</i> means jobs may stay forever). */ - public final void setMaxDestructionTime(Date maxDestructionTime) { + public final void setMaxDestructionTime(Date maxDestructionTime){ this.maxTime = maxDestructionTime; maxInterval = NO_INTERVAL; maxIntervalField = null; @@ -268,7 +264,7 @@ public class DestructionTimeController implements InputParamController, Serializ * * @return The maximum destruction interval. */ - public final int getMaxDestructionInterval() { + public final int getMaxDestructionInterval(){ return maxInterval; } @@ -277,7 +273,7 @@ public class DestructionTimeController implements InputParamController, Serializ * * @return The maximum interval field. */ - public final DateField getMaxIntervalField() { + public final DateField getMaxIntervalField(){ return maxIntervalField; } @@ -294,7 +290,7 @@ public class DestructionTimeController implements InputParamController, Serializ * * @see #setMaxDestructionInterval(int, DateField) */ - public final void setMaxDestructionInterval(int maxDestructionInterval) { + public final void setMaxDestructionInterval(int maxDestructionInterval){ setMaxDestructionInterval(maxDestructionInterval, DateField.MINUTE); } @@ -310,7 +306,7 @@ public class DestructionTimeController implements InputParamController, Serializ * @param maxDestructionInterval The maximum destruction interval ({@link #NO_INTERVAL}, 0 or a negative value mean the job may stay forever). * @param timeField The unit of the interval (<i>null</i> means the job may stay forever). */ - public final void setMaxDestructionInterval(int maxDestructionInterval, DateField timeField) { + public final void setMaxDestructionInterval(int maxDestructionInterval, DateField timeField){ this.maxInterval = maxDestructionInterval; maxIntervalField = timeField; maxTime = null; @@ -321,7 +317,7 @@ public class DestructionTimeController implements InputParamController, Serializ * * @return <i>true</i> if the destruction time can be modified, <i>false</i> otherwise. */ - public final boolean allowModification() { + public final boolean allowModification(){ return allowModification; } @@ -330,7 +326,7 @@ public class DestructionTimeController implements InputParamController, Serializ * * @param allowModification <i>true</i> if the destruction time can be modified, <i>false</i> otherwise. */ - public final void allowModification(boolean allowModification) { + public final void allowModification(boolean allowModification){ this.allowModification = allowModification; } diff --git a/src/uws/job/parameters/ExecutionDurationController.java b/src/uws/job/parameters/ExecutionDurationController.java index 43a2f46b0a91a70593692ffd79186114b1cf7128..7c2d7eedfb5680724b7a39df4c79b4b48d51771f 100644 --- a/src/uws/job/parameters/ExecutionDurationController.java +++ b/src/uws/job/parameters/ExecutionDurationController.java @@ -54,8 +54,9 @@ public class ExecutionDurationController implements InputParamController, Serial /** Indicates whether the execution duration of jobs can be modified. */ protected boolean allowModification = true; - - public ExecutionDurationController(){ ; } + public ExecutionDurationController(){ + ; + } public ExecutionDurationController(final long defaultDuration, final long maxDuration, final boolean allowModification){ setDefaultExecutionDuration(defaultDuration); @@ -64,12 +65,12 @@ public class ExecutionDurationController implements InputParamController, Serial } @Override - public Object getDefault() { + public Object getDefault(){ return defaultDuration; } @Override - public Object check(Object value) throws UWSException { + public Object check(Object value) throws UWSException{ if (value == null) return null; @@ -81,15 +82,15 @@ public class ExecutionDurationController implements InputParamController, Serial try{ duration = Long.parseLong(strValue); }catch(NumberFormatException nfe){ - throw UWSExceptionFactory.badFormat(null, UWSJob.PARAM_EXECUTION_DURATION, strValue, null, "A long value between "+UWSJob.UNLIMITED_DURATION+" and "+maxDuration+" (Default value: "+defaultDuration+")."); + throw UWSExceptionFactory.badFormat(null, UWSJob.PARAM_EXECUTION_DURATION, strValue, null, "A long value between " + UWSJob.UNLIMITED_DURATION + " and " + maxDuration + " (Default value: " + defaultDuration + ")."); } }else - throw UWSExceptionFactory.badFormat(null, UWSJob.PARAM_EXECUTION_DURATION, null, value.getClass().getName(), "A long value between "+UWSJob.UNLIMITED_DURATION+" and "+maxDuration+" (Default value: "+defaultDuration+")."); + throw UWSExceptionFactory.badFormat(null, UWSJob.PARAM_EXECUTION_DURATION, null, value.getClass().getName(), "A long value between " + UWSJob.UNLIMITED_DURATION + " and " + maxDuration + " (Default value: " + defaultDuration + ")."); if (duration < UWSJob.UNLIMITED_DURATION) duration = UWSJob.UNLIMITED_DURATION; else if (maxDuration > UWSJob.UNLIMITED_DURATION && duration > maxDuration) - throw new UWSException(UWSException.BAD_REQUEST, "The UWS limits the execution duration to maximum "+maxDuration+" seconds !"); + throw new UWSException(UWSException.BAD_REQUEST, "The UWS limits the execution duration to maximum " + maxDuration + " seconds !"); return duration; } @@ -102,7 +103,7 @@ public class ExecutionDurationController implements InputParamController, Serial * * @return The default execution duration <i>(0 or less mean an unlimited duration)</i>. */ - public final long getDefaultExecutionDuration() { + public final long getDefaultExecutionDuration(){ return defaultDuration; } @@ -111,8 +112,8 @@ public class ExecutionDurationController implements InputParamController, Serial * * @param defaultExecutionDuration The new default execution duration <i>({@link UWSJob#UNLIMITED_DURATION}, 0 or a negative value mean an unlimited duration)</i>. */ - public final boolean setDefaultExecutionDuration(long defaultExecutionDuration) { - defaultExecutionDuration = (defaultExecutionDuration <= 0)?UWSJob.UNLIMITED_DURATION:defaultExecutionDuration; + public final boolean setDefaultExecutionDuration(long defaultExecutionDuration){ + defaultExecutionDuration = (defaultExecutionDuration <= 0) ? UWSJob.UNLIMITED_DURATION : defaultExecutionDuration; if (defaultExecutionDuration != UWSJob.UNLIMITED_DURATION && maxDuration != UWSJob.UNLIMITED_DURATION && defaultExecutionDuration > maxDuration) return false; @@ -127,7 +128,7 @@ public class ExecutionDurationController implements InputParamController, Serial * * @return The maximum execution duration <i>(0 or less mean an unlimited duration)</i>. */ - public final long getMaxExecutionDuration() { + public final long getMaxExecutionDuration(){ return maxDuration; } @@ -136,8 +137,8 @@ public class ExecutionDurationController implements InputParamController, Serial * * @param maxExecutionDuration The maximum execution duration <i>({@link UWSJob#UNLIMITED_DURATION}, 0 or a negative value mean an unlimited duration)</i>. */ - public final void setMaxExecutionDuration(long maxExecutionDuration) { - maxDuration = (maxExecutionDuration <= 0)?UWSJob.UNLIMITED_DURATION:maxExecutionDuration; + public final void setMaxExecutionDuration(long maxExecutionDuration){ + maxDuration = (maxExecutionDuration <= 0) ? UWSJob.UNLIMITED_DURATION : maxExecutionDuration; if (defaultDuration != UWSJob.UNLIMITED_DURATION && maxDuration != UWSJob.UNLIMITED_DURATION && defaultDuration > maxDuration) defaultDuration = maxDuration; } @@ -147,7 +148,7 @@ public class ExecutionDurationController implements InputParamController, Serial * * @return <i>true</i> if the execution duration can be modified, <i>false</i> otherwise. */ - public final boolean allowModification() { + public final boolean allowModification(){ return allowModification; } @@ -156,7 +157,7 @@ public class ExecutionDurationController implements InputParamController, Serial * * @param allowModification <i>true</i> if the execution duration can be modified, <i>false</i> otherwise. */ - public final void allowModification(boolean allowModification) { + public final void allowModification(boolean allowModification){ this.allowModification = allowModification; } diff --git a/src/uws/job/parameters/StringParamController.java b/src/uws/job/parameters/StringParamController.java index 8d069cff9864c1dd3510ce0b5f9fbde90f49cae0..39b42bf2930080f38dd93cd5ec4f8d5ca52d889d 100644 --- a/src/uws/job/parameters/StringParamController.java +++ b/src/uws/job/parameters/StringParamController.java @@ -42,7 +42,6 @@ public class StringParamController implements InputParamController { /** Tells whether the parameter can be modified after its initialization. */ private boolean allowModification = true; - /** * Builds a controller of the specified String parameter. * @@ -74,7 +73,7 @@ public class StringParamController implements InputParamController { * * @return The default value. (MAY BE NULL) */ - public final String getDefaultValue() { + public final String getDefaultValue(){ return defaultValue; } @@ -83,7 +82,7 @@ public class StringParamController implements InputParamController { * * @param defaultValue The new default value. (MAY BE NULL) */ - public final void setDefaultValue(String defaultValue) { + public final void setDefaultValue(String defaultValue){ this.defaultValue = defaultValue; } @@ -92,7 +91,7 @@ public class StringParamController implements InputParamController { * * @return The allowed values. <i><u>note:</u> If NULL or empty, any value is allowed.</i> */ - public final String[] getPossibleValues() { + public final String[] getPossibleValues(){ return possibleValues; } @@ -101,7 +100,7 @@ public class StringParamController implements InputParamController { * * @param possibleValues The new allowed values. <i><u>note:</u> If NULL or empty, any value is allowed.</i> */ - public final void setPossibleValues(String[] possibleValues) { + public final void setPossibleValues(String[] possibleValues){ if (possibleValues == null || possibleValues.length == 0) this.possibleValues = null; else @@ -109,7 +108,7 @@ public class StringParamController implements InputParamController { } @Override - public final boolean allowModification() { + public final boolean allowModification(){ return allowModification; } @@ -118,12 +117,12 @@ public class StringParamController implements InputParamController { * * @param allowModif <i>true</i> to allow its modification after initialization, <i>false</i> otherwise. */ - public final void allowModification(final boolean allowModif) { + public final void allowModification(final boolean allowModif){ allowModification = allowModif; } @Override - public Object check(Object value) throws UWSException { + public Object check(Object value) throws UWSException{ if (value == null) return null; @@ -149,15 +148,15 @@ public class StringParamController implements InputParamController { protected final String getExpectedFormat(){ if (possibleValues == null || possibleValues.length == 0){ StringBuffer buffer = new StringBuffer("A String value among: "); - for(int i=0; i<possibleValues.length; i++) - buffer.append((i==0)?"":", ").append(possibleValues[i]); + for(int i = 0; i < possibleValues.length; i++) + buffer.append((i == 0) ? "" : ", ").append(possibleValues[i]); return buffer.toString(); }else return "A String value."; } @Override - public Object getDefault() { + public Object getDefault(){ return defaultValue; } diff --git a/src/uws/job/parameters/UWSParameters.java b/src/uws/job/parameters/UWSParameters.java index 5a576017c9b09c58d7f81311f56a32bc5fd98300..767706ad072510b40f48d4b9f48165b59d543bfb 100644 --- a/src/uws/job/parameters/UWSParameters.java +++ b/src/uws/job/parameters/UWSParameters.java @@ -95,23 +95,23 @@ import uws.service.UWS; * @author Grégory Mantelet (CDS) * @version 06/2012 */ -public class UWSParameters implements Iterable<Entry<String, Object>> { +public class UWSParameters implements Iterable<Entry<String,Object>> { /** * <p>Read-Write parameters.</p> * <p>Names of the UWS parameters whose the value can be modified by the user.</p> */ - protected final static String[] UWS_RW_PARAMETERS = new String[]{UWSJob.PARAM_PHASE, UWSJob.PARAM_RUN_ID, UWSJob.PARAM_EXECUTION_DURATION, UWSJob.PARAM_DESTRUCTION_TIME, UWSJob.PARAM_PARAMETERS}; + protected final static String[] UWS_RW_PARAMETERS = new String[]{UWSJob.PARAM_PHASE,UWSJob.PARAM_RUN_ID,UWSJob.PARAM_EXECUTION_DURATION,UWSJob.PARAM_DESTRUCTION_TIME,UWSJob.PARAM_PARAMETERS}; /** * <p>Read-Only parameters.</p> * <p>Names of the UWS parameters whose the value can NOT be modified by the user. These value are not kept. They are only ignored.</p> */ - protected final static String[] UWS_RO_PARAMETERS = new String[]{UWSJob.PARAM_JOB_ID, UWSJob.PARAM_OWNER, UWSJob.PARAM_QUOTE, UWSJob.PARAM_START_TIME, UWSJob.PARAM_END_TIME, UWSJob.PARAM_RESULTS, UWSJob.PARAM_ERROR_SUMMARY}; + protected final static String[] UWS_RO_PARAMETERS = new String[]{UWSJob.PARAM_JOB_ID,UWSJob.PARAM_OWNER,UWSJob.PARAM_QUOTE,UWSJob.PARAM_START_TIME,UWSJob.PARAM_END_TIME,UWSJob.PARAM_RESULTS,UWSJob.PARAM_ERROR_SUMMARY}; /** * List of all extracted parameters. */ - protected final Map<String, Object> params = new HashMap<String, Object>(10); + protected final Map<String,Object> params = new HashMap<String,Object>(10); /** * <p>List of all UWS additional parameters.</p> @@ -119,7 +119,7 @@ public class UWSParameters implements Iterable<Entry<String, Object>> { * It is deleted (set to NULL) when there is a modification in the list of all parameters * (so in the function {@link #set(String, Object)}, {@link #update(UWSParameters)} and {@link #init()}).</i></p> */ - private HashMap<String, Object> additionalParams = null; + private HashMap<String,Object> additionalParams = null; /** * List of the expected additional parameters. @@ -129,8 +129,7 @@ public class UWSParameters implements Iterable<Entry<String, Object>> { /** * List of the controllers of all the input parameters. */ - protected final Map<String, InputParamController> mapParamControllers; - + protected final Map<String,InputParamController> mapParamControllers; /** * Builds an empty list of UWS parameters. @@ -154,7 +153,7 @@ public class UWSParameters implements Iterable<Entry<String, Object>> { * * @see #getDefaultUWSParamControllers() */ - public UWSParameters(final Collection<String> expectedAdditionalParams, final Map<String, InputParamController> inputParamControllers){ + public UWSParameters(final Collection<String> expectedAdditionalParams, final Map<String,InputParamController> inputParamControllers){ // Set the input parameter controllers: mapParamControllers = getDefaultControllers(); if (inputParamControllers != null) @@ -175,12 +174,10 @@ public class UWSParameters implements Iterable<Entry<String, Object>> { * * @see #UWSParameters(HttpServletRequest, Collection, Map) */ - public UWSParameters(final HttpServletRequest request) throws UWSException { + public UWSParameters(final HttpServletRequest request) throws UWSException{ this(request, null, null); } - - /** * <p>Extracts and identifies all UWS standard and non-standard parameters from the given {@link HttpServletRequest}.</p> * @@ -198,7 +195,7 @@ public class UWSParameters implements Iterable<Entry<String, Object>> { * @see #UWSParameters(Collection, Map) */ @SuppressWarnings("unchecked") - public UWSParameters(final HttpServletRequest request, final Collection<String> expectedAdditionalParams, final Map<String, InputParamController> inputParamControllers) throws UWSException { + public UWSParameters(final HttpServletRequest request, final Collection<String> expectedAdditionalParams, final Map<String,InputParamController> inputParamControllers) throws UWSException{ this(expectedAdditionalParams, inputParamControllers); // Load all parameters: @@ -223,7 +220,7 @@ public class UWSParameters implements Iterable<Entry<String, Object>> { * * @see #UWSParameters(Map, Collection, Map) */ - public UWSParameters(final Map<String, Object> params) throws UWSException { + public UWSParameters(final Map<String,Object> params) throws UWSException{ this(params, null, null); } @@ -243,14 +240,14 @@ public class UWSParameters implements Iterable<Entry<String, Object>> { * * @see #UWSParameters(Collection, Map) */ - public UWSParameters(final Map<String, Object> params, final Collection<String> expectedAdditionalParams, final Map<String, InputParamController> inputParamControllers) throws UWSException { + public UWSParameters(final Map<String,Object> params, final Collection<String> expectedAdditionalParams, final Map<String,InputParamController> inputParamControllers) throws UWSException{ this(expectedAdditionalParams, inputParamControllers); // Load all parameters: if (params != null && !params.isEmpty()){ synchronized(params){ - Iterator<Entry<String, Object>> it = params.entrySet().iterator(); - Entry<String, Object> entry; + Iterator<Entry<String,Object>> it = params.entrySet().iterator(); + Entry<String,Object> entry; while(it.hasNext()){ entry = it.next(); set(entry.getKey(), entry.getValue()); @@ -264,8 +261,8 @@ public class UWSParameters implements Iterable<Entry<String, Object>> { * * @return Default list of controllers. <i><u>note:</u> This map can be modified !</i> */ - protected HashMap<String, InputParamController> getDefaultControllers(){ - HashMap<String, InputParamController> controllers = new HashMap<String, InputParamController>(2); + protected HashMap<String,InputParamController> getDefaultControllers(){ + HashMap<String,InputParamController> controllers = new HashMap<String,InputParamController>(2); controllers.put(UWSJob.PARAM_EXECUTION_DURATION, new ExecutionDurationController()); controllers.put(UWSJob.PARAM_DESTRUCTION_TIME, new DestructionTimeController()); return controllers; @@ -294,11 +291,11 @@ public class UWSParameters implements Iterable<Entry<String, Object>> { * @return The list of all available controllers or <i>null</i> if there is no controller * or if this {@link UWSParameters} instance doesn't know a {@link UWS}. */ - protected Iterator<Entry<String, InputParamController>> getControllers(){ + protected Iterator<Entry<String,InputParamController>> getControllers(){ return mapParamControllers.entrySet().iterator(); } - public final Iterator<Entry<String, Object>> iterator(){ + public final Iterator<Entry<String,Object>> iterator(){ return params.entrySet().iterator(); } @@ -332,10 +329,10 @@ public class UWSParameters implements Iterable<Entry<String, Object>> { * <p><i><u>note:</u> This method is thread safe (synchronized on the list of parameters) !</i></p> */ public final void init(){ - Iterator<Entry<String, InputParamController>> itControllers = getControllers(); + Iterator<Entry<String,InputParamController>> itControllers = getControllers(); if (itControllers != null){ synchronized(params){ - Entry<String, InputParamController> entry; + Entry<String,InputParamController> entry; while(itControllers.hasNext()){ entry = itControllers.next(); if (!params.containsKey(entry.getKey()) && entry.getValue().getDefault() != null) @@ -357,17 +354,17 @@ public class UWSParameters implements Iterable<Entry<String, Object>> { * * @exception UWSException If one of the given parameters is not allowed to be modified. */ - public String[] update(final UWSParameters newParams) throws UWSException { + public String[] update(final UWSParameters newParams) throws UWSException{ if (newParams != null && !newParams.params.isEmpty()){ synchronized(params){ additionalParams = null; String[] updated = new String[newParams.params.size()]; - int i=0; - for(Entry<String, Object> entry : newParams){ + int i = 0; + for(Entry<String,Object> entry : newParams){ // Test whether this parameter is allowed to be modified after its initialization: InputParamController controller = getController(entry.getKey()); if (controller != null && !controller.allowModification()) - throw new UWSException("The parameter \""+entry.getKey()+"\" can not be modified after initialization !"); + throw new UWSException("The parameter \"" + entry.getKey() + "\" can not be modified after initialization !"); // If the value is NULL, removes this parameter: if (entry.getValue() == null) params.remove(entry.getKey()); @@ -425,7 +422,7 @@ public class UWSParameters implements Iterable<Entry<String, Object>> { * @see #normalizeParamName(String) */ @SuppressWarnings("unchecked") - public final Object set(final String name, Object value) throws UWSException { + public final Object set(final String name, Object value) throws UWSException{ // Normalize (take into account the case ONLY FOR the non-standard UWS parameters) the given parameter name: String normalizedName = normalizeParamName(name); @@ -445,10 +442,10 @@ public class UWSParameters implements Iterable<Entry<String, Object>> { // the value MUST BE a Map<String, Object>: if (value instanceof Map){ try{ - Map<String, Object> otherParams = (Map<String,Object>)value; - HashMap<String, Object> mapOldValues = new HashMap<String, Object>(otherParams.size()); + Map<String,Object> otherParams = (Map<String,Object>)value; + HashMap<String,Object> mapOldValues = new HashMap<String,Object>(otherParams.size()); Object oldValue = null; - for(Entry<String, Object> entry : otherParams.entrySet()){ + for(Entry<String,Object> entry : otherParams.entrySet()){ oldValue = set(entry.getKey(), entry.getValue()); mapOldValues.put(entry.getKey(), oldValue); } @@ -573,7 +570,9 @@ public class UWSParameters implements Iterable<Entry<String, Object>> { params.put(UWSJob.PARAM_EXECUTION_DURATION, duration); } return duration; - }catch(NumberFormatException nfe){ ; } + }catch(NumberFormatException nfe){ + ; + } } } return UWSJob.UNLIMITED_DURATION; @@ -595,7 +594,9 @@ public class UWSParameters implements Iterable<Entry<String, Object>> { params.put(UWSJob.PARAM_DESTRUCTION_TIME, destruction); } return destruction; - }catch(ParseException pe){ ; } + }catch(ParseException pe){ + ; + } } } return null; @@ -609,15 +610,15 @@ public class UWSParameters implements Iterable<Entry<String, Object>> { * * @return All the UWS additional parameters. */ - public final Map<String, Object> getAdditionalParameters(){ + public final Map<String,Object> getAdditionalParameters(){ if (additionalParams == null){ synchronized(params){ - additionalParams = new HashMap<String, Object>(params.size()); - for(Entry<String, Object> entry : params.entrySet()){ + additionalParams = new HashMap<String,Object>(params.size()); + for(Entry<String,Object> entry : params.entrySet()){ boolean uwsParam = false; - for(int i=0; !uwsParam && i<UWS_RW_PARAMETERS.length; i++) + for(int i = 0; !uwsParam && i < UWS_RW_PARAMETERS.length; i++) uwsParam = entry.getKey().equals(UWS_RW_PARAMETERS[i]); - for(int i=0; !uwsParam && i<UWS_RO_PARAMETERS.length; i++) + for(int i = 0; !uwsParam && i < UWS_RO_PARAMETERS.length; i++) uwsParam = entry.getKey().equals(UWS_RO_PARAMETERS[i]); if (!uwsParam) additionalParams.put(entry.getKey(), entry.getValue()); diff --git a/src/uws/job/serializer/JSONSerializer.java b/src/uws/job/serializer/JSONSerializer.java index f16b7102370850c8491ac1851d2ab98d5774d44e..9ffb8325f1f206f3ee1a7c853f8c36996dddc41a 100644 --- a/src/uws/job/serializer/JSONSerializer.java +++ b/src/uws/job/serializer/JSONSerializer.java @@ -45,14 +45,13 @@ import uws.service.UWSUrl; public class JSONSerializer extends UWSSerializer { private static final long serialVersionUID = 1L; - @Override - public final String getMimeType() { + public final String getMimeType(){ return MIME_TYPE_JSON; } @Override - public String getUWS(final UWS uws, final JobOwner user) throws UWSException { + public String getUWS(final UWS uws, final JobOwner user) throws UWSException{ try{ return Json4Uws.getJson(uws).toString(); }catch(JSONException je){ @@ -61,7 +60,7 @@ public class JSONSerializer extends UWSSerializer { } @Override - public String getJobList(final JobList jobsList, final JobOwner owner, final boolean root) throws UWSException { + public String getJobList(final JobList jobsList, final JobOwner owner, final boolean root) throws UWSException{ try{ return Json4Uws.getJson(jobsList, owner).toString(); }catch(JSONException je){ @@ -70,7 +69,7 @@ public class JSONSerializer extends UWSSerializer { } @Override - public String getJob(final UWSJob job, final boolean root) throws UWSException { + public String getJob(final UWSJob job, final boolean root) throws UWSException{ try{ return Json4Uws.getJson(job, null, false).toString(); }catch(JSONException je){ @@ -79,7 +78,7 @@ public class JSONSerializer extends UWSSerializer { } @Override - public String getJobRef(final UWSJob job, final UWSUrl jobsListUrl) throws UWSException { + public String getJobRef(final UWSJob job, final UWSUrl jobsListUrl) throws UWSException{ try{ return Json4Uws.getJson(job, jobsListUrl, true).toString(); }catch(JSONException je){ @@ -88,7 +87,7 @@ public class JSONSerializer extends UWSSerializer { } @Override - public String getJobID(final UWSJob job, final boolean root) throws UWSException { + public String getJobID(final UWSJob job, final boolean root) throws UWSException{ try{ return Json4Uws.getJson(UWSJob.PARAM_JOB_ID, job.getJobId()).toString(); }catch(JSONException je){ @@ -97,7 +96,7 @@ public class JSONSerializer extends UWSSerializer { } @Override - public String getRunID(final UWSJob job, final boolean root) throws UWSException { + public String getRunID(final UWSJob job, final boolean root) throws UWSException{ try{ return Json4Uws.getJson(UWSJob.PARAM_RUN_ID, job.getRunId()).toString(); }catch(JSONException je){ @@ -106,7 +105,7 @@ public class JSONSerializer extends UWSSerializer { } @Override - public String getOwnerID(final UWSJob job, final boolean root) throws UWSException { + public String getOwnerID(final UWSJob job, final boolean root) throws UWSException{ if (job.getOwner() == null) return "{}"; else{ @@ -119,7 +118,7 @@ public class JSONSerializer extends UWSSerializer { } @Override - public String getPhase(final UWSJob job, final boolean root) throws UWSException { + public String getPhase(final UWSJob job, final boolean root) throws UWSException{ try{ return Json4Uws.getJson(UWSJob.PARAM_PHASE, job.getPhase().toString()).toString(); }catch(JSONException je){ @@ -128,7 +127,7 @@ public class JSONSerializer extends UWSSerializer { } @Override - public String getQuote(final UWSJob job, final boolean root) throws UWSException { + public String getQuote(final UWSJob job, final boolean root) throws UWSException{ try{ return Json4Uws.getJson(UWSJob.PARAM_QUOTE, job.getQuote()).toString(); }catch(JSONException je){ @@ -137,7 +136,7 @@ public class JSONSerializer extends UWSSerializer { } @Override - public String getExecutionDuration(final UWSJob job, final boolean root) throws UWSException { + public String getExecutionDuration(final UWSJob job, final boolean root) throws UWSException{ try{ return Json4Uws.getJson(UWSJob.PARAM_EXECUTION_DURATION, job.getExecutionDuration()).toString(); }catch(JSONException je){ @@ -146,7 +145,7 @@ public class JSONSerializer extends UWSSerializer { } @Override - public String getDestructionTime(final UWSJob job, final boolean root) throws UWSException { + public String getDestructionTime(final UWSJob job, final boolean root) throws UWSException{ if (job.getDestructionTime() != null){ try{ return Json4Uws.getJson(UWSJob.PARAM_DESTRUCTION_TIME, UWSJob.dateFormat.format(job.getDestructionTime())).toString(); @@ -158,7 +157,7 @@ public class JSONSerializer extends UWSSerializer { } @Override - public String getStartTime(final UWSJob job, final boolean root) throws UWSException { + public String getStartTime(final UWSJob job, final boolean root) throws UWSException{ if (job.getDestructionTime() != null){ try{ return Json4Uws.getJson(UWSJob.PARAM_START_TIME, UWSJob.dateFormat.format(job.getDestructionTime())).toString(); @@ -170,7 +169,7 @@ public class JSONSerializer extends UWSSerializer { } @Override - public String getEndTime(final UWSJob job, final boolean root) throws UWSException { + public String getEndTime(final UWSJob job, final boolean root) throws UWSException{ if (job.getDestructionTime() != null){ try{ return Json4Uws.getJson(UWSJob.PARAM_END_TIME, UWSJob.dateFormat.format(job.getDestructionTime())).toString(); @@ -182,7 +181,7 @@ public class JSONSerializer extends UWSSerializer { } @Override - public String getErrorSummary(final ErrorSummary error, final boolean root) throws UWSException { + public String getErrorSummary(final ErrorSummary error, final boolean root) throws UWSException{ try{ return Json4Uws.getJson(error).toString(); }catch(JSONException je){ @@ -191,7 +190,7 @@ public class JSONSerializer extends UWSSerializer { } @Override - public String getAdditionalParameters(final UWSJob job, final boolean root) throws UWSException { + public String getAdditionalParameters(final UWSJob job, final boolean root) throws UWSException{ try{ return Json4Uws.getJobParamsJson(job).toString(); }catch(JSONException je){ @@ -200,7 +199,7 @@ public class JSONSerializer extends UWSSerializer { } @Override - public String getAdditionalParameter(final String paramName, final Object paramValue, final boolean root) throws UWSException { + public String getAdditionalParameter(final String paramName, final Object paramValue, final boolean root) throws UWSException{ try{ return Json4Uws.getJson(paramName, (paramValue == null) ? null : paramValue.toString()).toString(); }catch(JSONException je){ @@ -209,7 +208,7 @@ public class JSONSerializer extends UWSSerializer { } @Override - public String getResults(final UWSJob job, final boolean root) throws UWSException { + public String getResults(final UWSJob job, final boolean root) throws UWSException{ try{ return Json4Uws.getJobResultsJson(job).toString(); }catch(JSONException je){ @@ -218,7 +217,7 @@ public class JSONSerializer extends UWSSerializer { } @Override - public String getResult(final Result result, final boolean root) throws UWSException { + public String getResult(final Result result, final boolean root) throws UWSException{ try{ return Json4Uws.getJobResultJson(result).toString(); }catch(JSONException je){ diff --git a/src/uws/job/serializer/UWSSerializer.java b/src/uws/job/serializer/UWSSerializer.java index 635a43ea32d4018882ad94e4bda44cc16d54c092..3303987621c111d3af67570c640748042f9ac659 100644 --- a/src/uws/job/serializer/UWSSerializer.java +++ b/src/uws/job/serializer/UWSSerializer.java @@ -60,7 +60,6 @@ public abstract class UWSSerializer implements Serializable { /** MIME type for HTML: text/html */ public static final String MIME_TYPE_HTML = "text/html"; - /** * Serializes the given parameter of the given job * or serializes the whole job if the given attributes array is empty or <i>null</i>. @@ -75,7 +74,7 @@ public abstract class UWSSerializer implements Serializable { * * @throws UWSException If the specified attribute/parameter/result does not exist. */ - public String getJob(final UWSJob job, final String[] attributes, final boolean root) throws UWSException { + public String getJob(final UWSJob job, final String[] attributes, final boolean root) throws UWSException{ if (attributes == null || attributes.length <= 0) return getJob(job, root); @@ -86,28 +85,28 @@ public abstract class UWSSerializer implements Serializable { return job.getJobId(); // RUN ID: else if (firstAttribute.equalsIgnoreCase(UWSJob.PARAM_RUN_ID)) - return (job.getRunId() == null)?"":job.getRunId(); + return (job.getRunId() == null) ? "" : job.getRunId(); // OWNER: else if (firstAttribute.equalsIgnoreCase(UWSJob.PARAM_OWNER)) - return (job.getOwner() == null)?"":job.getOwner().getPseudo(); + return (job.getOwner() == null) ? "" : job.getOwner().getPseudo(); // PHASE: else if (firstAttribute.equalsIgnoreCase(UWSJob.PARAM_PHASE)) return job.getPhase().toString(); // QUOTE: else if (firstAttribute.equalsIgnoreCase(UWSJob.PARAM_QUOTE)) - return job.getQuote()+""; + return job.getQuote() + ""; // START TIME: else if (firstAttribute.equalsIgnoreCase(UWSJob.PARAM_START_TIME)) - return (job.getStartTime() == null)?"":UWSJob.dateFormat.format(job.getStartTime()); + return (job.getStartTime() == null) ? "" : UWSJob.dateFormat.format(job.getStartTime()); // END TIME: else if (firstAttribute.equalsIgnoreCase(UWSJob.PARAM_END_TIME)) - return (job.getEndTime() == null)?"":UWSJob.dateFormat.format(job.getEndTime()); + return (job.getEndTime() == null) ? "" : UWSJob.dateFormat.format(job.getEndTime()); // EXECUTION DURATION: else if (firstAttribute.equalsIgnoreCase(UWSJob.PARAM_EXECUTION_DURATION)) - return job.getExecutionDuration()+""; + return job.getExecutionDuration() + ""; // DESTRUCTION TIME: else if (firstAttribute.equalsIgnoreCase(UWSJob.PARAM_DESTRUCTION_TIME)) - return (job.getDestructionTime() == null)?"":UWSJob.dateFormat.format(job.getDestructionTime()); + return (job.getDestructionTime() == null) ? "" : UWSJob.dateFormat.format(job.getDestructionTime()); // PARAMETERS LIST: else if (firstAttribute.equalsIgnoreCase(UWSJob.PARAM_PARAMETERS)){ if (attributes.length <= 1) @@ -122,7 +121,7 @@ public abstract class UWSSerializer implements Serializable { throw UWSExceptionFactory.incorrectJobParameter(job.getJobId(), secondAttribute); } // RESULTS LIST: - } else if (firstAttribute.equalsIgnoreCase(UWSJob.PARAM_RESULTS)){ + }else if (firstAttribute.equalsIgnoreCase(UWSJob.PARAM_RESULTS)){ if (attributes.length <= 1) return getResults(job, root); else{ @@ -135,7 +134,7 @@ public abstract class UWSSerializer implements Serializable { throw UWSExceptionFactory.incorrectJobResult(job.getJobId(), secondAttribute); } // ERROR DETAILS or ERROR SUMMARY: - } else if (firstAttribute.equalsIgnoreCase(UWSJob.PARAM_ERROR_SUMMARY)) + }else if (firstAttribute.equalsIgnoreCase(UWSJob.PARAM_ERROR_SUMMARY)) if (job.getErrorSummary() != null && job.getErrorSummary().hasDetail()) throw new UWSException(UWSException.SEE_OTHER, job.getErrorSummary().getDetails().toString()); else @@ -166,7 +165,7 @@ public abstract class UWSSerializer implements Serializable { * * @see UWSSerializer#getUWS(UWSService, String) */ - public String getUWS(final UWS uws) throws UWSException { + public String getUWS(final UWS uws) throws UWSException{ return getUWS(uws, null); } diff --git a/src/uws/job/serializer/XMLSerializer.java b/src/uws/job/serializer/XMLSerializer.java index 3a587a8fa3f1cdfb40d9b3d62c7deb3a541d49d6..2107b54a00fde8422799649e6e9a117df078155a 100644 --- a/src/uws/job/serializer/XMLSerializer.java +++ b/src/uws/job/serializer/XMLSerializer.java @@ -49,11 +49,12 @@ public class XMLSerializer extends UWSSerializer { /** The path of the XSLT style-sheet. */ protected String xsltPath = null; - /** * Builds a XML serializer. */ - public XMLSerializer(){ ; } + public XMLSerializer(){ + ; + } /** * Builds a XML serializer with a XSLT link. @@ -79,7 +80,7 @@ public class XMLSerializer extends UWSSerializer { * @param path The new XSLT path/URL. */ public final void setXSLTPath(final String path){ - if (path ==null) + if (path == null) xsltPath = null; else{ xsltPath = path.trim(); @@ -123,7 +124,7 @@ public class XMLSerializer extends UWSSerializer { */ protected final String getUWSNamespace(boolean root){ if (root) - return " "+getUWSNamespace(); + return " " + getUWSNamespace(); else return ""; } @@ -134,12 +135,13 @@ public class XMLSerializer extends UWSSerializer { } @Override - public String getUWS(final UWS uws, final JobOwner user) { + public String getUWS(final UWS uws, final JobOwner user){ String name = uws.getName(), description = uws.getDescription(); StringBuffer xml = new StringBuffer(getHeader()); xml.append("<uws").append(getUWSNamespace(true)); - if (name != null) xml.append(" name=\"").append(escapeXMLAttribute(name)).append("\""); + if (name != null) + xml.append(" name=\"").append(escapeXMLAttribute(name)).append("\""); xml.append(">\n"); if (description != null) @@ -149,7 +151,8 @@ public class XMLSerializer extends UWSSerializer { for(JobList jobList : uws){ UWSUrl jlUrl = jobList.getUrl(); xml.append("\t\t<jobListRef name=\"").append(escapeXMLAttribute(jobList.getName())).append("\" href=\""); - if (jlUrl != null) xml.append(escapeURL(jlUrl.getRequestURL())); + if (jlUrl != null) + xml.append(escapeURL(jlUrl.getRequestURL())); xml.append("\" />\n"); } xml.append("\t</jobLists>\n"); @@ -160,7 +163,7 @@ public class XMLSerializer extends UWSSerializer { } @Override - public String getJobList(final JobList jobsList, final JobOwner owner, final boolean root) throws UWSException { + public String getJobList(final JobList jobsList, final JobOwner owner, final boolean root) throws UWSException{ String name = jobsList.getName(); StringBuffer xml = new StringBuffer(getHeader()); @@ -180,8 +183,8 @@ public class XMLSerializer extends UWSSerializer { } @Override - public String getJob(final UWSJob job, final boolean root) { - StringBuffer xml = new StringBuffer(root?getHeader():""); + public String getJob(final UWSJob job, final boolean root){ + StringBuffer xml = new StringBuffer(root ? getHeader() : ""); String newLine = "\n\t"; // general information: @@ -225,20 +228,21 @@ public class XMLSerializer extends UWSSerializer { if (job.getRunId() != null && job.getRunId().length() > 0) xml.append("\" runId=\"").append(escapeXMLAttribute(job.getRunId())); xml.append("\" xlink:href=\""); - if (url!=null) xml.append(escapeURL(url)); + if (url != null) + xml.append(escapeURL(url)); xml.append("\">").append(getPhase(job, false)).append("</uws:jobRef>"); return xml.toString(); } @Override - public String getJobID(final UWSJob job, final boolean root) { - return (new StringBuffer(root?getHeader():"")).append("<uws:jobId").append(getUWSNamespace(root)).append(">").append(escapeXMLData(job.getJobId())).append("</uws:jobId>").toString(); + public String getJobID(final UWSJob job, final boolean root){ + return (new StringBuffer(root ? getHeader() : "")).append("<uws:jobId").append(getUWSNamespace(root)).append(">").append(escapeXMLData(job.getJobId())).append("</uws:jobId>").toString(); } @Override - public String getRunID(final UWSJob job, final boolean root) { - StringBuffer xml = new StringBuffer(root?getHeader():""); + public String getRunID(final UWSJob job, final boolean root){ + StringBuffer xml = new StringBuffer(root ? getHeader() : ""); xml.append("<uws:runId").append(getUWSNamespace(root)); if (job.getRunId() == null) xml.append(" xsi:nil=\"true\" />"); @@ -248,8 +252,8 @@ public class XMLSerializer extends UWSSerializer { } @Override - public String getOwnerID(final UWSJob job, final boolean root) { - StringBuffer xml = new StringBuffer(root?getHeader():""); + public String getOwnerID(final UWSJob job, final boolean root){ + StringBuffer xml = new StringBuffer(root ? getHeader() : ""); xml.append("<uws:ownerId").append(getUWSNamespace(root)); if (job.getOwner() == null) xml.append(" xsi:nil=\"true\" />"); @@ -259,13 +263,13 @@ public class XMLSerializer extends UWSSerializer { } @Override - public String getPhase(final UWSJob job, final boolean root) { - return (new StringBuffer(root?getHeader():"")).append("<uws:phase").append(getUWSNamespace(root)).append(">").append(job.getPhase()).append("</uws:phase>").toString(); + public String getPhase(final UWSJob job, final boolean root){ + return (new StringBuffer(root ? getHeader() : "")).append("<uws:phase").append(getUWSNamespace(root)).append(">").append(job.getPhase()).append("</uws:phase>").toString(); } @Override - public String getQuote(final UWSJob job, final boolean root) { - StringBuffer xml = new StringBuffer(root?getHeader():""); + public String getQuote(final UWSJob job, final boolean root){ + StringBuffer xml = new StringBuffer(root ? getHeader() : ""); xml.append("<uws:quote").append(getUWSNamespace(root)); if (job.getQuote() <= 0) xml.append(" xsi:nil=\"true\" />"); @@ -275,8 +279,8 @@ public class XMLSerializer extends UWSSerializer { } @Override - public String getStartTime(final UWSJob job, final boolean root) { - StringBuffer xml = new StringBuffer(root?getHeader():""); + public String getStartTime(final UWSJob job, final boolean root){ + StringBuffer xml = new StringBuffer(root ? getHeader() : ""); xml.append("<uws:startTime").append(getUWSNamespace(root)); if (job.getStartTime() == null) xml.append(" xsi:nil=\"true\" />"); @@ -286,8 +290,8 @@ public class XMLSerializer extends UWSSerializer { } @Override - public String getEndTime(final UWSJob job, final boolean root) { - StringBuffer xml = new StringBuffer(root?getHeader():""); + public String getEndTime(final UWSJob job, final boolean root){ + StringBuffer xml = new StringBuffer(root ? getHeader() : ""); xml.append("<uws:endTime").append(getUWSNamespace(root)); if (job.getEndTime() == null) xml.append(" xsi:nil=\"true\" />"); @@ -297,8 +301,8 @@ public class XMLSerializer extends UWSSerializer { } @Override - public String getDestructionTime(final UWSJob job, final boolean root) { - StringBuffer xml = new StringBuffer(root?getHeader():""); + public String getDestructionTime(final UWSJob job, final boolean root){ + StringBuffer xml = new StringBuffer(root ? getHeader() : ""); xml.append("<uws:destruction").append(getUWSNamespace(root)); if (job.getDestructionTime() == null) xml.append(" xsi:nil=\"true\" />"); @@ -308,13 +312,13 @@ public class XMLSerializer extends UWSSerializer { } @Override - public String getExecutionDuration(final UWSJob job, final boolean root) { - return (new StringBuffer(root?getHeader():"")).append("<uws:executionDuration").append(getUWSNamespace(root)).append(">").append(job.getExecutionDuration()).append("</uws:executionDuration>").toString(); + public String getExecutionDuration(final UWSJob job, final boolean root){ + return (new StringBuffer(root ? getHeader() : "")).append("<uws:executionDuration").append(getUWSNamespace(root)).append(">").append(job.getExecutionDuration()).append("</uws:executionDuration>").toString(); } @Override - public String getErrorSummary(final ErrorSummary error, final boolean root) { - StringBuffer xml = new StringBuffer(root?getHeader():""); + public String getErrorSummary(final ErrorSummary error, final boolean root){ + StringBuffer xml = new StringBuffer(root ? getHeader() : ""); xml.append(tabPrefix).append("<uws:errorSummary").append(getUWSNamespace(root)); if (error != null){ xml.append(" type=\"").append(error.getType()).append("\"").append(" hasDetail=\"").append(error.hasDetail()).append("\">"); @@ -326,10 +330,10 @@ public class XMLSerializer extends UWSSerializer { } @Override - public String getAdditionalParameters(final UWSJob job, final boolean root) { - StringBuffer xml = new StringBuffer(root?getHeader():""); + public String getAdditionalParameters(final UWSJob job, final boolean root){ + StringBuffer xml = new StringBuffer(root ? getHeader() : ""); xml.append(tabPrefix).append("<uws:parameters").append(getUWSNamespace(root)).append(">"); - String newLine = "\n\t"+tabPrefix; + String newLine = "\n\t" + tabPrefix; for(String paramName : job.getAdditionalParameters()) xml.append(newLine).append(getAdditionalParameter(paramName, job.getAdditionalParameterValue(paramName), false)); xml.append("\n").append(tabPrefix).append("</uws:parameters>"); @@ -337,7 +341,7 @@ public class XMLSerializer extends UWSSerializer { } @Override - public String getAdditionalParameter(final String paramName, final Object paramValue, final boolean root) { + public String getAdditionalParameter(final String paramName, final Object paramValue, final boolean root){ if (paramName != null && paramValue != null){ if (root) return paramValue.toString(); @@ -348,12 +352,12 @@ public class XMLSerializer extends UWSSerializer { } @Override - public String getResults(final UWSJob job, final boolean root) { - StringBuffer xml = new StringBuffer(root?getHeader():""); + public String getResults(final UWSJob job, final boolean root){ + StringBuffer xml = new StringBuffer(root ? getHeader() : ""); xml.append(tabPrefix).append("<uws:results").append(getUWSNamespace(root)).append(">"); Iterator<Result> it = job.getResults(); - String newLine = "\n\t"+tabPrefix; + String newLine = "\n\t" + tabPrefix; while(it.hasNext()) xml.append(newLine).append(getResult(it.next(), false)); xml.append("\n").append(tabPrefix).append("</uws:results>"); @@ -361,8 +365,8 @@ public class XMLSerializer extends UWSSerializer { } @Override - public String getResult(final Result result, final boolean root) { - StringBuffer xml = new StringBuffer(root?getHeader():""); + public String getResult(final Result result, final boolean root){ + StringBuffer xml = new StringBuffer(root ? getHeader() : ""); xml.append("<uws:result").append(getUWSNamespace(root)).append(" id=\"").append(escapeXMLAttribute(result.getId())).append("\""); if (result.getHref() != null){ if (result.getType() != null) @@ -376,7 +380,6 @@ public class XMLSerializer extends UWSSerializer { return xml.append(" />").toString(); } - /* ************** */ /* ESCAPE METHODS */ /* ************** */ @@ -390,7 +393,7 @@ public class XMLSerializer extends UWSSerializer { * @return Escaped data. */ public static String escapeXMLData(final String data){ - return "<![CDATA["+data+"]]>"; + return "<![CDATA[" + data + "]]>"; } /** @@ -402,21 +405,26 @@ public class XMLSerializer extends UWSSerializer { */ public static String escapeXMLAttribute(final String value){ StringBuffer encoded = new StringBuffer(); - for(int i=0; i<value.length(); i++){ + for(int i = 0; i < value.length(); i++){ char c = value.charAt(i); switch(c){ - case '&': - encoded.append("&"); break; - case '<': - encoded.append("<"); break; - case '>': - encoded.append(">"); break; - case '"': - encoded.append("""); break; - case '\'': - encoded.append("'"); break; - default: - encoded.append(c); + case '&': + encoded.append("&"); + break; + case '<': + encoded.append("<"); + break; + case '>': + encoded.append(">"); + break; + case '"': + encoded.append("""); + break; + case '\'': + encoded.append("'"); + break; + default: + encoded.append(c); } } return encoded.toString(); @@ -433,9 +441,9 @@ public class XMLSerializer extends UWSSerializer { * @see #escapeXMLAttribute(String) */ public static String escapeURL(final String url){ - try { + try{ return URLEncoder.encode(url, "UTF-8"); - } catch (UnsupportedEncodingException e) { + }catch(UnsupportedEncodingException e){ return escapeXMLAttribute(url); } } diff --git a/src/uws/job/user/DefaultJobOwner.java b/src/uws/job/user/DefaultJobOwner.java index d410c9d07137adf58fc5f68eb2b7156e57e208dd..eaf7400a1227b33ca3c5d615bdbb495da544eed8 100644 --- a/src/uws/job/user/DefaultJobOwner.java +++ b/src/uws/job/user/DefaultJobOwner.java @@ -42,7 +42,7 @@ public final class DefaultJobOwner implements JobOwner { private final String id; private String pseudo; - private HashMap<String, Object> otherData = null; + private HashMap<String,Object> otherData = null; /** * Builds a Job Owner which has the given ID. @@ -60,12 +60,12 @@ public final class DefaultJobOwner implements JobOwner { } @Override - public final String getID() { + public final String getID(){ return id; } @Override - public final String getPseudo() { + public final String getPseudo(){ return pseudo; } @@ -78,7 +78,7 @@ public final class DefaultJobOwner implements JobOwner { * @see uws.job.user.JobOwner#hasReadPermission(uws.job.JobList) */ @Override - public boolean hasReadPermission(JobList jl) { + public boolean hasReadPermission(JobList jl){ return true; } @@ -87,7 +87,7 @@ public final class DefaultJobOwner implements JobOwner { * @see uws.job.user.JobOwner#hasWritePermission(uws.job.JobList) */ @Override - public boolean hasWritePermission(JobList jl) { + public boolean hasWritePermission(JobList jl){ return true; } @@ -96,7 +96,7 @@ public final class DefaultJobOwner implements JobOwner { * @see uws.job.user.JobOwner#hasReadPermission(uws.job.UWSJob) */ @Override - public boolean hasReadPermission(UWSJob job) { + public boolean hasReadPermission(UWSJob job){ return (job == null) || (job.getOwner() == null) || (job.getOwner().equals(this)); } @@ -105,7 +105,7 @@ public final class DefaultJobOwner implements JobOwner { * @see uws.job.user.JobOwner#hasWritePermission(uws.job.UWSJob) */ @Override - public boolean hasWritePermission(UWSJob job) { + public boolean hasWritePermission(UWSJob job){ return (job == null) || (job.getOwner() == null) || (job.getOwner().equals(this)); } @@ -114,13 +114,13 @@ public final class DefaultJobOwner implements JobOwner { * @see uws.job.user.JobOwner#hasExecutePermission(uws.job.UWSJob) */ @Override - public boolean hasExecutePermission(UWSJob job) { + public boolean hasExecutePermission(UWSJob job){ return (job == null) || (job.getOwner() == null) || (job.getOwner().equals(this)); } public String putUserData(final String name, final String value){ if (otherData == null) - otherData = new HashMap<String, Object>(); + otherData = new HashMap<String,Object>(); return (String)otherData.put(name, value); } @@ -137,17 +137,17 @@ public final class DefaultJobOwner implements JobOwner { } @Override - public Map<String, Object> getDataToSave() { + public Map<String,Object> getDataToSave(){ return otherData; } @Override - public void restoreData(Map<String, Object> data) { + public void restoreData(Map<String,Object> data){ if (data == null || data.isEmpty()) return; if (otherData == null) - otherData = new HashMap<String, Object>(data.size()); + otherData = new HashMap<String,Object>(data.size()); otherData.putAll(data); } @@ -166,7 +166,7 @@ public final class DefaultJobOwner implements JobOwner { * @see java.lang.Object#equals(java.lang.Object) */ @Override - public boolean equals(Object obj) { + public boolean equals(Object obj){ if (obj == null || !(obj instanceof JobOwner)) return false; @@ -179,7 +179,7 @@ public final class DefaultJobOwner implements JobOwner { * @see java.lang.Object#hashCode() */ @Override - public int hashCode() { + public int hashCode(){ return id.hashCode(); } diff --git a/src/uws/job/user/JobOwner.java b/src/uws/job/user/JobOwner.java index 641bcf2ddb541b9d7dfe640a63291de68d5fbda9..b2a81d25ab3f85596c8c08f277c9bb35fdb7b8b7 100644 --- a/src/uws/job/user/JobOwner.java +++ b/src/uws/job/user/JobOwner.java @@ -101,13 +101,13 @@ public interface JobOwner { * * @return A map with some key/value pairs, <i>null</i> or an empty map if no additional user data. */ - public Map<String, Object> getDataToSave(); + public Map<String,Object> getDataToSave(); /** * Restores any additional user data from the given map. * * @param data A map with some key/value pairs, <i>null</i> or an empty map if no additional user data. */ - public void restoreData(final Map<String, Object> data); + public void restoreData(final Map<String,Object> data); } diff --git a/src/uws/service/AbstractUWSFactory.java b/src/uws/service/AbstractUWSFactory.java index 2d7a635112d488c68ab5470d59c98b7e30e4183f..04fbe8a5e18c9fbe76fef551e03bab0a00edccee 100644 --- a/src/uws/service/AbstractUWSFactory.java +++ b/src/uws/service/AbstractUWSFactory.java @@ -42,7 +42,6 @@ import uws.job.parameters.DestructionTimeController.DateField; import uws.job.user.JobOwner; - /** * <p>Abstract implementation of {@link UWSFactory}. * Only the function which creates a {@link JobThread} from a {@link UWSJob} needs to be implemented.</p> @@ -53,12 +52,14 @@ import uws.job.user.JobOwner; public abstract class AbstractUWSFactory implements UWSFactory { /** List the controllers of all the input parameters. See {@link UWSParameters} and {@link InputParamController} for more details. */ - protected final HashMap<String, InputParamController> inputParamControllers = new HashMap<String, InputParamController>(10); + protected final HashMap<String,InputParamController> inputParamControllers = new HashMap<String,InputParamController>(10); /** List of all expected additional parameters. */ protected final ArrayList<String> expectedAdditionalParams = new ArrayList<String>(10); - public AbstractUWSFactory(){ ; } + public AbstractUWSFactory(){ + ; + } /** * Builds a factory with a list of the name of all expected additional parameters. @@ -81,22 +82,22 @@ public abstract class AbstractUWSFactory implements UWSFactory { /* ***************** */ @Override - public UWSJob createJob(final HttpServletRequest request, final JobOwner user) throws UWSException { + public UWSJob createJob(final HttpServletRequest request, final JobOwner user) throws UWSException{ return new UWSJob(user, createUWSParameters(request)); } @Override - public UWSJob createJob(String jobID, JobOwner owner, UWSParameters params, long quote, long startTime, long endTime, List<Result> results, ErrorSummary error) throws UWSException { + public UWSJob createJob(String jobID, JobOwner owner, UWSParameters params, long quote, long startTime, long endTime, List<Result> results, ErrorSummary error) throws UWSException{ return new UWSJob(jobID, owner, params, quote, startTime, endTime, results, error); } @Override - public UWSParameters createUWSParameters(final Map<String, Object> params) throws UWSException { + public UWSParameters createUWSParameters(final Map<String,Object> params) throws UWSException{ return new UWSParameters(params, expectedAdditionalParams, inputParamControllers); } @Override - public UWSParameters createUWSParameters(final HttpServletRequest req) throws UWSException { + public UWSParameters createUWSParameters(final HttpServletRequest req) throws UWSException{ return new UWSParameters(req, expectedAdditionalParams, inputParamControllers); } @@ -155,7 +156,7 @@ public abstract class AbstractUWSFactory implements UWSFactory { * Gets the list of all UWS input parameter controllers. * @return All parameter controllers. */ - public final Map<String, InputParamController> getInputParamControllers(){ + public final Map<String,InputParamController> getInputParamControllers(){ return inputParamControllers; } @@ -163,7 +164,7 @@ public abstract class AbstractUWSFactory implements UWSFactory { * Gets an iterator on the list of all UWS input parameter controllers. * @return An iterator on all parameter controllers. */ - public final Iterator<Map.Entry<String, InputParamController>> getInputParamControllersIterator(){ + public final Iterator<Map.Entry<String,InputParamController>> getInputParamControllersIterator(){ return inputParamControllers.entrySet().iterator(); } diff --git a/src/uws/service/UWS.java b/src/uws/service/UWS.java index 0c7bdb4a020ddbb0f5e25e0ad00e35b287ecec1f..492b17b668b2f33c1c74eadd8c2fcdec64bf679f 100644 --- a/src/uws/service/UWS.java +++ b/src/uws/service/UWS.java @@ -78,7 +78,6 @@ public interface UWS extends Iterable<JobList> { */ public String getDescription(); - /* ******************* */ /* JOB LIST MANAGEMENT */ /* ******************* */ @@ -132,7 +131,6 @@ public interface UWS extends Iterable<JobList> { */ public boolean destroyJobList(final String name) throws UWSException; - /* **************************** */ /* JOB SERIALIZATION MANAGEMENT */ /* **************************** */ @@ -152,7 +150,6 @@ public interface UWS extends Iterable<JobList> { */ public UWSSerializer getSerializer(final String mimeTypes) throws UWSException; - /* ******************* */ /* UWS URL INTERPRETER */ /* ******************* */ @@ -167,7 +164,6 @@ public interface UWS extends Iterable<JobList> { */ public UWSUrl getUrlInterpreter(); - /* ************** */ /* LOG MANAGEMENT */ /* ************** */ @@ -182,7 +178,6 @@ public interface UWS extends Iterable<JobList> { */ public UWSLog getLogger(); - /* ******************* */ /* USER IDENTIFICATION */ /* ******************* */ @@ -193,7 +188,6 @@ public interface UWS extends Iterable<JobList> { */ public UserIdentifier getUserIdentifier(); - /* *********** */ /* JOB FACTORY */ /* *********** */ @@ -208,7 +202,6 @@ public interface UWS extends Iterable<JobList> { */ public UWSFactory getFactory(); - /* *************** */ /* FILE MANAGEMENT */ /* *************** */ @@ -222,7 +215,6 @@ public interface UWS extends Iterable<JobList> { */ public UWSFileManager getFileManager(); - /* ***************** */ /* BACKUP MANAGEMENT */ /* ***************** */ diff --git a/src/uws/service/UWSFactory.java b/src/uws/service/UWSFactory.java index e416dc606e563c1a453400c0ccd64df3e0c2c5a8..4cf384c1b5b4078879419414dfba1ff35123797a 100644 --- a/src/uws/service/UWSFactory.java +++ b/src/uws/service/UWSFactory.java @@ -112,6 +112,6 @@ public interface UWSFactory { * * @throws UWSException If an error occurs while extracting parameters. */ - public UWSParameters createUWSParameters(final Map<String, Object> params) throws UWSException; + public UWSParameters createUWSParameters(final Map<String,Object> params) throws UWSException; } diff --git a/src/uws/service/UWSService.java b/src/uws/service/UWSService.java index d0d1eb5fcd4972224f5d83ffbc5a31fbe2e81256..b6555c83a963b685ac64a62cb7de12a54d8d389e 100644 --- a/src/uws/service/UWSService.java +++ b/src/uws/service/UWSService.java @@ -195,13 +195,13 @@ public class UWSService implements UWS { protected String description = null; /** List of all managed jobs lists. <i>(it is a LinkedHashMap so that jobs lists are ordered by insertion)</i> */ - protected final Map<String, JobList> mapJobLists; + protected final Map<String,JobList> mapJobLists; /** The "interpreter" of UWS URLs. */ protected UWSUrl urlInterpreter = null; /** List of available serializers. */ - protected final Map<String, UWSSerializer> serializers; + protected final Map<String,UWSSerializer> serializers; /** The MIME type of the default serialization format. */ protected String defaultSerializer = null; @@ -239,30 +239,30 @@ public class UWSService implements UWS { /** Lets writing/formatting any exception/throwable in a HttpServletResponse. */ protected ServiceErrorWriter errorWriter; - /* ************ */ /* CONSTRUCTORS */ /* ************ *//** - * <p>Builds a UWS (the base URI will be extracted at the first request directly from the request itself).</p> - * - * <p> - * By default, this UWS has 2 serialization formats: XML ({@link XMLSerializer}) and JSON ({@link JSONSerializer}). - * All the default actions of a UWS are also already implemented. - * However, you still have to create at least one job list ! - * </p> - * - * <p><i><u>note:</u> since no logger is provided, a default one is set automatically (see {@link DefaultUWSLog}).</i></p> - * - * @param jobFactory Object which lets creating the UWS jobs managed by this UWS and their thread/task. - * @param fileManager Object which lets managing all files managed by this UWS (i.e. log, result, backup, error, ...). - * - * @throws NullPointerException If at least one of the parameters is <i>null</i>. - * - * @see #UWSService(UWSFactory, UWSFileManager, UWSLog) - */ - public UWSService(final UWSFactory jobFactory, final UWSFileManager fileManager) { + * <p>Builds a UWS (the base URI will be extracted at the first request directly from the request itself).</p> + * + * <p> + * By default, this UWS has 2 serialization formats: XML ({@link XMLSerializer}) and JSON ({@link JSONSerializer}). + * All the default actions of a UWS are also already implemented. + * However, you still have to create at least one job list ! + * </p> + * + * <p><i><u>note:</u> since no logger is provided, a default one is set automatically (see {@link DefaultUWSLog}).</i></p> + * + * @param jobFactory Object which lets creating the UWS jobs managed by this UWS and their thread/task. + * @param fileManager Object which lets managing all files managed by this UWS (i.e. log, result, backup, error, ...). + * + * @throws NullPointerException If at least one of the parameters is <i>null</i>. + * + * @see #UWSService(UWSFactory, UWSFileManager, UWSLog) + */ + public UWSService(final UWSFactory jobFactory, final UWSFileManager fileManager){ this(jobFactory, fileManager, (UWSLog)null); } + /** * <p>Builds a UWS (the base URI will be extracted at the first request directly from the request itself).</p> * @@ -278,7 +278,7 @@ public class UWSService implements UWS { * * @throws NullPointerException If at least one of the parameters is <i>null</i>. */ - public UWSService(final UWSFactory jobFactory, final UWSFileManager fileManager, final UWSLog logger) { + public UWSService(final UWSFactory jobFactory, final UWSFileManager fileManager, final UWSLog logger){ if (jobFactory == null) throw new NullPointerException("Missing UWS factory ! Can not create a UWSService."); factory = jobFactory; @@ -291,10 +291,10 @@ public class UWSService implements UWS { errorWriter = new DefaultUWSErrorWriter(this); // Initialize the list of jobs: - mapJobLists = new LinkedHashMap<String, JobList>(); + mapJobLists = new LinkedHashMap<String,JobList>(); // Initialize the list of available serializers: - serializers = new HashMap<String, UWSSerializer>(); + serializers = new HashMap<String,UWSSerializer>(); addSerializer(new XMLSerializer()); addSerializer(new JSONSerializer()); @@ -324,7 +324,7 @@ public class UWSService implements UWS { * * @see #UWSService(UWSFactory, UWSFileManager, UWSLog, String) */ - public UWSService(final UWSFactory jobFactory, final UWSFileManager fileManager, final String baseURI) throws UWSException { + public UWSService(final UWSFactory jobFactory, final UWSFileManager fileManager, final String baseURI) throws UWSException{ this(jobFactory, fileManager, null, baseURI); } @@ -340,7 +340,7 @@ public class UWSService implements UWS { * * @see UWSUrl#UWSUrl(String) */ - public UWSService(final UWSFactory jobFactory, final UWSFileManager fileManager, final UWSLog logger, final String baseURI) throws UWSException { + public UWSService(final UWSFactory jobFactory, final UWSFileManager fileManager, final UWSLog logger, final String baseURI) throws UWSException{ this(jobFactory, fileManager, logger); // Extract the name of the UWS: @@ -349,7 +349,7 @@ public class UWSService implements UWS { name = urlInterpreter.getUWSName(); getLogger().uwsInitialized(this); }catch(UWSException ex){ - throw new UWSException(UWSException.BAD_REQUEST, ex, "Invalid base UWS URI ("+baseURI+") !"); + throw new UWSException(UWSException.BAD_REQUEST, ex, "Invalid base UWS URI (" + baseURI + ") !"); } } @@ -364,7 +364,7 @@ public class UWSService implements UWS { * * @see #UWSService(UWSFactory, UWSFileManager, UWSLog, UWSUrl) */ - public UWSService(final UWSFactory jobFactory, final UWSFileManager fileManager, final UWSUrl urlInterpreter) { + public UWSService(final UWSFactory jobFactory, final UWSFileManager fileManager, final UWSUrl urlInterpreter){ this(jobFactory, fileManager, null, urlInterpreter); } @@ -376,7 +376,7 @@ public class UWSService implements UWS { * @param logger Object which lets printing any message (error, info, debug, warning). * @param urlInterpreter The UWS URL interpreter to use in this UWS. */ - public UWSService(final UWSFactory jobFactory, final UWSFileManager fileManager, final UWSLog logger, final UWSUrl urlInterpreter) { + public UWSService(final UWSFactory jobFactory, final UWSFileManager fileManager, final UWSLog logger, final UWSUrl urlInterpreter){ this(jobFactory, fileManager, logger); setUrlInterpreter(urlInterpreter); if (this.urlInterpreter != null) @@ -395,7 +395,7 @@ public class UWSService implements UWS { * * @return The error writer/formatter. */ - public final ServiceErrorWriter getErrorWriter() { + public final ServiceErrorWriter getErrorWriter(){ return errorWriter; } @@ -406,16 +406,15 @@ public class UWSService implements UWS { * * @param errorWriter The new error writer/formatter. */ - public final void setErrorWriter(ServiceErrorWriter errorWriter) { + public final void setErrorWriter(ServiceErrorWriter errorWriter){ if (errorWriter != null) this.errorWriter = errorWriter; } - /* ***************** */ /* GETTERS & SETTERS */ /* ***************** */ - public final String getName() { + public final String getName(){ return name; } @@ -428,7 +427,7 @@ public class UWSService implements UWS { this.name = name; } - public final String getDescription() { + public final String getDescription(){ return description; } @@ -437,7 +436,7 @@ public class UWSService implements UWS { * * @param description Its new description. */ - public final void setDescription(String description) { + public final void setDescription(String description){ this.description = description; } @@ -494,7 +493,7 @@ public class UWSService implements UWS { return fileManager; } - public final UWSBackupManager getBackupManager() { + public final UWSBackupManager getBackupManager(){ return backupManager; } @@ -506,7 +505,7 @@ public class UWSService implements UWS { * * @param backupManager Its new backup manager. */ - public final void setBackupManager(final UWSBackupManager backupManager) { + public final void setBackupManager(final UWSBackupManager backupManager){ this.backupManager = backupManager; } @@ -593,7 +592,7 @@ public class UWSService implements UWS { * * @throws UWSException If there is no serializer with this MIME type available in this UWS. */ - public final void setDefaultSerializer(String mimeType) throws UWSException { + public final void setDefaultSerializer(String mimeType) throws UWSException{ if (serializers.containsKey(mimeType)) defaultSerializer = mimeType; else @@ -647,7 +646,7 @@ public class UWSService implements UWS { return serializers.values().iterator(); } - public final UWSSerializer getSerializer(String mimeTypes) throws UWSException { + public final UWSSerializer getSerializer(String mimeTypes) throws UWSException{ choosenSerializer = null; if (mimeTypes != null){ @@ -656,7 +655,7 @@ public class UWSService implements UWS { ArrayList<String> lstMimeTypes = accept.getOrderedMimeTypes(); // Try each of them and stop at the first which match with an existing serializer: - for(int i=0; choosenSerializer == null && i<lstMimeTypes.size(); i++) + for(int i = 0; choosenSerializer == null && i < lstMimeTypes.size(); i++) choosenSerializer = serializers.get(lstMimeTypes.get(i)); } @@ -664,7 +663,7 @@ public class UWSService implements UWS { if (choosenSerializer == null){ choosenSerializer = serializers.get(defaultSerializer); if (choosenSerializer == null) - throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, "No UWS Serializer available neither for \""+mimeTypes+"\" (given MIME types) nor \""+defaultSerializer+"\" (default serializer MIME type) !"); + throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, "No UWS Serializer available neither for \"" + mimeTypes + "\" (given MIME types) nor \"" + defaultSerializer + "\" (default serializer MIME type) !"); } return choosenSerializer; @@ -759,8 +758,8 @@ public class UWSService implements UWS { try{ jl.setUWS(this); mapJobLists.put(jl.getName(), jl); - }catch (IllegalStateException ise){ - logger.error("The jobs list \""+jl.getName()+"\" can not be added into the UWS "+getName()+" !", ise); + }catch(IllegalStateException ise){ + logger.error("The jobs list \"" + jl.getName() + "\" can not be added into the UWS " + getName() + " !", ise); return false; } @@ -812,7 +811,7 @@ public class UWSService implements UWS { * @see JobList#clear() * @see JobList#setUWS(UWSService) */ - public boolean destroyJobList(JobList jl) { + public boolean destroyJobList(JobList jl){ if (jl == null) return false; @@ -822,7 +821,7 @@ public class UWSService implements UWS { jl.clear(); jl.setUWS(null); }catch(IllegalStateException ise){ - getLogger().warning("Impossible to erase completely the association between the jobs list \""+jl.getName()+"\" and the UWS \""+getName()+"\", because: "+ise.getMessage()); + getLogger().warning("Impossible to erase completely the association between the jobs list \"" + jl.getName() + "\" and the UWS \"" + getName() + "\", because: " + ise.getMessage()); } } return jl != null; @@ -880,7 +879,7 @@ public class UWSService implements UWS { * * @throws ArrayIndexOutOfBoundsException If the given index is incorrect (index < 0 || index >= uwsActions.size()). */ - public final boolean addUWSAction(int indAction, UWSAction action) throws ArrayIndexOutOfBoundsException { + public final boolean addUWSAction(int indAction, UWSAction action) throws ArrayIndexOutOfBoundsException{ if (!uwsActions.contains(action)){ uwsActions.add(indAction, action); return true; @@ -898,7 +897,7 @@ public class UWSService implements UWS { * * @throws ArrayIndexOutOfBoundsException If the index is incorrect (index < 0 || index >= uwsActions.size()). */ - public final boolean setUWSAction(int indAction, UWSAction action) throws ArrayIndexOutOfBoundsException { + public final boolean setUWSAction(int indAction, UWSAction action) throws ArrayIndexOutOfBoundsException{ if (!uwsActions.contains(action)){ uwsActions.set(indAction, action); return true; @@ -919,7 +918,7 @@ public class UWSService implements UWS { if (action == null) return null; else{ - for(int i=0; i<uwsActions.size(); i++){ + for(int i = 0; i < uwsActions.size(); i++){ if (uwsActions.get(i).equals(action)) return uwsActions.set(i, action); } @@ -945,7 +944,7 @@ public class UWSService implements UWS { * or <i>null</i> if there is no corresponding action. */ public final UWSAction getUWSAction(String actionName){ - for(int i=0; i<uwsActions.size(); i++){ + for(int i = 0; i < uwsActions.size(); i++){ if (uwsActions.get(i).getName().equals(actionName)) return uwsActions.get(i); } @@ -979,7 +978,7 @@ public class UWSService implements UWS { * * @throws ArrayIndexOutOfBoundsException If the given index is incorrect (index < 0 || index >= uwsActions.size()). */ - public final UWSAction removeUWSAction(int indAction) throws ArrayIndexOutOfBoundsException { + public final UWSAction removeUWSAction(int indAction) throws ArrayIndexOutOfBoundsException{ return uwsActions.remove(indAction); } @@ -991,7 +990,7 @@ public class UWSService implements UWS { * or <i>null</i> if there is no corresponding action. */ public final UWSAction removeUWSAction(String actionName){ - for(int i=0; i<uwsActions.size(); i++){ + for(int i = 0; i < uwsActions.size(); i++){ if (uwsActions.get(i).getName().equals(actionName)) return uwsActions.remove(i); } @@ -1027,7 +1026,7 @@ public class UWSService implements UWS { * @see UWSAction#match(UWSUrl, String, HttpServletRequest) * @see UWSAction#apply(UWSUrl, String, HttpServletRequest, HttpServletResponse) */ - public boolean executeRequest(HttpServletRequest request, HttpServletResponse response) throws UWSException, IOException { + public boolean executeRequest(HttpServletRequest request, HttpServletResponse response) throws UWSException, IOException{ if (request == null || response == null) return false; @@ -1044,10 +1043,10 @@ public class UWSService implements UWS { urlInterpreter.load(request); // Identify the user: - user = (userIdentifier == null)?null:userIdentifier.extractUserId(urlInterpreter, request); + user = (userIdentifier == null) ? null : userIdentifier.extractUserId(urlInterpreter, request); // Apply the appropriate UWS action: - for(int i=0; action == null && i<uwsActions.size(); i++){ + for(int i = 0; action == null && i < uwsActions.size(); i++){ if (uwsActions.get(i).match(urlInterpreter, user, request)){ action = uwsActions.get(i); choosenSerializer = null; @@ -1060,14 +1059,14 @@ public class UWSService implements UWS { throw new UWSException(UWSException.NOT_IMPLEMENTED, "Unknown UWS action ! This HTTP request can not be interpreted by this UWS service !"); response.flushBuffer(); - logger.httpRequest(request, user, (action != null)?action.getName():null, HttpServletResponse.SC_OK, "[OK]", null); + logger.httpRequest(request, user, (action != null) ? action.getName() : null, HttpServletResponse.SC_OK, "[OK]", null); }catch(UWSException ex){ if (ex.getHttpErrorCode() == UWSException.SEE_OTHER) actionApplied = true; - sendError(ex, request, user, (action != null)?action.getName():null, response); + sendError(ex, request, user, (action != null) ? action.getName() : null, response); }catch(Exception ex){ - sendError(ex, request, user, (action != null)?action.getName():null, response); + sendError(ex, request, user, (action != null) ? action.getName() : null, response); }finally{ executedAction = action; } @@ -1087,12 +1086,12 @@ public class UWSService implements UWS { * @throws IOException If there is an error during the redirection. * @throws UWSException If there is any other error. */ - public void redirect(String url, HttpServletRequest request, JobOwner user, String uwsAction, HttpServletResponse response) throws IOException, UWSException { + public void redirect(String url, HttpServletRequest request, JobOwner user, String uwsAction, HttpServletResponse response) throws IOException, UWSException{ response.setStatus(HttpServletResponse.SC_SEE_OTHER); response.setContentType(request.getContentType()); response.setHeader("Location", url); response.flushBuffer(); - logger.httpRequest(request, user, uwsAction, HttpServletResponse.SC_SEE_OTHER, "[Redirection toward "+url+"]", null); + logger.httpRequest(request, user, uwsAction, HttpServletResponse.SC_SEE_OTHER, "[Redirection toward " + url + "]", null); } /** @@ -1114,7 +1113,7 @@ public class UWSService implements UWS { * @see #redirect(String, HttpServletRequest, JobOwner, String, HttpServletResponse) * @see {@link ServiceErrorWriter#writeError(Throwable, HttpServletResponse, HttpServletRequest, JobOwner, String)} */ - public final void sendError(UWSException error, HttpServletRequest request, JobOwner user, String uwsAction, HttpServletResponse response) throws IOException, UWSException { + public final void sendError(UWSException error, HttpServletRequest request, JobOwner user, String uwsAction, HttpServletResponse response) throws IOException, UWSException{ if (error.getHttpErrorCode() == UWSException.SEE_OTHER) redirect(error.getMessage(), request, user, uwsAction, response); else{ @@ -1146,7 +1145,7 @@ public class UWSService implements UWS { * * @see {@link ServiceErrorWriter#writeError(Throwable, HttpServletResponse, HttpServletRequest, JobOwner, String)} */ - public final void sendError(Exception error, HttpServletRequest request, JobOwner user, String uwsAction, HttpServletResponse response) throws IOException, UWSException { + public final void sendError(Exception error, HttpServletRequest request, JobOwner user, String uwsAction, HttpServletResponse response) throws IOException, UWSException{ errorWriter.writeError(error, response, request, user, uwsAction); /*logger.error(error); response.sendError(UWSException.INTERNAL_SERVER_ERROR, error.getMessage()); diff --git a/src/uws/service/UWSServlet.java b/src/uws/service/UWSServlet.java index a80a83d56d9274907f987ab43b6d8eb3036c9cd1..bacb48034a2d9288e97467f24ed830c0407157e4 100644 --- a/src/uws/service/UWSServlet.java +++ b/src/uws/service/UWSServlet.java @@ -70,7 +70,6 @@ import uws.service.actions.UWSAction; import uws.service.backup.UWSBackupManager; - import uws.service.error.DefaultUWSErrorWriter; import uws.service.error.ServiceErrorWriter; import uws.service.file.LocalUWSFileManager; @@ -145,10 +144,10 @@ public abstract class UWSServlet extends HttpServlet implements UWS, UWSFactory protected String description = null; /** List of all managed jobs lists. <i>(it is a LinkedHashMap so that jobs lists are ordered by insertion)</i> */ - private Map<String, JobList> mapJobLists; + private Map<String,JobList> mapJobLists; /** List of available serializers. */ - private Map<String, UWSSerializer> serializers; + private Map<String,UWSSerializer> serializers; /** The MIME type of the default serialization format. */ protected String defaultSerializer = null; @@ -163,7 +162,7 @@ public abstract class UWSServlet extends HttpServlet implements UWS, UWSFactory protected final ArrayList<String> expectedAdditionalParams = new ArrayList<String>(10); /** List the controllers of all the input parameters. See {@link UWSParameters} and {@link InputParamController} for more details. */ - protected final HashMap<String, InputParamController> inputParamControllers = new HashMap<String, InputParamController>(10); + protected final HashMap<String,InputParamController> inputParamControllers = new HashMap<String,InputParamController>(10); /** Lets managing all UWS files (i.e. log, result, backup, ...). */ private UWSFileManager fileManager = null; @@ -177,14 +176,13 @@ public abstract class UWSServlet extends HttpServlet implements UWS, UWSFactory /** Lets writing/formatting any exception/throwable in a HttpServletResponse. */ protected ServiceErrorWriter errorWriter; - @Override - public final void init(ServletConfig config) throws ServletException { + public final void init(ServletConfig config) throws ServletException{ super.init(config); } @Override - public final void init() throws ServletException { + public final void init() throws ServletException{ // Set the general information about this UWS: name = getServletConfig().getInitParameter("name"); description = getServletConfig().getInitParameter("description"); @@ -203,10 +201,10 @@ public abstract class UWSServlet extends HttpServlet implements UWS, UWSFactory errorWriter = new DefaultUWSErrorWriter(this); // Initialize the list of jobs: - mapJobLists = new LinkedHashMap<String, JobList>(); + mapJobLists = new LinkedHashMap<String,JobList>(); // Initialize the list of available serializers: - serializers = new HashMap<String, UWSSerializer>(); + serializers = new HashMap<String,UWSSerializer>(); addSerializer(new XMLSerializer()); addSerializer(new JSONSerializer()); @@ -221,30 +219,30 @@ public abstract class UWSServlet extends HttpServlet implements UWS, UWSFactory public abstract void initUWS() throws UWSException; - public UWSFileManager createFileManager() throws UWSException { + public UWSFileManager createFileManager() throws UWSException{ UWSFileManager fm = null; String rootPath = getServletConfig().getInitParameter("rootDirectory"); if (rootPath == null || rootPath.trim().isEmpty()) - rootPath = ((name!=null && !name.trim().isEmpty())?name.replaceAll("/", "_"):"")+"_files"; + rootPath = ((name != null && !name.trim().isEmpty()) ? name.replaceAll("/", "_") : "") + "_files"; if (rootPath.startsWith("/")) fm = new LocalUWSFileManager(new File(rootPath)); else - fm = new LocalUWSFileManager(new File(getServletContext().getRealPath("/"+rootPath))); + fm = new LocalUWSFileManager(new File(getServletContext().getRealPath("/" + rootPath))); return fm; } @Override - public UWSFileManager getFileManager() { + public UWSFileManager getFileManager(){ return fileManager; } @Override - public final void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException { + public final void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException{ super.service(req, resp); } @Override - protected final void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + protected final void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ String uwsAction = null; JobOwner user = null; @@ -263,7 +261,7 @@ public abstract class UWSServlet extends HttpServlet implements UWS, UWSFactory user = (userIdentifier == null) ? null : userIdentifier.extractUserId(requestUrl, req); // METHOD GET: - if (method.equals("GET")) { + if (method.equals("GET")){ // HOME PAGE: if (!requestUrl.hasJobList()){ uwsAction = UWSAction.HOME_PAGE; @@ -321,10 +319,7 @@ public abstract class UWSServlet extends HttpServlet implements UWS, UWSFactory }// METHOD PUT: else if (method.equals("PUT")){ // SET JOB PARAMETER: - if (requestUrl.hasJobList() && requestUrl.hasJob() && req.getMethod().equalsIgnoreCase("put") - && requestUrl.getAttributes().length >= 2 - && requestUrl.getAttributes()[0].equalsIgnoreCase(UWSJob.PARAM_PARAMETERS) - && req.getParameter(requestUrl.getAttributes()[1]) != null){ + if (requestUrl.hasJobList() && requestUrl.hasJob() && req.getMethod().equalsIgnoreCase("put") && requestUrl.getAttributes().length >= 2 && requestUrl.getAttributes()[0].equalsIgnoreCase(UWSJob.PARAM_PARAMETERS) && req.getParameter(requestUrl.getAttributes()[1]) != null){ uwsAction = UWSAction.SET_JOB_PARAM; doSetJobParam(requestUrl, req, resp, user); @@ -372,7 +367,7 @@ public abstract class UWSServlet extends HttpServlet implements UWS, UWSFactory /* *********** */ /* UWS ACTIONS */ /* *********** */ - protected void writeHomePage(UWSUrl requestUrl, HttpServletRequest req, HttpServletResponse resp, JobOwner user) throws UWSException, ServletException, IOException { + protected void writeHomePage(UWSUrl requestUrl, HttpServletRequest req, HttpServletResponse resp, JobOwner user) throws UWSException, ServletException, IOException{ UWSSerializer serializer = getSerializer(req.getHeader("Accept")); resp.setContentType(serializer.getMimeType()); String serialization = serializer.getUWS(this); @@ -381,10 +376,10 @@ public abstract class UWSServlet extends HttpServlet implements UWS, UWSFactory output.print(serialization); output.flush(); }else - throw UWSExceptionFactory.incorrectSerialization(serialization, "the UWS "+getName()); + throw UWSExceptionFactory.incorrectSerialization(serialization, "the UWS " + getName()); } - protected void doListJob(UWSUrl requestUrl, HttpServletRequest req, HttpServletResponse resp, JobOwner user) throws UWSException, ServletException, IOException { + protected void doListJob(UWSUrl requestUrl, HttpServletRequest req, HttpServletResponse resp, JobOwner user) throws UWSException, ServletException, IOException{ // Get the jobs list: JobList jobsList = getJobList(requestUrl.getJobListName()); @@ -394,7 +389,7 @@ public abstract class UWSServlet extends HttpServlet implements UWS, UWSFactory jobsList.serialize(resp.getOutputStream(), serializer, user); } - protected void doAddJob(UWSUrl requestUrl, HttpServletRequest req, HttpServletResponse resp, JobOwner user) throws UWSException, ServletException, IOException { + protected void doAddJob(UWSUrl requestUrl, HttpServletRequest req, HttpServletResponse resp, JobOwner user) throws UWSException, ServletException, IOException{ // Get the jobs list: JobList jobsList = getJobList(requestUrl.getJobListName()); @@ -410,10 +405,10 @@ public abstract class UWSServlet extends HttpServlet implements UWS, UWSFactory // Make a redirection to the added job: redirect(requestUrl.jobSummary(jobsList.getName(), newJob.getJobId()).getRequestURL(), req, user, UWSAction.ADD_JOB, resp); }else - throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, "Unable to add the new job "+newJob.getJobId()+" to the jobs list "+jobsList.getName()+". (ID already used = "+(jobsList.getJob(newJob.getJobId())!=null)+")"); + throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, "Unable to add the new job " + newJob.getJobId() + " to the jobs list " + jobsList.getName() + ". (ID already used = " + (jobsList.getJob(newJob.getJobId()) != null) + ")"); } - protected void doDestroyJob(UWSUrl requestUrl, HttpServletRequest req, HttpServletResponse resp, JobOwner user) throws UWSException, ServletException, IOException { + protected void doDestroyJob(UWSUrl requestUrl, HttpServletRequest req, HttpServletResponse resp, JobOwner user) throws UWSException, ServletException, IOException{ // Get the jobs list: JobList jobsList = getJobList(requestUrl.getJobListName()); @@ -424,7 +419,7 @@ public abstract class UWSServlet extends HttpServlet implements UWS, UWSFactory redirect(requestUrl.listJobs(jobsList.getName()).getRequestURL(), req, user, UWSAction.DESTROY_JOB, resp); } - protected void doJobSummary(UWSUrl requestUrl, HttpServletRequest req, HttpServletResponse resp, JobOwner user) throws UWSException, ServletException, IOException { + protected void doJobSummary(UWSUrl requestUrl, HttpServletRequest req, HttpServletResponse resp, JobOwner user) throws UWSException, ServletException, IOException{ // Get the job: UWSJob job = getJob(requestUrl); @@ -434,7 +429,7 @@ public abstract class UWSServlet extends HttpServlet implements UWS, UWSFactory job.serialize(resp.getOutputStream(), serializer, user); } - protected void doGetJobParam(UWSUrl requestUrl, HttpServletRequest req, HttpServletResponse resp, JobOwner user) throws UWSException, ServletException, IOException { + protected void doGetJobParam(UWSUrl requestUrl, HttpServletRequest req, HttpServletResponse resp, JobOwner user) throws UWSException, ServletException, IOException{ // Get the job: UWSJob job = getJob(requestUrl, user); @@ -453,7 +448,7 @@ public abstract class UWSServlet extends HttpServlet implements UWS, UWSFactory input = getFileManager().getResultInput(result, job); UWSToolBox.write(input, result.getMimeType(), result.getSize(), resp); }catch(IOException ioe){ - throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, ioe, "Can not read the content of the result "+result.getId()+" (job ID: "+job.getJobId()+")."); + throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, ioe, "Can not read the content of the result " + result.getId() + " (job ID: " + job.getJobId() + ")."); }finally{ if (input != null) input.close(); @@ -470,7 +465,7 @@ public abstract class UWSServlet extends HttpServlet implements UWS, UWSFactory input = getFileManager().getErrorInput(error, job); UWSToolBox.write(input, "text/plain", getFileManager().getErrorSize(error, job), resp); }catch(IOException ioe){ - throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, ioe, "Can not read the error details (job ID: "+job.getJobId()+")."); + throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, ioe, "Can not read the error details (job ID: " + job.getJobId() + ")."); }finally{ if (input != null) input.close(); @@ -481,10 +476,7 @@ public abstract class UWSServlet extends HttpServlet implements UWS, UWSFactory // Write the value/content of the selected attribute: UWSSerializer serializer = getSerializer(req.getHeader("Accept")); String uwsField = attributes[0]; - if (uwsField == null || uwsField.trim().isEmpty() || (attributes.length <= 1 - && (uwsField.equalsIgnoreCase(UWSJob.PARAM_ERROR_SUMMARY) - || uwsField.equalsIgnoreCase(UWSJob.PARAM_RESULTS) - || uwsField.equalsIgnoreCase(UWSJob.PARAM_PARAMETERS)))) + if (uwsField == null || uwsField.trim().isEmpty() || (attributes.length <= 1 && (uwsField.equalsIgnoreCase(UWSJob.PARAM_ERROR_SUMMARY) || uwsField.equalsIgnoreCase(UWSJob.PARAM_RESULTS) || uwsField.equalsIgnoreCase(UWSJob.PARAM_PARAMETERS)))) resp.setContentType(serializer.getMimeType()); else resp.setContentType("text/plain"); @@ -492,7 +484,7 @@ public abstract class UWSServlet extends HttpServlet implements UWS, UWSFactory } } - protected void doSetJobParam(UWSUrl requestUrl, HttpServletRequest req, HttpServletResponse resp, JobOwner user) throws UWSException, ServletException, IOException { + protected void doSetJobParam(UWSUrl requestUrl, HttpServletRequest req, HttpServletResponse resp, JobOwner user) throws UWSException, ServletException, IOException{ // Get the job: UWSJob job = getJob(requestUrl); @@ -505,11 +497,11 @@ public abstract class UWSServlet extends HttpServlet implements UWS, UWSFactory redirect(requestUrl.jobSummary(requestUrl.getJobListName(), job.getJobId()).getRequestURL(), req, user, UWSAction.SET_JOB_PARAM, resp); } - public UWSJob getJob(UWSUrl requestUrl) throws UWSException { + public UWSJob getJob(UWSUrl requestUrl) throws UWSException{ return getJob(requestUrl, null); } - public UWSJob getJob(UWSUrl requestUrl, JobOwner user) throws UWSException { + public UWSJob getJob(UWSUrl requestUrl, JobOwner user) throws UWSException{ // Get the jobs list: JobList jobsList = getJobList(requestUrl.getJobListName()); @@ -531,27 +523,27 @@ public abstract class UWSServlet extends HttpServlet implements UWS, UWSFactory /* JOB CREATION */ /* ************ */ @Override - public final UWSFactory getFactory() { + public final UWSFactory getFactory(){ return this; } @Override - public UWSJob createJob(HttpServletRequest request, JobOwner user) throws UWSException { + public UWSJob createJob(HttpServletRequest request, JobOwner user) throws UWSException{ return new UWSJob(user, createUWSParameters(request)); } @Override - public UWSJob createJob(final String jobID, final JobOwner owner, final UWSParameters params, final long quote, final long startTime, final long endTime, final List<Result> results, final ErrorSummary error) throws UWSException { + public UWSJob createJob(final String jobID, final JobOwner owner, final UWSParameters params, final long quote, final long startTime, final long endTime, final List<Result> results, final ErrorSummary error) throws UWSException{ return new UWSJob(jobID, owner, params, quote, startTime, endTime, results, error); } @Override - public UWSParameters createUWSParameters(final Map<String, Object> params) throws UWSException { + public UWSParameters createUWSParameters(final Map<String,Object> params) throws UWSException{ return new UWSParameters(params, expectedAdditionalParams, inputParamControllers); } @Override - public UWSParameters createUWSParameters(final HttpServletRequest req) throws UWSException { + public UWSParameters createUWSParameters(final HttpServletRequest req) throws UWSException{ return new UWSParameters(req, expectedAdditionalParams, inputParamControllers); } @@ -568,12 +560,12 @@ public abstract class UWSServlet extends HttpServlet implements UWS, UWSFactory * @throws IOException If there is an error during the redirection. * @throws UWSException If there is any other error. */ - public void redirect(String url, HttpServletRequest request, JobOwner user, String uwsAction, HttpServletResponse response) throws ServletException, IOException { + public void redirect(String url, HttpServletRequest request, JobOwner user, String uwsAction, HttpServletResponse response) throws ServletException, IOException{ response.setStatus(HttpServletResponse.SC_SEE_OTHER); response.setContentType(request.getContentType()); response.setHeader("Location", url); response.flushBuffer(); - logger.httpRequest(request, user, uwsAction, HttpServletResponse.SC_SEE_OTHER, "[Redirection toward "+url+"]", null); + logger.httpRequest(request, user, uwsAction, HttpServletResponse.SC_SEE_OTHER, "[Redirection toward " + url + "]", null); } /** @@ -593,7 +585,7 @@ public abstract class UWSServlet extends HttpServlet implements UWS, UWSFactory * @see #redirect(String, HttpServletRequest, JobOwner, String, HttpServletResponse) * @see #writeError(Throwable, HttpServletResponse, HttpServletRequest, JobOwner, String) */ - public void sendError(UWSException error, HttpServletRequest request, JobOwner user, String uwsAction, HttpServletResponse response) throws ServletException, IOException { + public void sendError(UWSException error, HttpServletRequest request, JobOwner user, String uwsAction, HttpServletResponse response) throws ServletException, IOException{ if (error.getHttpErrorCode() == UWSException.SEE_OTHER) redirect(error.getMessage(), request, user, uwsAction, response); else{ @@ -614,7 +606,7 @@ public abstract class UWSServlet extends HttpServlet implements UWS, UWSFactory * * @return The error writer/formatter. */ - public final ServiceErrorWriter getErrorWriter() { + public final ServiceErrorWriter getErrorWriter(){ return errorWriter; } @@ -625,12 +617,11 @@ public abstract class UWSServlet extends HttpServlet implements UWS, UWSFactory * * @param errorWriter The new error writer/formatter. */ - public final void setErrorWriter(ServiceErrorWriter errorWriter) { + public final void setErrorWriter(ServiceErrorWriter errorWriter){ if (errorWriter != null) this.errorWriter = errorWriter; } - /* **************** */ /* INPUT PARAMETERS */ /* **************** */ @@ -690,7 +681,7 @@ public abstract class UWSServlet extends HttpServlet implements UWS, UWSFactory * Gets the list of all UWS input parameter controllers. * @return All parameter controllers. */ - public final Map<String, InputParamController> getInputParamControllers(){ + public final Map<String,InputParamController> getInputParamControllers(){ return inputParamControllers; } @@ -698,7 +689,7 @@ public abstract class UWSServlet extends HttpServlet implements UWS, UWSFactory * Gets an iterator on the list of all UWS input parameter controllers. * @return An iterator on all parameter controllers. */ - public final Iterator<Map.Entry<String, InputParamController>> getInputParamControllersIterator(){ + public final Iterator<Map.Entry<String,InputParamController>> getInputParamControllersIterator(){ return inputParamControllers.entrySet().iterator(); } @@ -807,14 +798,14 @@ public abstract class UWSServlet extends HttpServlet implements UWS, UWSFactory /** * @return The name. */ - public final String getName() { + public final String getName(){ return name; } /** * @return The description. */ - public final String getDescription() { + public final String getDescription(){ return description; } @@ -825,7 +816,7 @@ public abstract class UWSServlet extends HttpServlet implements UWS, UWSFactory return mapJobLists.values().iterator(); } - public JobList getJobList(String name) throws UWSException { + public JobList getJobList(String name) throws UWSException{ if (name != null) name = name.trim(); if (name == null || name.length() == 0) @@ -849,8 +840,8 @@ public abstract class UWSServlet extends HttpServlet implements UWS, UWSFactory try{ jl.setUWS(this); mapJobLists.put(jl.getName(), jl); - }catch (IllegalStateException ise){ - logger.error("The jobs list \""+jl.getName()+"\" can not be added into the UWS "+getName()+" !", ise); + }catch(IllegalStateException ise){ + logger.error("The jobs list \"" + jl.getName() + "\" can not be added into the UWS " + getName() + " !", ise); return false; } @@ -912,7 +903,7 @@ public abstract class UWSServlet extends HttpServlet implements UWS, UWSFactory jl.clear(); jl.setUWS(null); }catch(IllegalStateException ise){ - getLogger().warning("Impossible to erase completely the association between the jobs list \""+jl.getName()+"\" and the UWS \""+getName()+"\", because: "+ise.getMessage()); + getLogger().warning("Impossible to erase completely the association between the jobs list \"" + jl.getName() + "\" and the UWS \"" + getName() + "\", because: " + ise.getMessage()); } } return jl != null; @@ -955,7 +946,7 @@ public abstract class UWSServlet extends HttpServlet implements UWS, UWSFactory * @see AcceptHeader#AcceptHeader(String) * @see AcceptHeader#getOrderedMimeTypes() */ - public final UWSSerializer getSerializer(String mimeTypes) throws UWSException { + public final UWSSerializer getSerializer(String mimeTypes) throws UWSException{ UWSSerializer choosenSerializer = null; if (mimeTypes != null){ @@ -964,7 +955,7 @@ public abstract class UWSServlet extends HttpServlet implements UWS, UWSFactory ArrayList<String> lstMimeTypes = accept.getOrderedMimeTypes(); // Try each of them and stop at the first which match with an existing serializer: - for(int i=0; choosenSerializer == null && i<lstMimeTypes.size(); i++) + for(int i = 0; choosenSerializer == null && i < lstMimeTypes.size(); i++) choosenSerializer = serializers.get(lstMimeTypes.get(i)); } @@ -972,7 +963,7 @@ public abstract class UWSServlet extends HttpServlet implements UWS, UWSFactory if (choosenSerializer == null){ choosenSerializer = serializers.get(defaultSerializer); if (choosenSerializer == null) - throw UWSExceptionFactory.missingSerializer(mimeTypes+" (given MIME types) and "+defaultSerializer+" (default serializer MIME type)"); + throw UWSExceptionFactory.missingSerializer(mimeTypes + " (given MIME types) and " + defaultSerializer + " (default serializer MIME type)"); } return choosenSerializer; @@ -1070,7 +1061,7 @@ public abstract class UWSServlet extends HttpServlet implements UWS, UWSFactory * * @return Its backup manager. */ - public final UWSBackupManager getBackupManager() { + public final UWSBackupManager getBackupManager(){ return backupManager; } diff --git a/src/uws/service/UWSUrl.java b/src/uws/service/UWSUrl.java index 331f8d2f0403bdb37cea330042f38921cd3cbcf9..95073f706940405bd76786c856494b980aa46bad 100644 --- a/src/uws/service/UWSUrl.java +++ b/src/uws/service/UWSUrl.java @@ -66,7 +66,6 @@ public class UWSUrl implements Serializable { /** Name of the job attribute found in uwsURI (i.e. {results, report}). */ protected String[] attributes = new String[0]; // {results, report} - /* ************ */ /* CONSTRUCTORS */ /* ************ */ @@ -94,7 +93,7 @@ public class UWSUrl implements Serializable { * * @throws UWSException If the given baseURI is <i>null</i> or is an empty string. */ - public UWSUrl(String baseURI) throws UWSException { + public UWSUrl(String baseURI) throws UWSException{ if (baseURI == null) throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, "The given base UWS URI is NULL !"); @@ -113,7 +112,7 @@ public class UWSUrl implements Serializable { * * @see #extractBaseURI(HttpServletRequest) */ - public UWSUrl(HttpServletRequest request) throws UWSException { + public UWSUrl(HttpServletRequest request) throws UWSException{ String uri = extractBaseURI(request); if (uri == null) throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, "The extracted base UWS URI is NULL !"); @@ -150,9 +149,9 @@ public class UWSUrl implements Serializable { protected static final String normalizeURI(String uri){ uri = uri.trim(); if (uri.length() > 0 && uri.charAt(0) != '/') - uri = "/"+uri; - while (uri.length() >= 1 && uri.charAt(uri.length()-1) == '/') - uri = uri.substring(0, uri.length()-1).trim(); + uri = "/" + uri; + while(uri.length() >= 1 && uri.charAt(uri.length() - 1) == '/') + uri = uri.substring(0, uri.length() - 1).trim(); return uri.trim(); } @@ -203,7 +202,9 @@ public class UWSUrl implements Serializable { URL url = null; try{ url = new URL(request.getRequestURL().toString()); - }catch(MalformedURLException ex){;} + }catch(MalformedURLException ex){ + ; + } load(url); return; } @@ -299,9 +300,9 @@ public class UWSUrl implements Serializable { } if (uriParts.length >= 4){ - attributes = new String[uriParts.length-3]; - for(int i=3; i<uriParts.length; i++) - attributes[i-3] = uriParts[i].trim(); + attributes = new String[uriParts.length - 3]; + for(int i = 3; i < uriParts.length; i++) + attributes[i - 3] = uriParts[i].trim(); } } } @@ -314,7 +315,7 @@ public class UWSUrl implements Serializable { * * @return The baseUri. */ - public final String getBaseURI() { + public final String getBaseURI(){ return baseURI; } @@ -324,7 +325,7 @@ public class UWSUrl implements Serializable { * @return The presumed UWS name. */ public final String getUWSName(){ - return baseURI.substring(baseURI.lastIndexOf('/')+1); + return baseURI.substring(baseURI.lastIndexOf('/') + 1); } /** @@ -398,7 +399,7 @@ public class UWSUrl implements Serializable { * * @return The extracted jobs list name. */ - public final String getJobListName() { + public final String getJobListName(){ return jobListName; } @@ -416,7 +417,7 @@ public class UWSUrl implements Serializable { * * @return The extracted job ID. */ - public final String getJobId() { + public final String getJobId(){ return jobId; } @@ -492,8 +493,8 @@ public class UWSUrl implements Serializable { * </p> */ protected void updateRequestURL(){ - requestURI = baseURI+((uwsURI != null)?uwsURI:""); - requestURL = (urlHeader==null)?null:(urlHeader+requestURI); + requestURI = baseURI + ((uwsURI != null) ? uwsURI : ""); + requestURL = (urlHeader == null) ? null : (urlHeader + requestURI); } /** @@ -523,7 +524,7 @@ public class UWSUrl implements Serializable { * * @see #updateUwsURI() */ - public final void setJobListName(String jobListName) { + public final void setJobListName(String jobListName){ this.jobListName = jobListName; updateUwsURI(); } @@ -536,7 +537,7 @@ public class UWSUrl implements Serializable { * * @see #updateUwsURI() */ - public final void setJobId(String jobId) { + public final void setJobId(String jobId){ this.jobId = jobId; updateUwsURI(); } @@ -565,60 +566,145 @@ public class UWSUrl implements Serializable { /* URL BUILDING METHODS */ /* ******************** */ /** Gets the base UWS URI = UWS home page. */ - public final UWSUrl homePage() { + public final UWSUrl homePage(){ UWSUrl url = new UWSUrl(this); url.setUwsURI(null); return url; } /** Gets the UWS URL to get the specified <b>jobs list</b>. */ - public final UWSUrl listJobs (String jobListName) { UWSUrl url = homePage(); url.setJobListName(jobListName); return url; } + public final UWSUrl listJobs(String jobListName){ + UWSUrl url = homePage(); + url.setJobListName(jobListName); + return url; + } /** Gets the UWS URL to get the <b>summary</b>. */ - public final UWSUrl jobSummary (String jobListName, String jobId) { UWSUrl url = listJobs(jobListName); url.setJobId(jobId); return url; } + public final UWSUrl jobSummary(String jobListName, String jobId){ + UWSUrl url = listJobs(jobListName); + url.setJobId(jobId); + return url; + } + /** Gets the UWS URL to get the <b>runID</b>. */ - public final UWSUrl jobName (String jobListName, String jobId) { UWSUrl url = jobSummary(jobListName, jobId); url.setAttributes(new String[]{UWSJob.PARAM_RUN_ID}); return url; } + public final UWSUrl jobName(String jobListName, String jobId){ + UWSUrl url = jobSummary(jobListName, jobId); + url.setAttributes(new String[]{UWSJob.PARAM_RUN_ID}); + return url; + } + /** Gets the UWS URL to get the <b>phase</b>. */ - public final UWSUrl jobPhase (String jobListName, String jobId) { UWSUrl url = jobSummary(jobListName, jobId); url.setAttributes(new String[]{UWSJob.PARAM_PHASE}); return url; } + public final UWSUrl jobPhase(String jobListName, String jobId){ + UWSUrl url = jobSummary(jobListName, jobId); + url.setAttributes(new String[]{UWSJob.PARAM_PHASE}); + return url; + } + /** Gets the UWS URL to get the <b>execution duration</b>. */ - public final UWSUrl jobExecDuration (String jobListName, String jobId) { UWSUrl url = jobSummary(jobListName, jobId); url.setAttributes(new String[]{UWSJob.PARAM_EXECUTION_DURATION}); return url; } + public final UWSUrl jobExecDuration(String jobListName, String jobId){ + UWSUrl url = jobSummary(jobListName, jobId); + url.setAttributes(new String[]{UWSJob.PARAM_EXECUTION_DURATION}); + return url; + } + /** Gets the UWS URL to get the <b>destruction time</b>. */ - public final UWSUrl jobDestruction (String jobListName, String jobId) { UWSUrl url = jobSummary(jobListName, jobId); url.setAttributes(new String[]{UWSJob.PARAM_DESTRUCTION_TIME}); return url; } + public final UWSUrl jobDestruction(String jobListName, String jobId){ + UWSUrl url = jobSummary(jobListName, jobId); + url.setAttributes(new String[]{UWSJob.PARAM_DESTRUCTION_TIME}); + return url; + } + /** Gets the UWS URL to get the <b>error summary</b>. */ - public final UWSUrl jobError (String jobListName, String jobId) { UWSUrl url = jobSummary(jobListName, jobId); url.setAttributes(new String[]{UWSJob.PARAM_ERROR_SUMMARY}); return url; } + public final UWSUrl jobError(String jobListName, String jobId){ + UWSUrl url = jobSummary(jobListName, jobId); + url.setAttributes(new String[]{UWSJob.PARAM_ERROR_SUMMARY}); + return url; + } + /** Gets the UWS URL to get the <b>quote</b>. */ - public final UWSUrl jobQuote (String jobListName, String jobId) { UWSUrl url = jobSummary(jobListName, jobId); url.setAttributes(new String[]{UWSJob.PARAM_QUOTE}); return url; } + public final UWSUrl jobQuote(String jobListName, String jobId){ + UWSUrl url = jobSummary(jobListName, jobId); + url.setAttributes(new String[]{UWSJob.PARAM_QUOTE}); + return url; + } + /** Gets the UWS URL to get the <b>results</b>. */ - public final UWSUrl jobResults (String jobListName, String jobId) { UWSUrl url = jobSummary(jobListName, jobId); url.setAttributes(new String[]{UWSJob.PARAM_RESULTS}); return url; } + public final UWSUrl jobResults(String jobListName, String jobId){ + UWSUrl url = jobSummary(jobListName, jobId); + url.setAttributes(new String[]{UWSJob.PARAM_RESULTS}); + return url; + } + /** Gets the UWS URL to get the <b>specified result</b>. */ - public final UWSUrl jobResult (String jobListName, String jobId, String resultId) { UWSUrl url = jobSummary(jobListName, jobId); url.setAttributes(new String[]{UWSJob.PARAM_RESULTS, resultId}); return url; } + public final UWSUrl jobResult(String jobListName, String jobId, String resultId){ + UWSUrl url = jobSummary(jobListName, jobId); + url.setAttributes(new String[]{UWSJob.PARAM_RESULTS,resultId}); + return url; + } + /** Gets the UWS URL to get the <b>parameters</b>. */ - public final UWSUrl jobParameters (String jobListName, String jobId) { UWSUrl url = jobSummary(jobListName, jobId); url.setAttributes(new String[]{UWSJob.PARAM_PARAMETERS}); return url; } + public final UWSUrl jobParameters(String jobListName, String jobId){ + UWSUrl url = jobSummary(jobListName, jobId); + url.setAttributes(new String[]{UWSJob.PARAM_PARAMETERS}); + return url; + } + /** Gets the UWS URL to get the <b>parameters/parameter</b>. */ - public final UWSUrl jobParameter (String jobListName, String jobId, String paramName){ UWSUrl url = jobSummary(jobListName, jobId); url.setAttributes(new String[]{UWSJob.PARAM_PARAMETERS, paramName}); return url; } + public final UWSUrl jobParameter(String jobListName, String jobId, String paramName){ + UWSUrl url = jobSummary(jobListName, jobId); + url.setAttributes(new String[]{UWSJob.PARAM_PARAMETERS,paramName}); + return url; + } + /** Gets the UWS URL to get the <b>owner ID</b>. */ - public final UWSUrl jobOwner (String jobListName, String jobId) { UWSUrl url = jobSummary(jobListName, jobId); url.setAttributes(new String[]{UWSJob.PARAM_OWNER}); return url; } + public final UWSUrl jobOwner(String jobListName, String jobId){ + UWSUrl url = jobSummary(jobListName, jobId); + url.setAttributes(new String[]{UWSJob.PARAM_OWNER}); + return url; + } /* ******************************* */ /* URL BUILDING METHODS (HTTP GET) */ /* ******************************* */ /** Gets the UWS URL <b>(HTTP-GET ONLY)</b> to <b>create</b> a job with the given parameters. */ - public final String createJob (String jobListName, Map<String,String> parameters) { return listJobs(jobListName) +"?"+UWSToolBox.getQueryPart(parameters); } + public final String createJob(String jobListName, Map<String,String> parameters){ + return listJobs(jobListName) + "?" + UWSToolBox.getQueryPart(parameters); + } + /** Gets the UWS URL <b>(HTTP-GET ONLY)</b> to <b>delete</b> the specified job. */ - public final String deleteJob (String jobListName, String jobId) { return jobSummary(jobListName, jobId) +"?"+UWSJob.PARAM_ACTION+"="+UWSJob.ACTION_DELETE; } + public final String deleteJob(String jobListName, String jobId){ + return jobSummary(jobListName, jobId) + "?" + UWSJob.PARAM_ACTION + "=" + UWSJob.ACTION_DELETE; + } + /** Gets the UWS URL <b>(HTTP-GET ONLY)</b> to <b>start</b> the specified job. */ - public final String startJob (String jobListName, String jobId) { return jobPhase(jobListName, jobId) +"?"+UWSJob.PARAM_PHASE.toUpperCase()+"="+UWSJob.PHASE_RUN; } + public final String startJob(String jobListName, String jobId){ + return jobPhase(jobListName, jobId) + "?" + UWSJob.PARAM_PHASE.toUpperCase() + "=" + UWSJob.PHASE_RUN; + } + /** Gets the UWS URL <b>(HTTP-GET ONLY)</b> to <b>abort</b> the specified job. */ - public final String abortJob (String jobListName, String jobId) { return jobPhase(jobListName, jobId) +"?"+UWSJob.PARAM_PHASE.toUpperCase()+"="+UWSJob.PHASE_ABORT; } + public final String abortJob(String jobListName, String jobId){ + return jobPhase(jobListName, jobId) + "?" + UWSJob.PARAM_PHASE.toUpperCase() + "=" + UWSJob.PHASE_ABORT; + } /** Gets the UWS URL <b>(HTTP-GET ONLY)</b> to change the run ID. */ - public final String changeJobName (String jobListName, String jobId, String newName) { return jobName(jobListName, jobId) +"?"+UWSJob.PARAM_RUN_ID.toUpperCase()+"="+newName; } + public final String changeJobName(String jobListName, String jobId, String newName){ + return jobName(jobListName, jobId) + "?" + UWSJob.PARAM_RUN_ID.toUpperCase() + "=" + newName; + } + /** Gets the UWS URL <b>(HTTP-GET ONLY)</b> to change the destruction time. */ - public final String changeDestructionTime (String jobListName, String jobId, String newDestructionTime) { return jobDestruction(jobListName, jobId) +"?"+UWSJob.PARAM_DESTRUCTION_TIME.toUpperCase()+"="+newDestructionTime; } + public final String changeDestructionTime(String jobListName, String jobId, String newDestructionTime){ + return jobDestruction(jobListName, jobId) + "?" + UWSJob.PARAM_DESTRUCTION_TIME.toUpperCase() + "=" + newDestructionTime; + } + /** Gets the UWS URL <b>(HTTP-GET ONLY)</b> to change the execution duration. */ - public final String changeExecDuration (String jobListName, String jobId, String newExecDuration) { return jobExecDuration(jobListName, jobId) +"?"+UWSJob.PARAM_EXECUTION_DURATION.toUpperCase()+"="+newExecDuration; } + public final String changeExecDuration(String jobListName, String jobId, String newExecDuration){ + return jobExecDuration(jobListName, jobId) + "?" + UWSJob.PARAM_EXECUTION_DURATION.toUpperCase() + "=" + newExecDuration; + } + /** Gets the UWS URL <b>(HTTP-GET ONLY)</b> to change the specified parameter. */ - public final String changeJobParam (String jobListName, String jobId, String paramName, String paramValue) { return jobParameters(jobListName, jobId) +"?"+paramName.toUpperCase()+"="+paramValue; } + public final String changeJobParam(String jobListName, String jobId, String paramName, String paramValue){ + return jobParameters(jobListName, jobId) + "?" + paramName.toUpperCase() + "=" + paramValue; + } /** * Gets the full request URL corresponding to this UWSUrl. @@ -629,7 +715,7 @@ public class UWSUrl implements Serializable { * * @see #getRequestURL() */ - public URL toURL() throws MalformedURLException { + public URL toURL() throws MalformedURLException{ String url = getRequestURL(); return (url != null) ? (new URL(url)) : null; } diff --git a/src/uws/service/UserIdentifier.java b/src/uws/service/UserIdentifier.java index caa306feb79f43963c2d6e47f681c46d73fbf08e..5ec66dc624bc800ffb72f5b41f12e097005fff74 100644 --- a/src/uws/service/UserIdentifier.java +++ b/src/uws/service/UserIdentifier.java @@ -75,6 +75,6 @@ public interface UserIdentifier extends Serializable { * * @see DefaultUWSBackupManager#restoreAll() */ - public JobOwner restoreUser(final String id, final String pseudo, final Map<String, Object> otherData) throws UWSException; + public JobOwner restoreUser(final String id, final String pseudo, final Map<String,Object> otherData) throws UWSException; } \ No newline at end of file diff --git a/src/uws/service/actions/AddJob.java b/src/uws/service/actions/AddJob.java index 13e68dea6272e9db5c0538acb6e54c7bb07947c8..a7265016ad2f5f296e7db559587cdecbca4ec5e3 100644 --- a/src/uws/service/actions/AddJob.java +++ b/src/uws/service/actions/AddJob.java @@ -32,7 +32,6 @@ import uws.job.UWSJob; import uws.job.user.JobOwner; - import uws.service.UWSService; import uws.service.UWSUrl; @@ -59,12 +58,12 @@ public class AddJob extends UWSAction { * @see uws.service.actions.UWSAction#getName() */ @Override - public String getName() { + public String getName(){ return ADD_JOB; } @Override - public String getDescription() { + public String getDescription(){ return "Lets adding to the specified jobs list a job whose the parameters are given. (URL: {baseUWS_URL}/{jobListName}, Method: HTTP-POST, Parameters: job parameters)"; } @@ -78,10 +77,8 @@ public class AddJob extends UWSAction { * @see uws.service.actions.UWSAction#match(uws.service.UWSUrl, java.lang.String, javax.servlet.http.HttpServletRequest) */ @Override - public boolean match(UWSUrl urlInterpreter, JobOwner user, HttpServletRequest request) throws UWSException { - return (urlInterpreter.hasJobList() - && !urlInterpreter.hasJob() - && request.getMethod().equalsIgnoreCase("post")); + public boolean match(UWSUrl urlInterpreter, JobOwner user, HttpServletRequest request) throws UWSException{ + return (urlInterpreter.hasJobList() && !urlInterpreter.hasJob() && request.getMethod().equalsIgnoreCase("post")); } /** @@ -97,7 +94,7 @@ public class AddJob extends UWSAction { * @see uws.service.actions.UWSAction#apply(uws.service.UWSUrl, java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override - public boolean apply(UWSUrl urlInterpreter, JobOwner user, HttpServletRequest request, HttpServletResponse response) throws UWSException, IOException { + public boolean apply(UWSUrl urlInterpreter, JobOwner user, HttpServletRequest request, HttpServletResponse response) throws UWSException, IOException{ // Get the jobs list: JobList jobsList = getJobsList(urlInterpreter); @@ -116,7 +113,7 @@ public class AddJob extends UWSAction { return true; }else - throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, "Unable to add the new job to the jobs list. (ID of the new job = \""+newJob.getJobId()+"\" ; ID already used = "+(jobsList.getJob(newJob.getJobId())!=null)+")"); + throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, "Unable to add the new job to the jobs list. (ID of the new job = \"" + newJob.getJobId() + "\" ; ID already used = " + (jobsList.getJob(newJob.getJobId()) != null) + ")"); } } diff --git a/src/uws/service/actions/DestroyJob.java b/src/uws/service/actions/DestroyJob.java index b016f8be544da61c6707932c2c52d7e39d128115..d6e5d33ef9bafda2d79580816a8b8d33f7932dd8 100644 --- a/src/uws/service/actions/DestroyJob.java +++ b/src/uws/service/actions/DestroyJob.java @@ -48,7 +48,7 @@ import uws.service.UWSUrl; public class DestroyJob extends UWSAction { private static final long serialVersionUID = 1L; - public DestroyJob(UWSService u) { + public DestroyJob(UWSService u){ super(u); } @@ -57,12 +57,12 @@ public class DestroyJob extends UWSAction { * @see uws.service.actions.UWSAction#getName() */ @Override - public String getName() { + public String getName(){ return DESTROY_JOB; } @Override - public String getDescription() { + public String getDescription(){ return "Lets stopping the specified job, removing it from its jobs list and destroying all its associated resources. (URL: {baseUWS_URL}/{jobListName}/{job-id}, Method: HTTP-DELETE, No parameter) or (URL: {baseUWS_URL}/{jobListName}/{job-id}, Method: HTTP-POST, Parameter: ACTION=DELETE)"; } @@ -78,13 +78,8 @@ public class DestroyJob extends UWSAction { * @see uws.service.actions.UWSAction#match(uws.service.UWSUrl, java.lang.String, javax.servlet.http.HttpServletRequest) */ @Override - public boolean match(UWSUrl urlInterpreter, JobOwner user, HttpServletRequest request) throws UWSException { - return (urlInterpreter.hasJobList() - && urlInterpreter.hasJob() - && (request.getMethod().equalsIgnoreCase("delete") || (request.getMethod().equalsIgnoreCase("post") - && request.getParameter(UWSJob.PARAM_ACTION) != null - && request.getParameter(UWSJob.PARAM_ACTION).equalsIgnoreCase(UWSJob.ACTION_DELETE)) - )); + public boolean match(UWSUrl urlInterpreter, JobOwner user, HttpServletRequest request) throws UWSException{ + return (urlInterpreter.hasJobList() && urlInterpreter.hasJob() && (request.getMethod().equalsIgnoreCase("delete") || (request.getMethod().equalsIgnoreCase("post") && request.getParameter(UWSJob.PARAM_ACTION) != null && request.getParameter(UWSJob.PARAM_ACTION).equalsIgnoreCase(UWSJob.ACTION_DELETE)))); } /** @@ -100,7 +95,7 @@ public class DestroyJob extends UWSAction { * @see uws.service.actions.UWSAction#apply(uws.service.UWSUrl, java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override - public boolean apply(UWSUrl urlInterpreter, JobOwner user, HttpServletRequest request, HttpServletResponse response) throws UWSException, IOException { + public boolean apply(UWSUrl urlInterpreter, JobOwner user, HttpServletRequest request, HttpServletResponse response) throws UWSException, IOException{ // Get the jobs list: JobList jobsList = getJobsList(urlInterpreter); diff --git a/src/uws/service/actions/GetJobParam.java b/src/uws/service/actions/GetJobParam.java index 92696e93332b57a5e60b890975b47000f1938b57..048ceffaaa583fb12050a1bb614d7ce9e982cb48 100644 --- a/src/uws/service/actions/GetJobParam.java +++ b/src/uws/service/actions/GetJobParam.java @@ -67,12 +67,12 @@ public class GetJobParam extends UWSAction { * @see uws.service.actions.UWSAction#getName() */ @Override - public String getName() { + public String getName(){ return GET_JOB_PARAM; } @Override - public String getDescription() { + public String getDescription(){ return "Gets the value of a job attribute/parameter of the specified job. (URL: {baseUWS_URL}/{jobListName}/{job-id}/{job-attribute}, Method: HTTP-GET, No parameter)"; } @@ -88,11 +88,8 @@ public class GetJobParam extends UWSAction { * @see uws.service.actions.UWSAction#match(uws.service.UWSUrl, java.lang.String, javax.servlet.http.HttpServletRequest) */ @Override - public boolean match(UWSUrl urlInterpreter, JobOwner user, HttpServletRequest request) throws UWSException { - return (urlInterpreter.hasJobList() - && urlInterpreter.hasJobList() - && urlInterpreter.hasAttribute() - && request.getMethod().equalsIgnoreCase("get")); + public boolean match(UWSUrl urlInterpreter, JobOwner user, HttpServletRequest request) throws UWSException{ + return (urlInterpreter.hasJobList() && urlInterpreter.hasJobList() && urlInterpreter.hasAttribute() && request.getMethod().equalsIgnoreCase("get")); } /** @@ -109,7 +106,7 @@ public class GetJobParam extends UWSAction { * @see uws.service.actions.UWSAction#apply(uws.service.UWSUrl, java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override - public boolean apply(UWSUrl urlInterpreter, JobOwner user, HttpServletRequest request, HttpServletResponse response) throws UWSException, IOException { + public boolean apply(UWSUrl urlInterpreter, JobOwner user, HttpServletRequest request, HttpServletResponse response) throws UWSException, IOException{ // Get the job: UWSJob job = getJob(urlInterpreter, user); @@ -128,7 +125,7 @@ public class GetJobParam extends UWSAction { input = uws.getFileManager().getResultInput(result, job); UWSToolBox.write(input, result.getMimeType(), result.getSize(), response); }catch(IOException ioe){ - throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, ioe, "Can not read the content of the result "+result.getId()+" (job ID: "+job.getJobId()+")."); + throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, ioe, "Can not read the content of the result " + result.getId() + " (job ID: " + job.getJobId() + ")."); }finally{ if (input != null) input.close(); @@ -145,7 +142,7 @@ public class GetJobParam extends UWSAction { input = uws.getFileManager().getErrorInput(error, job); UWSToolBox.write(input, "text/plain", uws.getFileManager().getErrorSize(error, job), response); }catch(IOException ioe){ - throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, ioe, "Can not read the error details (job ID: "+job.getJobId()+")."); + throw new UWSException(UWSException.INTERNAL_SERVER_ERROR, ioe, "Can not read the error details (job ID: " + job.getJobId() + ")."); }finally{ if (input != null) input.close(); @@ -157,10 +154,7 @@ public class GetJobParam extends UWSAction { // Write the value/content of the selected attribute: UWSSerializer serializer = uws.getSerializer(request.getHeader("Accept")); String uwsField = attributes[0]; - if (uwsField == null || uwsField.trim().isEmpty() || (attributes.length <= 1 - && (uwsField.equalsIgnoreCase(UWSJob.PARAM_ERROR_SUMMARY) - || uwsField.equalsIgnoreCase(UWSJob.PARAM_RESULTS) - || uwsField.equalsIgnoreCase(UWSJob.PARAM_PARAMETERS)))) + if (uwsField == null || uwsField.trim().isEmpty() || (attributes.length <= 1 && (uwsField.equalsIgnoreCase(UWSJob.PARAM_ERROR_SUMMARY) || uwsField.equalsIgnoreCase(UWSJob.PARAM_RESULTS) || uwsField.equalsIgnoreCase(UWSJob.PARAM_PARAMETERS)))) response.setContentType(serializer.getMimeType()); else response.setContentType("text/plain"); @@ -170,8 +164,6 @@ public class GetJobParam extends UWSAction { return true; } - - /** * Tells whether the URL of this Result is the default one. * In this case, the result must be read from the result file and written in response of the HTTP request. diff --git a/src/uws/service/actions/JobSummary.java b/src/uws/service/actions/JobSummary.java index 801a0fcbca96f0ebed7cde77025a24376b5cbdce..adf9ed059e341dcaa2cbf355c3a45dc08c195df3 100644 --- a/src/uws/service/actions/JobSummary.java +++ b/src/uws/service/actions/JobSummary.java @@ -51,7 +51,7 @@ import uws.service.UWSUrl; public class JobSummary extends UWSAction { private static final long serialVersionUID = 1L; - public JobSummary(UWSService u) { + public JobSummary(UWSService u){ super(u); } @@ -60,12 +60,12 @@ public class JobSummary extends UWSAction { * @see uws.service.actions.UWSAction#getName() */ @Override - public String getName() { + public String getName(){ return JOB_SUMMARY; } @Override - public String getDescription() { + public String getDescription(){ return "Lets getting a summary of the specified job. (URL: {baseUWS_URL}/{jobListName}/{job-id}, Method: HTTP-GET, No parameter)"; } @@ -81,11 +81,8 @@ public class JobSummary extends UWSAction { * @see uws.service.actions.UWSAction#match(uws.service.UWSUrl, java.lang.String, javax.servlet.http.HttpServletRequest) */ @Override - public boolean match(UWSUrl urlInterpreter, JobOwner user, HttpServletRequest request) throws UWSException { - return (urlInterpreter.hasJobList() - && urlInterpreter.hasJob() - && !urlInterpreter.hasAttribute() - && request.getMethod().equalsIgnoreCase("get")); + public boolean match(UWSUrl urlInterpreter, JobOwner user, HttpServletRequest request) throws UWSException{ + return (urlInterpreter.hasJobList() && urlInterpreter.hasJob() && !urlInterpreter.hasAttribute() && request.getMethod().equalsIgnoreCase("get")); } /** @@ -99,7 +96,7 @@ public class JobSummary extends UWSAction { * @see uws.service.actions.UWSAction#apply(uws.service.UWSUrl, java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override - public boolean apply(UWSUrl urlInterpreter, JobOwner user, HttpServletRequest request, HttpServletResponse response) throws UWSException, IOException { + public boolean apply(UWSUrl urlInterpreter, JobOwner user, HttpServletRequest request, HttpServletResponse response) throws UWSException, IOException{ // Get the job: UWSJob job = getJob(urlInterpreter); diff --git a/src/uws/service/actions/ListJobs.java b/src/uws/service/actions/ListJobs.java index b403c3a8c7ceb9d46621b451a8aab6d505083190..dfeeb4fee6413d55d03114b069f88a4f4a33216f 100644 --- a/src/uws/service/actions/ListJobs.java +++ b/src/uws/service/actions/ListJobs.java @@ -51,7 +51,7 @@ import uws.service.UWSUrl; public class ListJobs extends UWSAction { private static final long serialVersionUID = 1L; - public ListJobs(UWSService u) { + public ListJobs(UWSService u){ super(u); } @@ -80,10 +80,8 @@ public class ListJobs extends UWSAction { * @see uws.service.actions.UWSAction#match(uws.service.UWSUrl, java.lang.String, javax.servlet.http.HttpServletRequest) */ @Override - public boolean match(UWSUrl urlInterpreter, JobOwner user, HttpServletRequest request) throws UWSException { - return (urlInterpreter.hasJobList() - && !urlInterpreter.hasJob() - && request.getMethod().equalsIgnoreCase("get")); + public boolean match(UWSUrl urlInterpreter, JobOwner user, HttpServletRequest request) throws UWSException{ + return (urlInterpreter.hasJobList() && !urlInterpreter.hasJob() && request.getMethod().equalsIgnoreCase("get")); } /** @@ -97,7 +95,7 @@ public class ListJobs extends UWSAction { * @see uws.service.actions.UWSAction#apply(uws.service.UWSUrl, java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override - public boolean apply(UWSUrl urlInterpreter, JobOwner user, HttpServletRequest request, HttpServletResponse response) throws UWSException, IOException { + public boolean apply(UWSUrl urlInterpreter, JobOwner user, HttpServletRequest request, HttpServletResponse response) throws UWSException, IOException{ // Get the jobs list: JobList jobsList = getJobsList(urlInterpreter); diff --git a/src/uws/service/actions/SetJobParam.java b/src/uws/service/actions/SetJobParam.java index 3fe9bf30841ff7000a2ec1bc0696eecf9696a18b..02026bbff3fa922f0552a16b597afa26a2ea6c45 100644 --- a/src/uws/service/actions/SetJobParam.java +++ b/src/uws/service/actions/SetJobParam.java @@ -57,12 +57,12 @@ public class SetJobParam extends UWSAction { * @see uws.service.actions.UWSAction#getName() */ @Override - public String getName() { + public String getName(){ return SET_JOB_PARAM; } @Override - public String getDescription() { + public String getDescription(){ return "Sets the value of a job attribute/parameter of the specified job. (URL: {baseUWS_URL}/{jobListName}/{job-id}/{job-attribute}, Method: HTTP-POST or HTTP-PUT, Parameter: {JOB-ATTRIBUTE}={attribute-value})"; } @@ -78,20 +78,8 @@ public class SetJobParam extends UWSAction { * @see uws.service.actions.UWSAction#match(uws.service.UWSUrl, java.lang.String, javax.servlet.http.HttpServletRequest) */ @Override - public boolean match(UWSUrl urlInterpreter, JobOwner user, HttpServletRequest request) throws UWSException { - return (urlInterpreter.hasJobList() - && urlInterpreter.hasJob() - && ( - (request.getMethod().equalsIgnoreCase("post") - && (!urlInterpreter.hasAttribute() || urlInterpreter.getAttributes().length == 1) - && request.getParameterMap().size() > 0) - || - (request.getMethod().equalsIgnoreCase("put") - && urlInterpreter.getAttributes().length >= 2 - && urlInterpreter.getAttributes()[0].equalsIgnoreCase(UWSJob.PARAM_PARAMETERS) - && request.getParameter(urlInterpreter.getAttributes()[1]) != null) - ) - ); + public boolean match(UWSUrl urlInterpreter, JobOwner user, HttpServletRequest request) throws UWSException{ + return (urlInterpreter.hasJobList() && urlInterpreter.hasJob() && ((request.getMethod().equalsIgnoreCase("post") && (!urlInterpreter.hasAttribute() || urlInterpreter.getAttributes().length == 1) && request.getParameterMap().size() > 0) || (request.getMethod().equalsIgnoreCase("put") && urlInterpreter.getAttributes().length >= 2 && urlInterpreter.getAttributes()[0].equalsIgnoreCase(UWSJob.PARAM_PARAMETERS) && request.getParameter(urlInterpreter.getAttributes()[1]) != null))); } /** @@ -107,7 +95,7 @@ public class SetJobParam extends UWSAction { * @see uws.service.actions.UWSAction#apply(uws.service.UWSUrl, java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override - public boolean apply(UWSUrl urlInterpreter, JobOwner user, HttpServletRequest request, HttpServletResponse response) throws UWSException, IOException { + public boolean apply(UWSUrl urlInterpreter, JobOwner user, HttpServletRequest request, HttpServletResponse response) throws UWSException, IOException{ // Get the job: UWSJob job = getJob(urlInterpreter); diff --git a/src/uws/service/actions/ShowHomePage.java b/src/uws/service/actions/ShowHomePage.java index 39540121c861f8c98796f8bd7001bf1554538eb0..c43749750a5c16ab68f84a14037dcaceeed0c748 100644 --- a/src/uws/service/actions/ShowHomePage.java +++ b/src/uws/service/actions/ShowHomePage.java @@ -32,7 +32,6 @@ import javax.servlet.http.HttpServletResponse; import uws.UWSException; import uws.UWSExceptionFactory; - import uws.job.serializer.UWSSerializer; import uws.job.user.JobOwner; @@ -62,12 +61,12 @@ public class ShowHomePage extends UWSAction { * @see uws.service.actions.UWSAction#getName() */ @Override - public String getName() { + public String getName(){ return HOME_PAGE; } @Override - public String getDescription() { + public String getDescription(){ return "Shows the UWS home page. (URL: {baseUWS_URL}, Method: HTTP-GET, No parameter)"; } @@ -77,7 +76,7 @@ public class ShowHomePage extends UWSAction { * @see uws.service.actions.UWSAction#match(uws.service.UWSUrl, uws.job.user.JobOwner, javax.servlet.http.HttpServletRequest) */ @Override - public boolean match(UWSUrl urlInterpreter, JobOwner user, HttpServletRequest request) throws UWSException { + public boolean match(UWSUrl urlInterpreter, JobOwner user, HttpServletRequest request) throws UWSException{ return !urlInterpreter.hasJobList(); } @@ -99,7 +98,7 @@ public class ShowHomePage extends UWSAction { * @see UWSService#redirect(String, HttpServletRequest, JobOwner, String, HttpServletResponse) */ @Override - public boolean apply(UWSUrl urlInterpreter, JobOwner user, HttpServletRequest request, HttpServletResponse response) throws UWSException, IOException { + public boolean apply(UWSUrl urlInterpreter, JobOwner user, HttpServletRequest request, HttpServletResponse response) throws UWSException, IOException{ if (uws.isDefaultHomePage()){ UWSSerializer serializer = uws.getSerializer(request.getHeader("Accept")); response.setContentType(serializer.getMimeType()); @@ -109,7 +108,7 @@ public class ShowHomePage extends UWSAction { output.print(serialization); output.flush(); }else - throw UWSExceptionFactory.incorrectSerialization(serialization, "the UWS "+uws.getName()); + throw UWSExceptionFactory.incorrectSerialization(serialization, "the UWS " + uws.getName()); }else{ if (uws.isHomePageRedirection()) uws.redirect(uws.getHomePage(), request, user, getName(), response); diff --git a/src/uws/service/actions/UWSAction.java b/src/uws/service/actions/UWSAction.java index 004402c03809f4d4be23ddc7a63ecb9b51ea75c4..381336386e74807182c44d071d2dcd913d7bfb20 100644 --- a/src/uws/service/actions/UWSAction.java +++ b/src/uws/service/actions/UWSAction.java @@ -132,7 +132,7 @@ public abstract class UWSAction implements Serializable { * @see UWSUrl#getJobListName() * @see UWSService#getJobList(String) */ - protected final JobList getJobsList(UWSUrl urlInterpreter) throws UWSException { + protected final JobList getJobsList(UWSUrl urlInterpreter) throws UWSException{ String jlName = urlInterpreter.getJobListName(); JobList jobsList = null; @@ -162,7 +162,7 @@ public abstract class UWSAction implements Serializable { * * @see #getJob(UWSUrl, String, boolean) */ - protected final UWSJob getJob(UWSUrl urlInterpreter) throws UWSException { + protected final UWSJob getJob(UWSUrl urlInterpreter) throws UWSException{ return getJob(urlInterpreter, (JobOwner)null); } @@ -185,7 +185,7 @@ public abstract class UWSAction implements Serializable { * * @since 3.1 */ - protected final UWSJob getJob(UWSUrl urlInterpreter, JobOwner user) throws UWSException { + protected final UWSJob getJob(UWSUrl urlInterpreter, JobOwner user) throws UWSException{ String jobId = urlInterpreter.getJobId(); UWSJob job = null; @@ -215,7 +215,7 @@ public abstract class UWSAction implements Serializable { * * @see #getJob(UWSUrl, JobList, String, boolean) */ - protected final UWSJob getJob(UWSUrl urlInterpreter, JobList jobsList) throws UWSException { + protected final UWSJob getJob(UWSUrl urlInterpreter, JobList jobsList) throws UWSException{ return getJob(urlInterpreter, jobsList, null); } @@ -239,7 +239,7 @@ public abstract class UWSAction implements Serializable { * * @since 3.1 */ - protected final UWSJob getJob(UWSUrl urlInterpreter, JobList jobsList, JobOwner user) throws UWSException { + protected final UWSJob getJob(UWSUrl urlInterpreter, JobList jobsList, JobOwner user) throws UWSException{ String jobId = urlInterpreter.getJobId(); UWSJob job = null; @@ -302,7 +302,7 @@ public abstract class UWSAction implements Serializable { } @Override - public String toString() { + public String toString(){ return getName(); } diff --git a/src/uws/service/backup/DefaultUWSBackupManager.java b/src/uws/service/backup/DefaultUWSBackupManager.java index 3c9e0c06b40bdbe6c4368eb0ff5538fb1b28eb9c..2a9db4b418bc27e94ba27f1d975c870bfdafadd2 100644 --- a/src/uws/service/backup/DefaultUWSBackupManager.java +++ b/src/uws/service/backup/DefaultUWSBackupManager.java @@ -111,7 +111,6 @@ public class DefaultUWSBackupManager implements UWSBackupManager { /** Timer which saves the backup each <i>backupFreq</i> milliseconds. */ protected Timer timAutoBackup = null; - /** * Builds a backup manager in the mode "auto": one file for all users and all jobs, and the backup * is done all minutes (see {@link #DEFAULT_FREQUENCY}. @@ -120,7 +119,7 @@ public class DefaultUWSBackupManager implements UWSBackupManager { * * @see #DefaultBackupManager(UWS, long) */ - public DefaultUWSBackupManager(final UWS uws) { + public DefaultUWSBackupManager(final UWS uws){ this(uws, DEFAULT_FREQUENCY); } @@ -136,16 +135,16 @@ public class DefaultUWSBackupManager implements UWSBackupManager { * @param uws The UWS to save/restore. * @param frequency The backup frequency (in ms ; MUST BE positive and different from 0. If negative or 0, the frequency will be automatically set to {@link #DEFAULT_FREQUENCY}). */ - public DefaultUWSBackupManager(final UWS uws, final long frequency) { + public DefaultUWSBackupManager(final UWS uws, final long frequency){ this.uws = uws; this.byUser = false; this.backupFreq = (frequency <= 0) ? MANUAL : frequency; if (backupFreq > 0){ timAutoBackup = new Timer(); - timAutoBackup.scheduleAtFixedRate(new TimerTask() { + timAutoBackup.scheduleAtFixedRate(new TimerTask(){ @Override - public void run() { + public void run(){ saveAll(); } }, backupFreq, backupFreq); @@ -163,7 +162,7 @@ public class DefaultUWSBackupManager implements UWSBackupManager { * * @see #DefaultBackupManager(UWS, boolean, long) */ - public DefaultUWSBackupManager(final UWS uws, final boolean byUser) throws UWSException { + public DefaultUWSBackupManager(final UWS uws, final boolean byUser) throws UWSException{ this(uws, byUser, byUser ? AT_USER_ACTION : DEFAULT_FREQUENCY); } @@ -176,7 +175,7 @@ public class DefaultUWSBackupManager implements UWSBackupManager { * * @throws UWSException If the user identification is disabled (that's to say, if the given UWS has no UserIdentifier) while the parameter <i>byUser</i> is <i>true</i>. */ - public DefaultUWSBackupManager(final UWS uws, final boolean byUser, final long frequency) throws UWSException { + public DefaultUWSBackupManager(final UWS uws, final boolean byUser, final long frequency) throws UWSException{ this.uws = uws; this.byUser = byUser; this.backupFreq = frequency; @@ -188,9 +187,9 @@ public class DefaultUWSBackupManager implements UWSBackupManager { backupFreq = MANUAL; else if (backupFreq > 0){ timAutoBackup = new Timer(); - timAutoBackup.scheduleAtFixedRate(new TimerTask() { + timAutoBackup.scheduleAtFixedRate(new TimerTask(){ @Override - public void run() { + public void run(){ saveAll(); } }, backupFreq, backupFreq); @@ -203,19 +202,19 @@ public class DefaultUWSBackupManager implements UWSBackupManager { * * @return <i>true</i> if the backup is enabled, <i>false</i> otherwise. */ - public final boolean isEnabled() { + public final boolean isEnabled(){ return enabled; } - public final void setEnabled(boolean enabled) { + public final void setEnabled(boolean enabled){ this.enabled = enabled; if (backupFreq > 0){ if (this.enabled){ if (timAutoBackup == null){ timAutoBackup = new Timer(); - timAutoBackup.scheduleAtFixedRate(new TimerTask() { + timAutoBackup.scheduleAtFixedRate(new TimerTask(){ @Override - public void run() { + public void run(){ saveAll(); } }, backupFreq, backupFreq); @@ -234,7 +233,7 @@ public class DefaultUWSBackupManager implements UWSBackupManager { * * @return The backup frequency (in milliseconds). */ - public final long getBackupFreq() { + public final long getBackupFreq(){ return backupFreq; } @@ -251,7 +250,7 @@ public class DefaultUWSBackupManager implements UWSBackupManager { * * @param freq The new backup frequency (in milliseconds) ({@link #AT_USER_ACTION}, {@link #MANUAL}, {@link #DEFAULT_FREQUENCY} or any other positive value). */ - public final void setBackupFreq(long freq) { + public final void setBackupFreq(long freq){ if (freq < 0) freq = MANUAL; else if (freq == AT_USER_ACTION && !byUser) @@ -265,9 +264,9 @@ public class DefaultUWSBackupManager implements UWSBackupManager { if (enabled && backupFreq > 0){ timAutoBackup = new Timer(); - timAutoBackup.scheduleAtFixedRate(new TimerTask() { + timAutoBackup.scheduleAtFixedRate(new TimerTask(){ @Override - public void run() { + public void run(){ saveAll(); } }, 0, backupFreq); @@ -279,7 +278,7 @@ public class DefaultUWSBackupManager implements UWSBackupManager { * * @return The date of the last restoration (MAY BE NULL). */ - public final Date getLastRestoration() { + public final Date getLastRestoration(){ return lastRestoration; } @@ -288,7 +287,7 @@ public class DefaultUWSBackupManager implements UWSBackupManager { * * @return The date of the last backup (MAY BE NULL). */ - public final Date getLastBackup() { + public final Date getLastBackup(){ return lastBackup; } @@ -307,12 +306,11 @@ public class DefaultUWSBackupManager implements UWSBackupManager { return UWSToolBox.getDefaultLogger(); } - /* ************ */ /* SAVE METHODS */ /* ************ */ - public int[] saveAll() { + public int[] saveAll(){ if (!enabled) return null; @@ -320,7 +318,7 @@ public class DefaultUWSBackupManager implements UWSBackupManager { int nbJobs = 0, nbOwners = 0; // List all users of this UWS: - HashMap<String, JobOwner> users = new HashMap<String, JobOwner>(); + HashMap<String,JobOwner> users = new HashMap<String,JobOwner>(); for(JobList jl : uws){ Iterator<JobOwner> it = jl.getUsers(); while(it.hasNext()){ @@ -364,7 +362,7 @@ public class DefaultUWSBackupManager implements UWSBackupManager { out.value(getJSONUser(user)); nbSavedOwners++; }catch(JSONException je){ - getLogger().error("Unexpected JSON error while saving the user '"+user.getID()+"' !", je); + getLogger().error("Unexpected JSON error while saving the user '" + user.getID() + "' !", je); } } out.endArray(); @@ -380,9 +378,9 @@ public class DefaultUWSBackupManager implements UWSBackupManager { nbSavedJobs++; writer.flush(); }catch(UWSException ue){ - getLogger().error("Unexpected UWS error while saving the job '"+job.getJobId()+"' !", ue); + getLogger().error("Unexpected UWS error while saving the job '" + job.getJobId() + "' !", ue); }catch(JSONException je){ - getLogger().error("Unexpected JSON error while saving the job '"+job.getJobId()+"' !", je); + getLogger().error("Unexpected JSON error while saving the job '" + job.getJobId() + "' !", je); } } } @@ -403,7 +401,7 @@ public class DefaultUWSBackupManager implements UWSBackupManager { } // Build the report and log it: - int[] report = new int[]{nbSavedJobs, nbJobs, nbSavedOwners, nbOwners}; + int[] report = new int[]{nbSavedJobs,nbJobs,nbSavedOwners,nbOwners}; getLogger().uwsSaved(uws, report); lastBackup = new Date(); @@ -418,7 +416,7 @@ public class DefaultUWSBackupManager implements UWSBackupManager { return saveOwner(user, false); } - protected int[] saveOwner(JobOwner user, boolean fromSaveAll) { + protected int[] saveOwner(JobOwner user, boolean fromSaveAll){ if (!enabled) return null; @@ -427,7 +425,7 @@ public class DefaultUWSBackupManager implements UWSBackupManager { return new int[]{-1,-1}; UWSFileManager fileManager = uws.getFileManager(); - int[] saveReport = new int[]{0, 0}; + int[] saveReport = new int[]{0,0}; PrintWriter writer = null; try{ // Create a writer toward the backup file: @@ -455,9 +453,9 @@ public class DefaultUWSBackupManager implements UWSBackupManager { saveReport[0]++; writer.flush(); }catch(JSONException je){ - getLogger().error("Unexpected JSON error while saving the "+saveReport[1]+"-th job of the job list '"+jl.getName()+"' owned by the user '"+user.getID()+"' !", je); + getLogger().error("Unexpected JSON error while saving the " + saveReport[1] + "-th job of the job list '" + jl.getName() + "' owned by the user '" + user.getID() + "' !", je); }catch(UWSException ue){ - getLogger().error("Unexpected UWS error while saving the "+saveReport[1]+"-th job of the job list '"+jl.getName()+"' owned by the user '"+user.getID()+"' !", ue); + getLogger().error("Unexpected UWS error while saving the " + saveReport[1] + "-th job of the job list '" + jl.getName() + "' owned by the user '" + user.getID() + "' !", ue); } } } @@ -474,9 +472,9 @@ public class DefaultUWSBackupManager implements UWSBackupManager { return saveReport; }catch(IOException ie){ - getLogger().error("Unexpected IO error while saving the jobs of user '"+user.getID()+"' !", ie); - }catch (JSONException je) { - getLogger().error("Unexpected JSON error while saving the jobs of user '"+user.getID()+"' !", je); + getLogger().error("Unexpected IO error while saving the jobs of user '" + user.getID() + "' !", ie); + }catch(JSONException je){ + getLogger().error("Unexpected JSON error while saving the jobs of user '" + user.getID() + "' !", je); }finally{ // Close the writer: if (writer != null) @@ -508,14 +506,14 @@ public class DefaultUWSBackupManager implements UWSBackupManager { * * @throws JSONException If there is an error while building the JSON object. */ - protected JSONObject getJSONUser(final JobOwner user) throws JSONException { + protected JSONObject getJSONUser(final JobOwner user) throws JSONException{ JSONObject jsonUser = new JSONObject(); jsonUser.put("id", user.getID()); jsonUser.put("pseudo", user.getPseudo()); if (user.getDataToSave() != null){ Iterator<Map.Entry<String,Object>> itUserData = user.getDataToSave().entrySet().iterator(); while(itUserData.hasNext()){ - Map.Entry<String, Object> userData = itUserData.next(); + Map.Entry<String,Object> userData = itUserData.next(); jsonUser.put(userData.getKey(), userData.getValue()); } } @@ -539,19 +537,18 @@ public class DefaultUWSBackupManager implements UWSBackupManager { * @throws UWSException If there is an error while getting job parameters and serializing them. * @throws JSONException If there is an error while building the JSON object. */ - protected JSONObject getJSONJob(final UWSJob job, final String jlName) throws UWSException, JSONException { + protected JSONObject getJSONJob(final UWSJob job, final String jlName) throws UWSException, JSONException{ JSONObject jsonJob = Json4Uws.getJson(job); - jsonJob.put(UWSJob.PARAM_OWNER, (job != null && job.getOwner() != null)?job.getOwner().getID():null); + jsonJob.put(UWSJob.PARAM_OWNER, (job != null && job.getOwner() != null) ? job.getOwner().getID() : null); jsonJob.put("jobListName", jlName); return jsonJob; } - /* ******************* */ /* RESTORATION METHODS */ /* ******************* */ - public int[] restoreAll() { + public int[] restoreAll(){ // Removes all current jobs from the UWS before restoring it from files: for(JobList jl : uws) jl.clear(); @@ -575,7 +572,7 @@ public class DefaultUWSBackupManager implements UWSBackupManager { try{ itInput = new SingleInputIterator(fileManager.getBackupInput()); }catch(IOException ioe){ - getLogger().error("[restoration] Restoration of the UWS "+uws.getName()+" failed because an unexpected IO error has occured.", ioe); + getLogger().error("[restoration] Restoration of the UWS " + uws.getName() + " failed because an unexpected IO error has occured.", ioe); return null; } } @@ -589,7 +586,7 @@ public class DefaultUWSBackupManager implements UWSBackupManager { // Create the JSON reader: JSONTokener in = new JSONTokener(new InputStreamReader(inputStream)); - HashMap<String, JobOwner> users = new HashMap<String, JobOwner>(); + HashMap<String,JobOwner> users = new HashMap<String,JobOwner>(); String key; JSONObject object; @@ -652,7 +649,7 @@ public class DefaultUWSBackupManager implements UWSBackupManager { } } }catch(UWSException ue){ - getLogger().error("[restoration] The "+nbUsers+"-th user can not be restored !", ue); + getLogger().error("[restoration] The " + nbUsers + "-th user can not be restored !", ue); } } @@ -673,13 +670,13 @@ public class DefaultUWSBackupManager implements UWSBackupManager { if (restoreJob(object, users)) nbRestoredJobs++; }catch(UWSException ue){ - getLogger().error("[restoration] The "+nbJobs+"-th job can not be restored !", ue); + getLogger().error("[restoration] The " + nbJobs + "-th job can not be restored !", ue); } } }// any other key is ignore but with a warning message: else - getLogger().warning("[restoration] Key '"+key+"' ignored because unknown ! The UWS may be not completely restored !"); + getLogger().warning("[restoration] Key '" + key + "' ignored because unknown ! The UWS may be not completely restored !"); } }catch(JSONException je){ getLogger().error("[restoration] Incorrect JSON format for a UWS backup file !", je); @@ -700,11 +697,10 @@ public class DefaultUWSBackupManager implements UWSBackupManager { } if (!userIdentificationEnabled && nbUsers > 0) - getLogger().warning("[restoration] "+nbUsers+" job owners have not been restored because the user identification is disabled in this UWS ! => Jobs of these users have not been restored !"); - + getLogger().warning("[restoration] " + nbUsers + " job owners have not been restored because the user identification is disabled in this UWS ! => Jobs of these users have not been restored !"); // Build the restoration report and log it: - int[] report = new int[]{nbRestoredJobs, nbJobs, nbRestoredUsers, nbUsers}; + int[] report = new int[]{nbRestoredJobs,nbJobs,nbRestoredUsers,nbUsers}; getLogger().uwsRestored(uws, report); return report; @@ -721,14 +717,14 @@ public class DefaultUWSBackupManager implements UWSBackupManager { * * @see JobOwner#restoreData(Map) */ - protected JobOwner getUser(final JSONObject json) throws UWSException { + protected JobOwner getUser(final JSONObject json) throws UWSException{ if (json == null || json.length() == 0) return null; // Fetch all user data: String ID = null, pseudo = null; String[] keys = JSONObject.getNames(json); - Map<String, Object> userData = new HashMap<String, Object>(keys.length-2); + Map<String,Object> userData = new HashMap<String,Object>(keys.length - 2); for(String key : keys){ try{ if (key.equalsIgnoreCase("id")) @@ -738,7 +734,7 @@ public class DefaultUWSBackupManager implements UWSBackupManager { else userData.put(key, json.getString(key)); }catch(JSONException je){ - getLogger().error("[restoration] Incorrect JSON format for the serialization of the user "+ID+" !", je); + getLogger().error("[restoration] Incorrect JSON format for the serialization of the user " + ID + " !", je); } } @@ -761,14 +757,14 @@ public class DefaultUWSBackupManager implements UWSBackupManager { * or if the job list name is incorrect, * or if there is an error with "parameters", "error" and "results". */ - protected boolean restoreJob(final JSONObject json, Map<String, JobOwner> users) throws UWSException { + protected boolean restoreJob(final JSONObject json, Map<String,JobOwner> users) throws UWSException{ if (json == null || json.length() == 0) return false; - String jobListName=null, jobId=null, ownerID=null, tmp; + String jobListName = null, jobId = null, ownerID = null, tmp; //Date destruction=null; - long quote = UWSJob.UNLIMITED_DURATION, /*duration = UWSJob.UNLIMITED_DURATION, */startTime=-1, endTime=-1; - HashMap<String, Object> inputParams = new HashMap<String, Object>(10); + long quote = UWSJob.UNLIMITED_DURATION, /*duration = UWSJob.UNLIMITED_DURATION, */startTime = -1, endTime = -1; + HashMap<String,Object> inputParams = new HashMap<String,Object>(10); //Map<String, Object> params = null; ArrayList<Result> results = null; ErrorSummary error = null; @@ -812,7 +808,7 @@ public class DefaultUWSBackupManager implements UWSBackupManager { tmp = json.getString(key); inputParams.put(UWSJob.PARAM_DESTRUCTION_TIME, UWSJob.dateFormat.parse(tmp)); }catch(ParseException pe){ - getLogger().error("[restoration] Incorrect date format for the '"+key+"' parameter !", pe); + getLogger().error("[restoration] Incorrect date format for the '" + key + "' parameter !", pe); } }// key=START_TIME: @@ -822,7 +818,7 @@ public class DefaultUWSBackupManager implements UWSBackupManager { Date d = UWSJob.dateFormat.parse(tmp); startTime = d.getTime(); }catch(ParseException pe){ - getLogger().error("[restoration] Incorrect date format for the '"+key+"' parameter !", pe); + getLogger().error("[restoration] Incorrect date format for the '" + key + "' parameter !", pe); } }// key=END_TIME: @@ -832,7 +828,7 @@ public class DefaultUWSBackupManager implements UWSBackupManager { Date d = UWSJob.dateFormat.parse(tmp); endTime = d.getTime(); }catch(ParseException pe){ - getLogger().error("[restoration] Incorrect date format for the '"+key+"' parameter !", pe); + getLogger().error("[restoration] Incorrect date format for the '" + key + "' parameter !", pe); } }// key=PARAMETERS: @@ -849,20 +845,20 @@ public class DefaultUWSBackupManager implements UWSBackupManager { }// Ignore any other key but with a warning message: else - getLogger().warning("[restoration] The job attribute '"+key+"' has been ignored because unknown ! A job may be not completely restored !"); + getLogger().warning("[restoration] The job attribute '" + key + "' has been ignored because unknown ! A job may be not completely restored !"); }catch(JSONException je){ - getLogger().error("[restoration] Incorrect JSON format for a job serialization (attribute: \""+key+"\") !", je); + getLogger().error("[restoration] Incorrect JSON format for a job serialization (attribute: \"" + key + "\") !", je); } } // The job list name is REQUIRED: if (jobListName == null || jobListName.isEmpty()) - getLogger().error("[restoration] Missing job list name ! => Can not restore the job "+jobId+" !"); + getLogger().error("[restoration] Missing job list name ! => Can not restore the job " + jobId + " !"); // The job list name MUST correspond to an existing job list: else if (uws.getJobList(jobListName) == null) - getLogger().error("[restoration] No job list named "+jobListName+" ! => Can not restore the job "+jobId+" !"); + getLogger().error("[restoration] No job list named " + jobListName + " ! => Can not restore the job " + jobId + " !"); // The job ID is REQUIRED: else if (jobId == null || jobId.isEmpty()) @@ -875,7 +871,7 @@ public class DefaultUWSBackupManager implements UWSBackupManager { // If the specified user is unknown, display a warning and create the job without owner: if (ownerID != null && !ownerID.isEmpty() && owner == null){ - getLogger().error("[restoration] Unknown job owner: "+ownerID+" ! => Can not restore the job "+jobId+" !"); + getLogger().error("[restoration] Unknown job owner: " + ownerID + " ! => Can not restore the job " + jobId + " !"); return false; } @@ -916,7 +912,7 @@ public class DefaultUWSBackupManager implements UWSBackupManager { * * @see #restoreJob(JSONObject, Map) */ - protected void restoreOtherJobParams(final JSONObject json, final UWSJob job) throws UWSException { + protected void restoreOtherJobParams(final JSONObject json, final UWSJob job) throws UWSException{ ; } @@ -930,17 +926,17 @@ public class DefaultUWSBackupManager implements UWSBackupManager { * * @throws UWSException */ - protected Map<String, Object> getParameters(final JSONObject obj) throws UWSException { + protected Map<String,Object> getParameters(final JSONObject obj) throws UWSException{ if (obj == null || obj.length() == 0) return null; - HashMap<String, Object> params = new HashMap<String, Object>(obj.length()); + HashMap<String,Object> params = new HashMap<String,Object>(obj.length()); String[] names = JSONObject.getNames(obj); for(String n : names){ try{ params.put(n, obj.get(n)); }catch(JSONException je){ - getLogger().error("Incorrect JSON format for the serialization of the parameter '"+n+"' !", je); + getLogger().error("Incorrect JSON format for the serialization of the parameter '" + n + "' !", je); } } return params; @@ -958,18 +954,18 @@ public class DefaultUWSBackupManager implements UWSBackupManager { * * @see {@link #getResult(JSONObject)} */ - protected ArrayList<Result> getResults(final JSONArray array) throws UWSException { + protected ArrayList<Result> getResults(final JSONArray array) throws UWSException{ if (array == null || array.length() == 0) return null; ArrayList<Result> results = new ArrayList<Result>(array.length()); - for(int i=0; i<array.length(); i++){ + for(int i = 0; i < array.length(); i++){ try{ Result r = getResult(array.getJSONObject(i)); if (r != null) results.add(r); }catch(JSONException je){ - getLogger().error("Incorrect JSON format for the serialization of the "+(i+1)+"-th result !", je); + getLogger().error("Incorrect JSON format for the serialization of the " + (i + 1) + "-th result !", je); } } @@ -986,11 +982,11 @@ public class DefaultUWSBackupManager implements UWSBackupManager { * @throws JSONException If there is an error while reading the JSON. * @throws UWSException */ - protected Result getResult(final JSONObject obj) throws JSONException, UWSException { + protected Result getResult(final JSONObject obj) throws JSONException, UWSException{ if (obj == null || obj.length() == 0) return null; - String id=null, type=null, href=null, mime=null; + String id = null, type = null, href = null, mime = null; boolean redirection = false; long size = -1; String[] names = JSONObject.getNames(obj); @@ -1008,7 +1004,7 @@ public class DefaultUWSBackupManager implements UWSBackupManager { else if (n.equalsIgnoreCase("size")) size = obj.getLong(n); else - getLogger().warning("[restoration] The result parameter '"+n+"' has been ignored because unknown ! A result may be not completely restored !"); + getLogger().warning("[restoration] The result parameter '" + n + "' has been ignored because unknown ! A result may be not completely restored !"); } if (id == null){ @@ -1031,11 +1027,11 @@ public class DefaultUWSBackupManager implements UWSBackupManager { * * @throws UWSException */ - protected ErrorSummary getError(final JSONObject obj) throws UWSException { + protected ErrorSummary getError(final JSONObject obj) throws UWSException{ if (obj == null || obj.length() == 0) return null; - String type=null, message=null, details=null; + String type = null, message = null, details = null; String[] names = JSONObject.getNames(obj); for(String n : names){ try{ @@ -1048,7 +1044,7 @@ public class DefaultUWSBackupManager implements UWSBackupManager { else if (n.equalsIgnoreCase("message")) message = obj.getString(n); else - getLogger().warning("[restoration] The error attribute '"+n+"' has been ignored because unknown ! => An error summary may be not completely restored !"); + getLogger().warning("[restoration] The error attribute '" + n + "' has been ignored because unknown ! => An error summary may be not completely restored !"); }catch(JSONException je){ getLogger().error("Incorrect JSON format for an error serialization !", je); } @@ -1059,7 +1055,6 @@ public class DefaultUWSBackupManager implements UWSBackupManager { return null; } - /* **************** */ /* USEFUL ITERATORS */ /* **************** */ @@ -1082,7 +1077,7 @@ public class DefaultUWSBackupManager implements UWSBackupManager { private boolean endReached = false; - public JSONObjectReader(final JSONTokener input, final UWSLog log) throws JSONException { + public JSONObjectReader(final JSONTokener input, final UWSLog log) throws JSONException{ this.input = input; this.logger = log; @@ -1095,7 +1090,7 @@ public class DefaultUWSBackupManager implements UWSBackupManager { input.back(); } - private void readNext() throws JSONException { + private void readNext() throws JSONException{ if (nextKey != null){ nextKey = null; if (!prepareNextPair()){ @@ -1105,98 +1100,98 @@ public class DefaultUWSBackupManager implements UWSBackupManager { } char c = input.nextClean(); - switch (c) { - case 0: - throw input.syntaxError("A JSONObject text must end with '}'"); - case '}': - endReached = true; - return; - default: - input.back(); - nextKey = input.nextValue().toString(); + switch(c){ + case 0: + throw input.syntaxError("A JSONObject text must end with '}'"); + case '}': + endReached = true; + return; + default: + input.back(); + nextKey = input.nextValue().toString(); } /* * The key is followed by ':'. We will also tolerate '=' or '=>'. */ c = input.nextClean(); - if (c == '=') { - if (input.next() != '>') { + if (c == '='){ + if (input.next() != '>'){ input.back(); } - } else if (c != ':') { + }else if (c != ':'){ throw input.syntaxError("Expected a ':' after a key"); } } - private boolean prepareNextPair() throws JSONException { + private boolean prepareNextPair() throws JSONException{ if (!valueGot) skipValue(); /* * Pairs are separated by ','. We will also tolerate ';'. */ - switch (input.nextClean()) { - case ';': - case ',': - if (input.nextClean() == '}') { + switch(input.nextClean()){ + case ';': + case ',': + if (input.nextClean() == '}'){ + endReached = true; + return false; + } + input.back(); + break; + case '}': endReached = true; return false; - } - input.back(); - break; - case '}': - endReached = true; - return false; - default: - throw input.syntaxError("Expected a ',' or '}'"); + default: + throw input.syntaxError("Expected a ',' or '}'"); } return true; } - private void skipValue() throws JSONException { + private void skipValue() throws JSONException{ valueGot = true; input.nextValue(); } - public JSONObject getJSONObject() throws JSONException { + public JSONObject getJSONObject() throws JSONException{ valueGot = true; return new JSONObject(input); } - public JSONArray getJSONArray() throws JSONException { + public JSONArray getJSONArray() throws JSONException{ valueGot = true; return new JSONArray(input); } - public String getString() throws JSONException { + public String getString() throws JSONException{ valueGot = true; return input.nextValue().toString(); } - public Object getValue() throws JSONException { + public Object getValue() throws JSONException{ valueGot = true; return input.nextValue(); } - public JSONArrayReader getArrayReader() throws JSONException { + public JSONArrayReader getArrayReader() throws JSONException{ valueGot = true; return new JSONArrayReader(input, logger); } - public JSONObjectReader getObjectReader() throws JSONException { + public JSONObjectReader getObjectReader() throws JSONException{ valueGot = true; return new JSONObjectReader(input, logger); } @Override - public boolean hasNext() { + public boolean hasNext(){ return !endReached; } @Override - public String next() throws NoSuchElementException { + public String next() throws NoSuchElementException{ if (endReached) throw new NoSuchElementException(); @@ -1211,7 +1206,7 @@ public class DefaultUWSBackupManager implements UWSBackupManager { } @Override - public void remove() throws UnsupportedOperationException { + public void remove() throws UnsupportedOperationException{ throw new UnsupportedOperationException(); } } @@ -1232,27 +1227,27 @@ public class DefaultUWSBackupManager implements UWSBackupManager { private JSONObject nextObj = null; - public JSONArrayReader(final JSONTokener input, final UWSLog log) throws JSONException { + public JSONArrayReader(final JSONTokener input, final UWSLog log) throws JSONException{ this.input = input; this.logger = log; char c = input.nextClean(); switch(c){ - case '[': - closeToken = ']'; - break; - case '(': - closeToken = ')'; - break; - default: - endReached = true; - throw input.syntaxError("A JSONArray text must start with '['"); + case '[': + closeToken = ']'; + break; + case '(': + closeToken = ')'; + break; + default: + endReached = true; + throw input.syntaxError("A JSONArray text must start with '['"); } readNext(); } - protected void readNext() throws JSONException { + protected void readNext() throws JSONException{ nextObj = null; while(nextObj == null && !endReached){ @@ -1265,36 +1260,36 @@ public class DefaultUWSBackupManager implements UWSBackupManager { } // Ensures the next character is allowed (',' or ']'): - switch (c) { - case ';': - case ',': - if (input.nextClean() == ']') { + switch(c){ + case ';': + case ',': + if (input.nextClean() == ']'){ + endReached = true; + return; + } + input.back(); + break; + case ']': + case ')': endReached = true; + if (closeToken != c){ + throw input.syntaxError("Expected a '" + new Character(closeToken) + "'"); + } return; - } - input.back(); - break; - case ']': - case ')': - endReached = true; - if (closeToken != c) { - throw input.syntaxError("Expected a '" + new Character(closeToken) + "'"); - } - return; - default: - endReached = true; - throw input.syntaxError("Expected a ',' or ']'"); + default: + endReached = true; + throw input.syntaxError("Expected a ',' or ']'"); } } } @Override - public boolean hasNext() { + public boolean hasNext(){ return (nextObj != null); } @Override - public JSONObject next() throws NoSuchElementException { + public JSONObject next() throws NoSuchElementException{ if (nextObj == null && endReached) throw new NoSuchElementException(); JSONObject obj = nextObj; @@ -1309,7 +1304,7 @@ public class DefaultUWSBackupManager implements UWSBackupManager { } @Override - public void remove() throws UnsupportedOperationException { + public void remove() throws UnsupportedOperationException{ throw new UnsupportedOperationException(); } @@ -1325,13 +1320,18 @@ public class DefaultUWSBackupManager implements UWSBackupManager { */ protected final static class SingleInputIterator implements Iterator<InputStream> { private InputStream input; + public SingleInputIterator(final InputStream input){ this.input = input; } + @Override - public boolean hasNext() { return (input != null); } + public boolean hasNext(){ + return (input != null); + } + @Override - public InputStream next() throws NoSuchElementException { + public InputStream next() throws NoSuchElementException{ if (input == null) throw new NoSuchElementException(); else{ @@ -1340,8 +1340,9 @@ public class DefaultUWSBackupManager implements UWSBackupManager { return in; } } + @Override - public void remove() throws UnsupportedOperationException { + public void remove() throws UnsupportedOperationException{ throw new UnsupportedOperationException(); } } diff --git a/src/uws/service/error/AbstractServiceErrorWriter.java b/src/uws/service/error/AbstractServiceErrorWriter.java index ab6973b9adda653046486746be12cda4ffa3bbd4..a71b45c2013623a3fae48cb431857716fdc10d06 100644 --- a/src/uws/service/error/AbstractServiceErrorWriter.java +++ b/src/uws/service/error/AbstractServiceErrorWriter.java @@ -38,7 +38,7 @@ import uws.service.log.UWSLog; */ public abstract class AbstractServiceErrorWriter implements ServiceErrorWriter { - protected final String[] managedFormats = new String[]{"application/json", "json", "text/json", "text/html", "html"}; + protected final String[] managedFormats = new String[]{"application/json","json","text/json","text/html","html"}; /** * Logger to use to display the given errors in the appropriate log files. @@ -47,21 +47,21 @@ public abstract class AbstractServiceErrorWriter implements ServiceErrorWriter { protected abstract UWSLog getLogger(); @Override - public void writeError(Throwable t, HttpServletResponse response, HttpServletRequest request, JobOwner user, String action) throws IOException { + public void writeError(Throwable t, HttpServletResponse response, HttpServletRequest request, JobOwner user, String action) throws IOException{ if (t != null && response != null){ - formatError(t, true, ErrorType.FATAL, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, action, user, response, (request!=null)?request.getHeader("Accept"):null); + formatError(t, true, ErrorType.FATAL, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, action, user, response, (request != null) ? request.getHeader("Accept") : null); getLogger().error(t); String errorMsg = t.getMessage(); if (errorMsg == null || errorMsg.trim().isEmpty()) - errorMsg = t.getClass().getName()+" (no error message)"; + errorMsg = t.getClass().getName() + " (no error message)"; getLogger().httpRequest(request, user, action, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, errorMsg, t); } } @Override - public void writeError(String message, ErrorType type, int httpErrorCode, HttpServletResponse response, HttpServletRequest request, JobOwner user, String action) throws IOException { + public void writeError(String message, ErrorType type, int httpErrorCode, HttpServletResponse response, HttpServletRequest request, JobOwner user, String action) throws IOException{ if (message != null && response != null){ - formatError(new Exception(message), false, type, httpErrorCode, action, user, response, (request!=null)?request.getHeader("Accept"):null); + formatError(new Exception(message), false, type, httpErrorCode, action, user, response, (request != null) ? request.getHeader("Accept") : null); getLogger().httpRequest(request, user, action, httpErrorCode, message, null); } } @@ -107,7 +107,7 @@ public abstract class AbstractServiceErrorWriter implements ServiceErrorWriter { * @see #formatHTMLError(Throwable, boolean, ErrorType, int, String, JobOwner, HttpServletResponse) * @see #formatJSONError(Throwable, boolean, ErrorType, int, String, JobOwner, HttpServletResponse) */ - protected void formatError(final Throwable t, final boolean printStackTrace, final ErrorType type, final int httpErrorCode, final String action, final JobOwner user, final HttpServletResponse response, final String acceptHeader) throws IOException { + protected void formatError(final Throwable t, final boolean printStackTrace, final ErrorType type, final int httpErrorCode, final String action, final JobOwner user, final HttpServletResponse response, final String acceptHeader) throws IOException{ // Reset the whole response to ensure the output stream is free: if (response.isCommitted()) return; @@ -134,7 +134,7 @@ public abstract class AbstractServiceErrorWriter implements ServiceErrorWriter { * * @throws IOException If there is an error while writing the given exception. */ - protected void formatHTMLError(final Throwable t, final boolean printStackTrace, final ErrorType type, final int httpErrorCode, final String action, final JobOwner user, final HttpServletResponse response) throws IOException { + protected void formatHTMLError(final Throwable t, final boolean printStackTrace, final ErrorType type, final int httpErrorCode, final String action, final JobOwner user, final HttpServletResponse response) throws IOException{ // Set the HTTP status code and the content type of the response: response.setStatus(httpErrorCode); response.setContentType(UWSSerializer.MIME_TYPE_HTML); @@ -159,30 +159,30 @@ public abstract class AbstractServiceErrorWriter implements ServiceErrorWriter { out.println("\t</head>\n\t<body>"); // Title: - String errorColor = (type == ErrorType.FATAL)?"red":"orange"; - out.println("\t\t<h1 style=\"text-align: center; background-color:"+errorColor+"; color: white; font-weight: bold;\">SERVICE ERROR - "+httpErrorCode+"</h1>"); + String errorColor = (type == ErrorType.FATAL) ? "red" : "orange"; + out.println("\t\t<h1 style=\"text-align: center; background-color:" + errorColor + "; color: white; font-weight: bold;\">SERVICE ERROR - " + httpErrorCode + "</h1>"); // Description part: out.println("\t\t<h2>Description</h2>"); out.println("\t\t<ul>"); - out.println("\t\t\t<li><b>Type: </b>"+type+"</li>"); + out.println("\t\t\t<li><b>Type: </b>" + type + "</li>"); if (action != null && !action.trim().isEmpty()) - out.println("\t\t\t<li><b>Action: </b>"+action+"</li>"); - String context=null; + out.println("\t\t\t<li><b>Action: </b>" + action + "</li>"); + String context = null; String msg = t.getMessage(); if (msg != null && !msg.trim().isEmpty()){ - int start=msg.indexOf("["), end=msg.indexOf("]"); + int start = msg.indexOf("["), end = msg.indexOf("]"); if (start >= 0 && start < end){ - context = msg.substring(start+1, end); - msg = msg.substring(end+1); + context = msg.substring(start + 1, end); + msg = msg.substring(end + 1); } }else msg = ""; if (context != null) - out.println("\t\t\t<li><b>Context: </b>"+context+"</li>"); + out.println("\t\t\t<li><b>Context: </b>" + context + "</li>"); if (printStackTrace) - out.println("\t\t\t<li><b>Exception: </b>"+t.getClass().getName()+"</li>"); - out.println("\t\t\t<li><b>Message:</b><p>"+msg+"</p></li>"); + out.println("\t\t\t<li><b>Exception: </b>" + t.getClass().getName() + "</li>"); + out.println("\t\t\t<li><b>Message:</b><p>" + msg + "</p></li>"); out.println("\t\t</ul>"); // Stack trace part: @@ -193,15 +193,15 @@ public abstract class AbstractServiceErrorWriter implements ServiceErrorWriter { out.println("\t\t<table style=\"width: ihnerit;\">"); out.println("\t\t\t<tr><th>Class</th><th>Method</th><th>Line</th></tr>"); StackTraceElement[] trace = cause.getStackTrace(); - for(int i=0; i<trace.length; i++) - out.println("\t\t\t<tr"+((i%2 != 0)?" class=\"alt\"":"")+"><td>"+trace[i].getClassName()+"</td><td>"+trace[i].getMethodName()+"</td><td>"+trace[i].getLineNumber()+"</td></tr>"); + for(int i = 0; i < trace.length; i++) + out.println("\t\t\t<tr" + ((i % 2 != 0) ? " class=\"alt\"" : "") + "><td>" + trace[i].getClassName() + "</td><td>" + trace[i].getMethodName() + "</td><td>" + trace[i].getLineNumber() + "</td></tr>"); out.println("\t\t</table>"); // Print the stack trace of the "next" error: cause = cause.getCause(); if (cause != null){ - out.println("\t\t<p><b>Caused by "+cause.getClass().getName()+":</b></p>"); - out.println("\t\t<p>"+cause.getMessage()+"</p>"); + out.println("\t\t<p><b>Caused by " + cause.getClass().getName() + ":</b></p>"); + out.println("\t\t<p>" + cause.getMessage() + "</p>"); } }while(cause != null); } @@ -224,7 +224,7 @@ public abstract class AbstractServiceErrorWriter implements ServiceErrorWriter { * * @throws IOException If there is an error while writing the given exception. */ - protected void formatJSONError(final Throwable t, final boolean printStackTrace, final ErrorType type, final int httpErrorCode, final String action, final JobOwner user, final HttpServletResponse response) throws IOException { + protected void formatJSONError(final Throwable t, final boolean printStackTrace, final ErrorType type, final int httpErrorCode, final String action, final JobOwner user, final HttpServletResponse response) throws IOException{ // Set the HTTP status code and the content type of the response: response.setStatus(httpErrorCode); response.setContentType(UWSSerializer.MIME_TYPE_JSON); @@ -238,13 +238,13 @@ public abstract class AbstractServiceErrorWriter implements ServiceErrorWriter { json.key("errortype").value(type.toString()); json.key("action").value(action); - String context=null; + String context = null; String msg = t.getMessage(); if (msg != null && !msg.trim().isEmpty()){ - int start=msg.indexOf("["), end=msg.indexOf("]"); + int start = msg.indexOf("["), end = msg.indexOf("]"); if (start >= 0 && start < end){ - context = msg.substring(start+1, end); - msg = msg.substring(end+1); + context = msg.substring(start + 1, end); + msg = msg.substring(end + 1); } }else msg = ""; @@ -263,7 +263,7 @@ public abstract class AbstractServiceErrorWriter implements ServiceErrorWriter { json.key("exception").value(cause.getClass().getName()); json.key("stacktrace").array(); StackTraceElement[] trace = cause.getStackTrace(); - for(int i=0; i<trace.length; i++){ + for(int i = 0; i < trace.length; i++){ json.object(); json.key("class").value(trace[i].getClassName()); json.key("method").value(trace[i].getMethodName()); diff --git a/src/uws/service/error/DefaultUWSErrorWriter.java b/src/uws/service/error/DefaultUWSErrorWriter.java index 7f4c68603cb9009a91f5d6ab69fd12574926e071..82529f65d5cbf231655ad006924be7868e91e2c5 100644 --- a/src/uws/service/error/DefaultUWSErrorWriter.java +++ b/src/uws/service/error/DefaultUWSErrorWriter.java @@ -44,7 +44,7 @@ public class DefaultUWSErrorWriter extends AbstractServiceErrorWriter { } @Override - public void writeError(Throwable t, HttpServletResponse response, HttpServletRequest request, JobOwner user, String action) throws IOException { + public void writeError(Throwable t, HttpServletResponse response, HttpServletRequest request, JobOwner user, String action) throws IOException{ if (t instanceof UWSException){ UWSException ue = (UWSException)t; formatError(ue, (ue.getMessage() == null || ue.getMessage().trim().isEmpty()), ue.getUWSErrorType(), ue.getHttpErrorCode(), action, user, response, request.getHeader("Accept")); diff --git a/src/uws/service/file/DefaultOwnerGroupIdentifier.java b/src/uws/service/file/DefaultOwnerGroupIdentifier.java index b67b9f35d3ad2fd68aee2f71de709ed05d57c924..a55645e1fed60b8098baa99c8cc26e0b8a8eef01 100644 --- a/src/uws/service/file/DefaultOwnerGroupIdentifier.java +++ b/src/uws/service/file/DefaultOwnerGroupIdentifier.java @@ -39,7 +39,7 @@ public class DefaultOwnerGroupIdentifier implements OwnerGroupIdentifier { protected static final Pattern DIR_PREFIX_PATTERN = Pattern.compile(".*([a-zA-Z])[^a-zA-Z]*"); @Override - public String getOwnerGroup(JobOwner owner) { + public String getOwnerGroup(JobOwner owner){ if (owner == null || owner.getID() == null || owner.getID().trim().isEmpty()) return null; else{ diff --git a/src/uws/service/file/LocalUWSFileManager.java b/src/uws/service/file/LocalUWSFileManager.java index 3a6a66cfb5d5af034372fb96bd7c67342d66ae78..41f89f79d6b53b168d19a5a9018a4204333ec9d7 100644 --- a/src/uws/service/file/LocalUWSFileManager.java +++ b/src/uws/service/file/LocalUWSFileManager.java @@ -82,8 +82,7 @@ public class LocalUWSFileManager implements UWSFileManager { protected final boolean groupUserDirectories; protected final OwnerGroupIdentifier ownerGroupId; - protected Map<String, PrintWriter> logOutputs = new HashMap<String, PrintWriter>(); - + protected Map<String,PrintWriter> logOutputs = new HashMap<String,PrintWriter>(); /** * <p>Builds a {@link UWSFileManager} which manages all UWS files in the given directory.</p> @@ -98,7 +97,7 @@ public class LocalUWSFileManager implements UWSFileManager { * * @see #LocalUWSFileManager(File, boolean, boolean, OwnerGroupIdentifier) */ - public LocalUWSFileManager(final File root) throws UWSException { + public LocalUWSFileManager(final File root) throws UWSException{ this(root, true, true, null); } @@ -118,7 +117,7 @@ public class LocalUWSFileManager implements UWSFileManager { * * @see #LocalUWSFileManager(File, boolean, boolean, OwnerGroupIdentifier) */ - public LocalUWSFileManager(final File root, final boolean oneDirectoryForEachUser, final boolean groupUserDirectories) throws UWSException { + public LocalUWSFileManager(final File root, final boolean oneDirectoryForEachUser, final boolean groupUserDirectories) throws UWSException{ this(root, oneDirectoryForEachUser, groupUserDirectories, null); } @@ -138,7 +137,7 @@ public class LocalUWSFileManager implements UWSFileManager { * * @throws UWSException If the given root directory is <i>null</i>, is not a directory or has not the READ and WRITE permissions. */ - public LocalUWSFileManager(final File root, final boolean oneDirectoryForEachUser, final boolean groupUserDirectories, final OwnerGroupIdentifier ownerGroupIdentifier) throws UWSException { + public LocalUWSFileManager(final File root, final boolean oneDirectoryForEachUser, final boolean groupUserDirectories, final OwnerGroupIdentifier ownerGroupIdentifier) throws UWSException{ if (root == null) throw new NullPointerException("Missing root directory ! Impossible to create a LocalUWSFileManager."); else if (!root.exists()){ @@ -197,7 +196,7 @@ public class LocalUWSFileManager implements UWSFileManager { * * @throws IOException If there is an error while removing the owner directory. */ - protected void cleanOwnerDirectory(final JobOwner owner) throws IOException { + protected void cleanOwnerDirectory(final JobOwner owner) throws IOException{ // Remove the owner directory if empty or if only the owner backup file exists: if (owner != null && oneDirectoryForEachUser){ File ownerDir = getOwnerDirectory(owner); @@ -234,19 +233,19 @@ public class LocalUWSFileManager implements UWSFileManager { * * @return Name of the log type group. */ - protected String getLogTypeGroup(final UWSLogType logType) { + protected String getLogTypeGroup(final UWSLogType logType){ switch(logType){ - case INFO: - case WARNING: - case ERROR: - return "DefaultLog"; - case DEBUG: - case HTTP_ACTIVITY: - return logType.toString(); - case CUSTOM: - return logType.getCustomType(); - default: - return UNKNOWN_LOG_TYPE_GROUP; + case INFO: + case WARNING: + case ERROR: + return "DefaultLog"; + case DEBUG: + case HTTP_ACTIVITY: + return logType.toString(); + case CUSTOM: + return logType.getCustomType(); + default: + return UNKNOWN_LOG_TYPE_GROUP; } } @@ -281,7 +280,7 @@ public class LocalUWSFileManager implements UWSFileManager { } @Override - public InputStream getLogInput(final UWSLogType logType) throws IOException { + public InputStream getLogInput(final UWSLogType logType) throws IOException{ String logTypeGroup = getLogTypeGroup(logType); File logFile = getLogFile(logTypeGroup); if (logFile.exists()) @@ -291,7 +290,7 @@ public class LocalUWSFileManager implements UWSFileManager { } @Override - public PrintWriter getLogOutput(final UWSLogType logType) throws IOException { + public PrintWriter getLogOutput(final UWSLogType logType) throws IOException{ String logTypeGroup = getLogTypeGroup(logType); PrintWriter output = logOutputs.get(logTypeGroup); if (output == null){ @@ -308,9 +307,9 @@ public class LocalUWSFileManager implements UWSFileManager { * Print a header into the log file so that separating older log messages to the new ones. */ protected void printLogHeader(final PrintWriter out){ - String msgHeader = "########################################### LOG STARTS "+dateFormat.format(new Date())+" ###########################################"; + String msgHeader = "########################################### LOG STARTS " + dateFormat.format(new Date()) + " ###########################################"; StringBuffer buf = new StringBuffer(""); - for(int i=0; i<msgHeader.length(); i++) + for(int i = 0; i < msgHeader.length(); i++) buf.append('#'); String separator = buf.toString(); @@ -337,7 +336,7 @@ public class LocalUWSFileManager implements UWSFileManager { * @see UWSToolBox#getFileExtension(String) */ protected String getResultFileName(final Result result, final UWSJob job){ - String fileName = job.getJobId()+"_"; + String fileName = job.getJobId() + "_"; if (result != null && result.getId() != null && !result.getId().trim().isEmpty()) fileName += result.getId(); @@ -345,7 +344,7 @@ public class LocalUWSFileManager implements UWSFileManager { fileName += Result.DEFAULT_RESULT_NAME; String fileExt = UWSToolBox.getFileExtension(result.getMimeType()); - fileExt = (fileExt == null) ? "" : ("."+fileExt); + fileExt = (fileExt == null) ? "" : ("." + fileExt); fileName += fileExt; return fileName; @@ -368,20 +367,20 @@ public class LocalUWSFileManager implements UWSFileManager { } @Override - public InputStream getResultInput(Result result, UWSJob job) throws IOException { + public InputStream getResultInput(Result result, UWSJob job) throws IOException{ File resultFile = getResultFile(result, job); return resultFile.exists() ? new FileInputStream(resultFile) : null; } @Override - public OutputStream getResultOutput(Result result, UWSJob job) throws IOException { + public OutputStream getResultOutput(Result result, UWSJob job) throws IOException{ File resultFile = getResultFile(result, job); createParentDir(resultFile); return new FileOutputStream(resultFile); } @Override - public long getResultSize(Result result, UWSJob job) throws IOException { + public long getResultSize(Result result, UWSJob job) throws IOException{ File resultFile = getResultFile(result, job); if (resultFile == null || !resultFile.exists()) return -1; @@ -390,7 +389,7 @@ public class LocalUWSFileManager implements UWSFileManager { } @Override - public boolean deleteResult(Result result, UWSJob job) throws IOException { + public boolean deleteResult(Result result, UWSJob job) throws IOException{ boolean deleted = getResultFile(result, job).delete(); if (deleted) @@ -399,7 +398,6 @@ public class LocalUWSFileManager implements UWSFileManager { return deleted; } - /* ********************** */ /* ERROR FILES MANAGEMENT */ /* ********************** */ @@ -412,8 +410,8 @@ public class LocalUWSFileManager implements UWSFileManager { * * @return Name of the file corresponding to the described error. */ - protected String getErrorFileName(final ErrorSummary error, final UWSJob job) { - return job.getJobId()+"_ERROR.log"; + protected String getErrorFileName(final ErrorSummary error, final UWSJob job){ + return job.getJobId() + "_ERROR.log"; } /** @@ -433,20 +431,20 @@ public class LocalUWSFileManager implements UWSFileManager { } @Override - public InputStream getErrorInput(ErrorSummary error, UWSJob job) throws IOException { + public InputStream getErrorInput(ErrorSummary error, UWSJob job) throws IOException{ File errorFile = getErrorFile(error, job); return errorFile.exists() ? new FileInputStream(errorFile) : null; } @Override - public OutputStream getErrorOutput(ErrorSummary error, UWSJob job) throws IOException { + public OutputStream getErrorOutput(ErrorSummary error, UWSJob job) throws IOException{ File errorFile = getErrorFile(error, job); createParentDir(errorFile); return new FileOutputStream(errorFile); } @Override - public long getErrorSize(ErrorSummary error, UWSJob job) throws IOException { + public long getErrorSize(ErrorSummary error, UWSJob job) throws IOException{ File errorFile = getErrorFile(error, job); if (errorFile == null || !errorFile.exists()) return -1; @@ -455,7 +453,7 @@ public class LocalUWSFileManager implements UWSFileManager { } @Override - public boolean deleteError(ErrorSummary error, UWSJob job) throws IOException { + public boolean deleteError(ErrorSummary error, UWSJob job) throws IOException{ boolean deleted = getErrorFile(error, job).delete(); if (deleted) @@ -464,7 +462,6 @@ public class LocalUWSFileManager implements UWSFileManager { return deleted; } - /* *********************** */ /* BACKUP FILES MANAGEMENT */ /* *********************** */ @@ -478,14 +475,14 @@ public class LocalUWSFileManager implements UWSFileManager { * * @throws IllegalArgumentException If the given owner is <i>null</i> or an empty string. */ - protected String getBackupFileName(final JobOwner owner) throws IllegalArgumentException { + protected String getBackupFileName(final JobOwner owner) throws IllegalArgumentException{ if (owner == null || owner.getID() == null || owner.getID().trim().isEmpty()) throw new IllegalArgumentException("Missing owner ! Can not get the backup file of an unknown owner. See LocalUWSFileManager.getBackupFile(JobOwner)"); - return owner.getID().replaceAll(File.separator, "_")+".backup"; + return owner.getID().replaceAll(File.separator, "_") + ".backup"; } @Override - public InputStream getBackupInput(JobOwner owner) throws IllegalArgumentException, IOException { + public InputStream getBackupInput(JobOwner owner) throws IllegalArgumentException, IOException{ File backupFile = new File(getOwnerDirectory(owner), getBackupFileName(owner)); return backupFile.exists() ? new FileInputStream(backupFile) : null; } @@ -496,7 +493,7 @@ public class LocalUWSFileManager implements UWSFileManager { } @Override - public OutputStream getBackupOutput(JobOwner owner) throws IllegalArgumentException, IOException { + public OutputStream getBackupOutput(JobOwner owner) throws IllegalArgumentException, IOException{ File backupFile = new File(getOwnerDirectory(owner), getBackupFileName(owner)); createParentDir(backupFile); return new FileOutputStream(backupFile); @@ -508,24 +505,23 @@ public class LocalUWSFileManager implements UWSFileManager { * * @return The name of the UWS general backup file. */ - protected String getBackupFileName() { + protected String getBackupFileName(){ return DEFAULT_BACKUP_FILE_NAME; } @Override - public InputStream getBackupInput() throws IOException { + public InputStream getBackupInput() throws IOException{ File backupFile = new File(rootDirectory, getBackupFileName()); return backupFile.exists() ? new FileInputStream(backupFile) : null; } @Override - public OutputStream getBackupOutput() throws IOException { + public OutputStream getBackupOutput() throws IOException{ File backupFile = new File(rootDirectory, getBackupFileName()); createParentDir(backupFile); return new FileOutputStream(backupFile); } - /* ************** */ /* TOOL FUNCTIONS */ /* ************** */ @@ -598,7 +594,7 @@ public class LocalUWSFileManager implements UWSFileManager { } @Override - public boolean hasNext() { + public boolean hasNext(){ return itBackupFiles != null && itBackupFiles.hasNext(); } @@ -609,24 +605,24 @@ public class LocalUWSFileManager implements UWSFileManager { * @see java.util.Iterator#next() */ @Override - public InputStream next() throws NoSuchElementException { + public InputStream next() throws NoSuchElementException{ if (itBackupFiles == null) throw new NoSuchElementException(); - try { + try{ File f = itBackupFiles.next(); if (!itBackupFiles.hasNext()) itBackupFiles = null; return (f == null || !f.exists()) ? null : new FileInputStream(f); - } catch (FileNotFoundException e) { + }catch(FileNotFoundException e){ return null; } } @Override - public void remove() { + public void remove(){ throw new UnsupportedOperationException(); } @@ -640,7 +636,7 @@ public class LocalUWSFileManager implements UWSFileManager { */ protected final static class DirectoryFilter implements FileFilter { @Override - public boolean accept(File f) { + public boolean accept(File f){ return f != null && f.isDirectory(); } } @@ -653,6 +649,7 @@ public class LocalUWSFileManager implements UWSFileManager { */ protected final class OwnerFileFilter implements FileFilter { protected String ownerID = null; + /** * Sets the ID of the user whose the backup file must be returned. * If <i>null</i>, all the found backup files will be returned EXCEPT the backup file for the whole UWS. @@ -662,14 +659,15 @@ public class LocalUWSFileManager implements UWSFileManager { public void setOwnerID(final String ownerID){ this.ownerID = ownerID; } + @Override - public boolean accept(File f) { + public boolean accept(File f){ if (f == null || f.isDirectory()) return false; else if (ownerID == null || ownerID.trim().isEmpty()) return f.getName().endsWith(".backup") && !f.getName().equalsIgnoreCase(getBackupFileName()); else - return f.getName().equalsIgnoreCase(ownerID+".backup"); + return f.getName().equalsIgnoreCase(ownerID + ".backup"); } } diff --git a/src/uws/service/file/UWSFileManager.java b/src/uws/service/file/UWSFileManager.java index 45ff5469cab00d6a48534810a4b6bfc7f47b1019..bc8520b60b1ffa9cf3d2165b6399c94478da680f 100644 --- a/src/uws/service/file/UWSFileManager.java +++ b/src/uws/service/file/UWSFileManager.java @@ -70,7 +70,6 @@ public interface UWSFileManager { */ public PrintWriter getLogOutput(final UWSLogType logType) throws IOException; - /* *********************** */ /* RESULT FILES MANAGEMENT */ /* *********************** */ @@ -112,7 +111,6 @@ public interface UWSFileManager { */ public boolean deleteResult(final Result result, final UWSJob job) throws IOException; - /* ********************** */ /* ERROR FILES MANAGEMENT */ /* ********************** */ @@ -154,7 +152,6 @@ public interface UWSFileManager { */ public boolean deleteError(final ErrorSummary error, final UWSJob job) throws IOException; - /* *********************** */ /* BACKUP FILES MANAGEMENT */ /* *********************** */ diff --git a/src/uws/service/log/DefaultUWSLog.java b/src/uws/service/log/DefaultUWSLog.java index 452217692d9cbe48b45ac7ae77340ba59fe1937c..5fd9586ef9d5052a1e8393df7c16e36ffe539bb6 100644 --- a/src/uws/service/log/DefaultUWSLog.java +++ b/src/uws/service/log/DefaultUWSLog.java @@ -63,7 +63,6 @@ public class DefaultUWSLog implements UWSLog { */ protected int minResponseCodeForStackTrace = 500; - /** * <p>Builds a {@link UWSLog} which will use the file manager * of the given UWS to get the log output (see {@link UWSFileManager#getLogOutput(UWSLogType)}).</p> @@ -105,7 +104,7 @@ public class DefaultUWSLog implements UWSLog { * * @param output An output stream. */ - public DefaultUWSLog(final OutputStream output) { + public DefaultUWSLog(final OutputStream output){ uws = null; fileManager = null; defaultOutput = new PrintWriter(output); @@ -129,7 +128,7 @@ public class DefaultUWSLog implements UWSLog { * Gets the date formatter/parser to use for any date read/write into this logger. * @return A date formatter/parser. */ - public final DateFormat getDateFormat() { + public final DateFormat getDateFormat(){ return dateFormat; } @@ -137,7 +136,7 @@ public class DefaultUWSLog implements UWSLog { * Sets the date formatter/parser to use for any date read/write into this logger. * @param dateFormat The date formatter/parser to use from now. (MUST BE DIFFERENT FROM NULL) */ - public final void setDateFormat(final DateFormat dateFormat) { + public final void setDateFormat(final DateFormat dateFormat){ if (dateFormat != null) this.dateFormat = dateFormat; } @@ -215,7 +214,7 @@ public class DefaultUWSLog implements UWSLog { out.println(msg); else if (t != null && t instanceof UWSException){ UWSException uwsEx = (UWSException)t; - out.println("EXCEPTION "+uwsEx.getClass().getName()+"\t"+uwsEx.getUWSErrorType()+"\tHTTP-"+uwsEx.getHttpErrorCode()+"\t"+uwsEx.getMessage()); + out.println("EXCEPTION " + uwsEx.getClass().getName() + "\t" + uwsEx.getUWSErrorType() + "\tHTTP-" + uwsEx.getHttpErrorCode() + "\t" + uwsEx.getMessage()); }else out.println(); // Print the stack trace, if any: @@ -225,22 +224,44 @@ public class DefaultUWSLog implements UWSLog { } @Override - public void debug(String msg) { log(UWSLogType.DEBUG, msg, null); } - @Override - public void debug(Throwable t) { log(UWSLogType.DEBUG, null, t); } + public void debug(String msg){ + log(UWSLogType.DEBUG, msg, null); + } + @Override - public void debug(String msg, Throwable t) { log(UWSLogType.DEBUG, msg, t); } + public void debug(Throwable t){ + log(UWSLogType.DEBUG, null, t); + } + @Override - public void info(String msg) { log(UWSLogType.INFO, msg, null); } + public void debug(String msg, Throwable t){ + log(UWSLogType.DEBUG, msg, t); + } + @Override - public void warning(String msg) { log(UWSLogType.WARNING, msg, null); } + public void info(String msg){ + log(UWSLogType.INFO, msg, null); + } + @Override - public void error(String msg) { log(UWSLogType.ERROR, msg, null); } + public void warning(String msg){ + log(UWSLogType.WARNING, msg, null); + } + @Override - public void error(Throwable t) { log(UWSLogType.ERROR, null, t); } + public void error(String msg){ + log(UWSLogType.ERROR, msg, null); + } + @Override - public void error(String msg, Throwable t) { log(UWSLogType.ERROR, msg, t); } + public void error(Throwable t){ + log(UWSLogType.ERROR, null, t); + } + @Override + public void error(String msg, Throwable t){ + log(UWSLogType.ERROR, msg, t); + } /* **************************** */ /* METHODS ABOUT THE UWS STATUS */ @@ -254,77 +275,76 @@ public class DefaultUWSLog implements UWSLog { * @return Name of the given UWS (followed by a space: " ") or an empty string (""). */ protected final static String getUWSName(final UWS uws){ - return ((uws != null && uws.getName() != null && !uws.getName().trim().isEmpty()) ? (uws.getName()+" ") : ""); + return ((uws != null && uws.getName() != null && !uws.getName().trim().isEmpty()) ? (uws.getName() + " ") : ""); } @Override - public void uwsInitialized(UWS uws) { + public void uwsInitialized(UWS uws){ if (uws != null){ - String msg = "UWS "+getUWSName(uws)+"INITIALIZED !"; + String msg = "UWS " + getUWSName(uws) + "INITIALIZED !"; info(msg); log(UWSLogType.HTTP_ACTIVITY, msg, null); } } @Override - public void ownerJobsSaved(JobOwner owner, int[] report) { + public void ownerJobsSaved(JobOwner owner, int[] report){ if (owner != null){ - String strReport = (report == null || report.length != 2) ? "???" : (report[0]+"/"+report[1]); - String ownerPseudo = (owner.getPseudo() != null && !owner.getPseudo().trim().isEmpty() && !owner.getID().equals(owner.getPseudo())) ? (" (alias "+owner.getPseudo()+")") : ""; - info(strReport+" saved jobs for the user "+owner.getID()+ownerPseudo+" !"); + String strReport = (report == null || report.length != 2) ? "???" : (report[0] + "/" + report[1]); + String ownerPseudo = (owner.getPseudo() != null && !owner.getPseudo().trim().isEmpty() && !owner.getID().equals(owner.getPseudo())) ? (" (alias " + owner.getPseudo() + ")") : ""; + info(strReport + " saved jobs for the user " + owner.getID() + ownerPseudo + " !"); } } @Override - public void uwsRestored(UWS uws, int[] report) { + public void uwsRestored(UWS uws, int[] report){ if (uws != null){ - String strReport = (report == null || report.length != 4) ? "[Unknown report format !]" : (report[0]+"/"+report[1]+" restored jobs and "+report[2]+"/"+report[3]+" restored users"); - info("UWS "+getUWSName(uws)+"RESTORED => "+strReport); + String strReport = (report == null || report.length != 4) ? "[Unknown report format !]" : (report[0] + "/" + report[1] + " restored jobs and " + report[2] + "/" + report[3] + " restored users"); + info("UWS " + getUWSName(uws) + "RESTORED => " + strReport); } } @Override - public void uwsSaved(UWS uws, int[] report) { + public void uwsSaved(UWS uws, int[] report){ if (uws != null){ - String strReport = (report == null || report.length != 4) ? "[Unknown report format !]" : (report[0]+"/"+report[1]+" saved jobs and "+report[2]+"/"+report[3]+" saved users"); - info("UWS "+getUWSName(uws)+"SAVED => "+strReport); + String strReport = (report == null || report.length != 4) ? "[Unknown report format !]" : (report[0] + "/" + report[1] + " saved jobs and " + report[2] + "/" + report[3] + " saved users"); + info("UWS " + getUWSName(uws) + "SAVED => " + strReport); } } @Override - public void jobCreated(UWSJob job) { + public void jobCreated(UWSJob job){ if (job != null){ String jlName = (job.getJobList() != null) ? job.getJobList().getName() : null; - info("JOB "+job.getJobId()+" CREATED" + ((jlName!=null) ? (" and added into "+jlName) : "") + " !" ); + info("JOB " + job.getJobId() + " CREATED" + ((jlName != null) ? (" and added into " + jlName) : "") + " !"); } } @Override - public void jobDestroyed(UWSJob job, JobList jl) { + public void jobDestroyed(UWSJob job, JobList jl){ if (job != null){ String jlName = (jl != null) ? jl.getName() : null; - info("JOB "+job.getJobId()+" DESTROYED" + ((jlName!=null) ? (" and removed from "+jlName) : "") + " !" ); + info("JOB " + job.getJobId() + " DESTROYED" + ((jlName != null) ? (" and removed from " + jlName) : "") + " !"); } } @Override - public void jobStarted(UWSJob job) { + public void jobStarted(UWSJob job){ if (job != null){ - info("JOB "+job.getJobId()+" STARTED !" ); + info("JOB " + job.getJobId() + " STARTED !"); } } @Override - public void jobFinished(UWSJob job) { + public void jobFinished(UWSJob job){ if (job != null){ long endTime = (job.getEndTime() == null) ? -1 : job.getEndTime().getTime(); long startTime = (job.getStartTime() == null) ? -1 : job.getStartTime().getTime(); - long duration = (endTime > 0 && startTime > 0) ? (endTime-startTime) : -1; - info("JOB "+job.getJobId()+" FINISHED with the phase "+job.getPhase() + ((duration>0) ? " after an execution of "+duration+"ms" : "" ) + " !"); + long duration = (endTime > 0 && startTime > 0) ? (endTime - startTime) : -1; + info("JOB " + job.getJobId() + " FINISHED with the phase " + job.getPhase() + ((duration > 0) ? " after an execution of " + duration + "ms" : "") + " !"); } } - /* ************* */ /* HTTP ACTIVITY */ /* ************* */ @@ -387,34 +407,33 @@ public class DefaultUWSLog implements UWSLog { str.append(request.getHeader("User-Agent")); // Send the log message to the log file: - log(UWSLogType.HTTP_ACTIVITY, str.toString(), (responseStatusCode >= minResponseCodeForStackTrace)?responseError:null); + log(UWSLogType.HTTP_ACTIVITY, str.toString(), (responseStatusCode >= minResponseCodeForStackTrace) ? responseError : null); } } - /* ********************** */ /* THREAD STATUS MESSAGES */ /* ********************** */ @Override - public void threadStarted(Thread t, String task) { + public void threadStarted(Thread t, String task){ if (t != null) - info("THREAD "+t.getId()+" STARTED\t"+t.getName()+"\t"+t.getState()+"\t"+t.getThreadGroup().activeCount()+" active threads"); + info("THREAD " + t.getId() + " STARTED\t" + t.getName() + "\t" + t.getState() + "\t" + t.getThreadGroup().activeCount() + " active threads"); } @Override - public void threadFinished(Thread t, String task) { + public void threadFinished(Thread t, String task){ if (t != null) - info("THREAD "+t.getId()+" ENDED\t"+t.getName()+"\t"+t.getState()+"\t"+t.getThreadGroup().activeCount()+" active threads"); + info("THREAD " + t.getId() + " ENDED\t" + t.getName() + "\t" + t.getState() + "\t" + t.getThreadGroup().activeCount() + " active threads"); } @Override - public void threadInterrupted(Thread t, String task, Throwable error) { + public void threadInterrupted(Thread t, String task, Throwable error){ if (t != null){ if (error == null || error instanceof InterruptedException) - info("THREAD "+t.getId()+" CANCELLED\t"+t.getName()+"\t"+t.getState()+"\t"+t.getThreadGroup().activeCount()+" active threads"); + info("THREAD " + t.getId() + " CANCELLED\t" + t.getName() + "\t" + t.getState() + "\t" + t.getThreadGroup().activeCount() + " active threads"); else - error("THREAD "+t.getId()+" INTERRUPTED\t"+t.getName()+"\t"+t.getState()+"\t"+t.getThreadGroup().activeCount()+" active threads", error); + error("THREAD " + t.getId() + " INTERRUPTED\t" + t.getName() + "\t" + t.getState() + "\t" + t.getThreadGroup().activeCount() + " active threads", error); } } diff --git a/src/uws/service/log/UWSLog.java b/src/uws/service/log/UWSLog.java index 63d4a7b29e51bc24c342cb23efbc4fe7361c87fa..350fe0244bca769ca5e4881ad4074784dcaae624 100644 --- a/src/uws/service/log/UWSLog.java +++ b/src/uws/service/log/UWSLog.java @@ -90,7 +90,6 @@ public interface UWSLog { */ public void error(final String msg, final Throwable t); - /* *************************************** */ /* LOGGING METHODS TO WATCH THE UWS STATUS */ /* *************************************** */ @@ -148,7 +147,6 @@ public interface UWSLog { */ public void jobDestroyed(final UWSJob job, final JobList jl); - /* ************* */ /* HTTP ACTIVITY */ /* ************* */ @@ -164,7 +162,6 @@ public interface UWSLog { */ public void httpRequest(final HttpServletRequest request, final JobOwner user, final String uwsAction, final int responseStatusCode, final String responseMsg, final Throwable responseError); - /* ********************** */ /* THREAD STATUS MESSAGES */ /* ********************** */ diff --git a/src/uws/service/log/UWSLogType.java b/src/uws/service/log/UWSLogType.java index d9ccd413b9db9ac8a18ed78866fac937bea96da7..1aed19bd4c58e5a55f33989b2892db1a60f40d03 100644 --- a/src/uws/service/log/UWSLogType.java +++ b/src/uws/service/log/UWSLogType.java @@ -28,13 +28,8 @@ package uws.service.log; * @see UWSLog * @see DefaultUWSLog */ -public enum UWSLogType { - HTTP_ACTIVITY, - DEBUG, - INFO, - WARNING, - ERROR, - CUSTOM; +public enum UWSLogType{ + HTTP_ACTIVITY, DEBUG, INFO, WARNING, ERROR, CUSTOM; protected String customType = this.name(); diff --git a/test/adql/SearchIterator.java b/test/adql/SearchIterator.java index f22a14b1c29eba74cce1284af46cadc51eb32b04..c36588209dedb161c47d46a7e3deaefdb731798d 100644 --- a/test/adql/SearchIterator.java +++ b/test/adql/SearchIterator.java @@ -36,18 +36,17 @@ public class SearchIterator implements Iterator<SearchResult> { /** List of the next SearchResult objects which has at least one result (themselves or included SearchResult). */ protected Vector<SearchResult> toExplore; - public SearchIterator(SearchResult r){ toExplore = new Vector<SearchResult>(); if (r != null && r.hasResult()) toExplore.add(r); } - public boolean hasNext() { + public boolean hasNext(){ return !toExplore.isEmpty(); } - public SearchResult next() throws NoSuchElementException { + public SearchResult next() throws NoSuchElementException{ SearchResult next = null; while(next == null && !toExplore.isEmpty()){ @@ -70,7 +69,7 @@ public class SearchIterator implements Iterator<SearchResult> { return next; } - public void remove() throws UnsupportedOperationException { + public void remove() throws UnsupportedOperationException{ throw new UnsupportedOperationException("The REMOVE operation is not possible in a search result !"); } diff --git a/test/adql/SearchResult.java b/test/adql/SearchResult.java index 2da101490df98a2d7c3c1129369cf134dd7ab698..3a373d8868c40ee83ab0baa3f75e1f40da44f6a6 100644 --- a/test/adql/SearchResult.java +++ b/test/adql/SearchResult.java @@ -73,7 +73,6 @@ public final class SearchResult implements Iterable<SearchResult> { /** If it is impossible to replace an ADQL object by another one, a SearchResult must be created (with result = true) and this field must contain an error description. */ private String error = null; - /** * <p>Builds a SearchResult (node) with its value (node value).</p> * <p><i><u>Note:</u> By using this constructor the created SearchResult will not correspond to a matched ADQL object.</i></p> @@ -96,7 +95,8 @@ public final class SearchResult implements Iterable<SearchResult> { value = nodeValue; result = (nodeValue != null) && isResult; - if (result) nbResults = 1; + if (result) + nbResults = 1; } /** @@ -144,7 +144,7 @@ public final class SearchResult implements Iterable<SearchResult> { public final void setError(String msg){ if (msg != null){ msg = msg.trim(); - error = (msg.length()==0)?null:msg; + error = (msg.length() == 0) ? null : msg; }else error = null; } @@ -208,9 +208,9 @@ public final class SearchResult implements Iterable<SearchResult> { * Once the counting phase finished the direct parent node is notify that it must update its own number of results. */ private final void updateNbResults(){ - synchronized (this) { + synchronized(this){ // Count all results from this node: - nbResults = isResult()?1:0; + nbResults = isResult() ? 1 : 0; for(SearchResult r : children) nbResults += r.getNbResults(); } @@ -244,7 +244,7 @@ public final class SearchResult implements Iterable<SearchResult> { * @see java.lang.Iterable#iterator() * @see SearchIterator */ - public final Iterator<SearchResult> iterator() { + public final Iterator<SearchResult> iterator(){ return new SearchIterator(this); } diff --git a/test/adql/TestADQLQuery.java b/test/adql/TestADQLQuery.java index 9e957b0192d6327f80c21fe2f5acfcf700398750..7fac283d388e9b9db1e92921d3667455e912389a 100644 --- a/test/adql/TestADQLQuery.java +++ b/test/adql/TestADQLQuery.java @@ -28,7 +28,7 @@ import adql.search.ISearchHandler; import adql.search.SearchColumnHandler; public class TestADQLQuery { - public static final void main(String[] args) throws Exception { + public static final void main(String[] args) throws Exception{ ADQLQuery query = new ADQLQuery(); // SELECT: @@ -60,7 +60,7 @@ public class TestADQLQuery { ClauseADQL<ADQLOrder> orderBy = query.getOrderBy(); orderBy.add(new ADQLOrder(1, true)); - System.out.println("*** QUERY ***\n"+query.toADQL()); + System.out.println("*** QUERY ***\n" + query.toADQL()); ISearchHandler sHandler = new SearchColumnHandler(false); Iterator<ADQLObject> results = query.search(sHandler); @@ -82,8 +82,8 @@ public class TestADQLQuery { // Iterator<ADQLObject> results = sHandler.iterator(); System.out.println("\n*** SEARCH ALL COLUMNS ***"); while(results.hasNext()) - System.out.println("\t- "+results.next().toADQL()); + System.out.println("\t- " + results.next().toADQL()); - System.out.println("\n*** QUERY ***\n"+query.toADQL()); + System.out.println("\n*** QUERY ***\n" + query.toADQL()); } } diff --git a/test/adql/TestIN.java b/test/adql/TestIN.java index 789391a8ea95c514104f42c60467080c13023bf4..43ad6cac396f2260a8ff0af7e44803ce67aa2936 100644 --- a/test/adql/TestIN.java +++ b/test/adql/TestIN.java @@ -23,9 +23,9 @@ import adql.translator.PostgreSQLTranslator; public class TestIN { - public static void main(String[] args) throws Exception { - In myIn = new In(new ADQLColumn("typeObj"), new ADQLOperand[]{new StringConstant("galaxy"), new StringConstant("star"), new StringConstant("planet"), new StringConstant("nebula")}, true); - System.out.println(myIn.getName()+": "+myIn.toADQL()); + public static void main(String[] args) throws Exception{ + In myIn = new In(new ADQLColumn("typeObj"), new ADQLOperand[]{new StringConstant("galaxy"),new StringConstant("star"),new StringConstant("planet"),new StringConstant("nebula")}, true); + System.out.println(myIn.getName() + ": " + myIn.toADQL()); ADQLQuery subQuery = new ADQLQuery(); @@ -40,30 +40,30 @@ public class TestIN { orderBy.add(new ADQLOrder(1)); myIn.setSubQuery(subQuery); - System.out.println("\n*** "+myIn.getName().toUpperCase()+" ***\n"+myIn.toADQL()); + System.out.println("\n*** " + myIn.getName().toUpperCase() + " ***\n" + myIn.toADQL()); PostgreSQLTranslator translator = new PostgreSQLTranslator(); - System.out.println("\n*** SQL TRANSLATION ***\n"+translator.translate(myIn)); + System.out.println("\n*** SQL TRANSLATION ***\n" + translator.translate(myIn)); - IReplaceHandler sHandler = new SimpleReplaceHandler(true) { + IReplaceHandler sHandler = new SimpleReplaceHandler(true){ @Override - public boolean match(ADQLObject obj) { + public boolean match(ADQLObject obj){ return (obj instanceof ADQLColumn) && ((ADQLColumn)obj).getColumnName().equals("typeObj"); } @Override - public ADQLObject getReplacer(ADQLObject objToReplace) { + public ADQLObject getReplacer(ADQLObject objToReplace){ return new ADQLColumn("type"); } }; sHandler.searchAndReplace(myIn); - System.out.println("INFO: "+sHandler.getNbReplacement()+"/"+sHandler.getNbMatch()+" replaced objects !"); + System.out.println("INFO: " + sHandler.getNbReplacement() + "/" + sHandler.getNbMatch() + " replaced objects !"); Iterator<ADQLObject> results = sHandler.iterator(); System.out.println("\n*** SEARCH RESULTS ***"); while(results.hasNext()) - System.out.println("\t- "+results.next()); + System.out.println("\t- " + results.next()); - System.out.println("\n*** AFTER REPLACEMENT ***\n"+myIn.toADQL()); + System.out.println("\n*** AFTER REPLACEMENT ***\n" + myIn.toADQL()); } }