List of usage examples for java.util SortedSet add
boolean add(E e);
From source file:com.mirth.connect.connectors.jdbc.DatabaseConnectorServlet.java
@Override public SortedSet<Table> getTables(String channelId, String channelName, String driver, String url, String username, String password, Set<String> tableNamePatterns, String selectLimit, Set<String> resourceIds) { CustomDriver customDriver = null;/*from ww w. java 2 s . com*/ Connection connection = null; try { url = replacer.replaceValues(url, channelId, channelName); username = replacer.replaceValues(username, channelId, channelName); password = replacer.replaceValues(password, channelId, channelName); String schema = null; try { MirthContextFactory contextFactory = contextFactoryController.getContextFactory(resourceIds); try { ClassLoader isolatedClassLoader = contextFactory.getIsolatedClassLoader(); if (isolatedClassLoader != null) { customDriver = new CustomDriver(isolatedClassLoader, driver); logger.debug("Custom driver created: " + customDriver.toString() + ", Version " + customDriver.getMajorVersion() + "." + customDriver.getMinorVersion()); } else { logger.debug("Custom classloader is not being used, defaulting to DriverManager."); } } catch (Exception e) { logger.debug("Error creating custom driver, defaulting to DriverManager.", e); } } catch (Exception e) { logger.debug("Error retrieving context factory, defaulting to DriverManager.", e); } if (customDriver == null) { Class.forName(driver); } int oldLoginTimeout = DriverManager.getLoginTimeout(); DriverManager.setLoginTimeout(30); if (customDriver != null) { connection = customDriver.connect(url, username, password); } else { connection = DriverManager.getConnection(url, username, password); } DriverManager.setLoginTimeout(oldLoginTimeout); DatabaseMetaData dbMetaData = connection.getMetaData(); // the sorted set to hold the table information SortedSet<Table> tableInfoList = new TreeSet<Table>(); // Use a schema if the user name matches one of the schemas. // Fix for Oracle: MIRTH-1045 ResultSet schemasResult = null; try { schemasResult = dbMetaData.getSchemas(); while (schemasResult.next()) { String schemaResult = schemasResult.getString(1); if (username.equalsIgnoreCase(schemaResult)) { schema = schemaResult; } } } finally { if (schemasResult != null) { schemasResult.close(); } } // based on the table name pattern, attempt to retrieve the table information tableNamePatterns = translateTableNamePatterns(tableNamePatterns); List<String> tableNameList = new ArrayList<String>(); // go through each possible table name patterns and query for the tables for (String tableNamePattern : tableNamePatterns) { ResultSet rs = null; try { rs = dbMetaData.getTables(null, schema, tableNamePattern, TABLE_TYPES); // based on the result set, loop through to store the table name so it can be used to // retrieve the table's column information while (rs.next()) { tableNameList.add(rs.getString("TABLE_NAME")); } } finally { if (rs != null) { rs.close(); } } } // for each table, grab their column information for (String tableName : tableNameList) { ResultSet rs = null; ResultSet backupRs = null; boolean fallback = false; try { // apparently it's much more efficient to use ResultSetMetaData to retrieve // column information. So each driver is defined with their own unique SELECT // statement to query the table columns and use ResultSetMetaData to retrieve // the column information. If driver is not defined with the select statement // then we'll define to the generic method of getting column information, but // this could be extremely slow List<Column> columnList = new ArrayList<Column>(); if (StringUtils.isEmpty(selectLimit)) { logger.debug("No select limit is defined, using generic method"); rs = dbMetaData.getColumns(null, null, tableName, null); // retrieve all relevant column information for (int i = 0; rs.next(); i++) { Column column = new Column(rs.getString("COLUMN_NAME"), rs.getString("TYPE_NAME"), rs.getInt("COLUMN_SIZE")); columnList.add(column); } } else { logger.debug( "Select limit is defined, using specific select query : '" + selectLimit + "'"); // replace the '?' with the appropriate schema.table name, and use ResultSetMetaData to // retrieve column information final String schemaTableName = StringUtils.isNotEmpty(schema) ? "\"" + schema + "\".\"" + tableName + "\"" : "\"" + tableName + "\""; final String queryString = selectLimit.trim().replaceAll("\\?", Matcher.quoteReplacement(schemaTableName)); Statement statement = connection.createStatement(); try { rs = statement.executeQuery(queryString); ResultSetMetaData rsmd = rs.getMetaData(); // retrieve all relevant column information for (int i = 1; i < rsmd.getColumnCount() + 1; i++) { Column column = new Column(rsmd.getColumnName(i), rsmd.getColumnTypeName(i), rsmd.getPrecision(i)); columnList.add(column); } } catch (SQLException sqle) { logger.info("Failed to execute '" + queryString + "', fall back to generic approach to retrieve column information"); fallback = true; } finally { if (statement != null) { statement.close(); } } // failed to use selectLimit method, so we need to fall back to generic // if this generic approach fails, then there's nothing we can do if (fallback) { // Re-initialize in case some columns were added before failing columnList = new ArrayList<Column>(); logger.debug("Using fallback method for retrieving columns"); backupRs = dbMetaData.getColumns(null, null, tableName.replace("/", "//"), null); // retrieve all relevant column information while (backupRs.next()) { Column column = new Column(backupRs.getString("COLUMN_NAME"), backupRs.getString("TYPE_NAME"), backupRs.getInt("COLUMN_SIZE")); columnList.add(column); } } } // create table object and add to the list of table definitions Table table = new Table(tableName, columnList); tableInfoList.add(table); } finally { if (rs != null) { rs.close(); } if (backupRs != null) { backupRs.close(); } } } return tableInfoList; } catch (Exception e) { throw new MirthApiException(new Exception("Could not retrieve database tables and columns.", e)); } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { } } } }
From source file:com.mirth.connect.connectors.jdbc.JdbcConnectorService.java
public Object invoke(String method, Object object, String sessionsId) throws Exception { if (method.equals("getInformationSchema")) { // method 'getInformationSchema' will return Set<Table> Connection connection = null; try {/* ww w .j a v a 2 s .co m*/ Properties properties = (Properties) object; String driver = properties.getProperty(DatabaseReaderProperties.DATABASE_DRIVER); String address = properties.getProperty(DatabaseReaderProperties.DATABASE_URL); String user = properties.getProperty(DatabaseReaderProperties.DATABASE_USERNAME); String password = properties.getProperty(DatabaseReaderProperties.DATABASE_PASSWORD); // Although these properties are not persisted, they used by the JdbcConnectorService String tableNamePatternExp = properties .getProperty(DatabaseReaderProperties.DATABASE_TABLE_NAME_PATTERN_EXPRESSION); String selectLimit = properties.getProperty(DatabaseReaderProperties.DATABASE_SELECT_LIMIT); String schema = null; Class.forName(driver); int oldLoginTimeout = DriverManager.getLoginTimeout(); DriverManager.setLoginTimeout(30); connection = DriverManager.getConnection(address, user, password); DriverManager.setLoginTimeout(oldLoginTimeout); DatabaseMetaData dbMetaData = connection.getMetaData(); // the sorted set to hold the table information SortedSet<Table> tableInfoList = new TreeSet<Table>(); // Use a schema if the user name matches one of the schemas. // Fix for Oracle: MIRTH-1045 ResultSet schemasResult = null; try { schemasResult = dbMetaData.getSchemas(); while (schemasResult.next()) { String schemaResult = schemasResult.getString(1); if (user.equalsIgnoreCase(schemaResult)) { schema = schemaResult; } } } finally { if (schemasResult != null) { schemasResult.close(); } } // based on the table name pattern, attempt to retrieve the table information List<String> tablePatternList = translateTableNamePatternExpression(tableNamePatternExp); List<String> tableNameList = new ArrayList<String>(); // go through each possible table name patterns and query for the tables for (String tableNamePattern : tablePatternList) { ResultSet rs = null; try { rs = dbMetaData.getTables(null, schema, tableNamePattern, TABLE_TYPES); // based on the result set, loop through to store the table name so it can be used to // retrieve the table's column information while (rs.next()) { tableNameList.add(rs.getString("TABLE_NAME")); } } finally { if (rs != null) { rs.close(); } } } // for each table, grab their column information for (String tableName : tableNameList) { ResultSet rs = null; ResultSet backupRs = null; boolean fallback = false; try { // apparently it's much more efficient to use ResultSetMetaData to retrieve // column information. So each driver is defined with their own unique SELECT // statement to query the table columns and use ResultSetMetaData to retrieve // the column information. If driver is not defined with the select statement // then we'll define to the generic method of getting column information, but // this could be extremely slow List<Column> columnList = new ArrayList<Column>(); if (StringUtils.isEmpty(selectLimit)) { logger.debug("No select limit is defined, using generic method"); rs = dbMetaData.getColumns(null, null, tableName, null); // retrieve all relevant column information for (int i = 0; rs.next(); i++) { Column column = new Column(rs.getString("COLUMN_NAME"), rs.getString("TYPE_NAME"), rs.getInt("COLUMN_SIZE")); columnList.add(column); } } else { logger.debug( "Select limit is defined, using specific select query : '" + selectLimit + "'"); // replace the '?' with the appropriate schema.table name, and use ResultSetMetaData to // retrieve column information final String schemaTableName = StringUtils.isNotEmpty(schema) ? schema + "." + tableName : tableName; final String queryString = selectLimit.trim().replaceAll("\\?", schemaTableName); Statement statement = connection.createStatement(); try { rs = statement.executeQuery(queryString); ResultSetMetaData rsmd = rs.getMetaData(); // retrieve all relevant column information for (int i = 1; i < rsmd.getColumnCount() + 1; i++) { Column column = new Column(rsmd.getColumnName(i), rsmd.getColumnTypeName(i), rsmd.getPrecision(i)); columnList.add(column); } } catch (SQLException sqle) { logger.info("Failed to execute '" + queryString + "', fall back to generic approach to retrieve column information"); fallback = true; } finally { if (statement != null) { statement.close(); } } // failed to use selectLimit method, so we need to fall back to generic // if this generic approach fails, then there's nothing we can do if (fallback) { // Re-initialize in case some columns were added before failing columnList = new ArrayList<Column>(); logger.debug("Using fallback method for retrieving columns"); backupRs = dbMetaData.getColumns(null, null, tableName, null); // retrieve all relevant column information for (int i = 0; backupRs.next(); i++) { Column column = new Column(backupRs.getString("COLUMN_NAME"), backupRs.getString("TYPE_NAME"), backupRs.getInt("COLUMN_SIZE")); columnList.add(column); } } } // create table object and add to the list of table definitions Table table = new Table(tableName, columnList); tableInfoList.add(table); } finally { if (rs != null) { rs.close(); } if (backupRs != null) { backupRs.close(); } } } return tableInfoList; } catch (Exception e) { throw new Exception("Could not retrieve database tables and columns.", e); } finally { if (connection != null) { connection.close(); } } } return null; }
From source file:com.mirth.connect.connectors.jdbc.DatabaseConnectorService.java
public Object invoke(String channelId, String method, Object object, String sessionsId) throws Exception { if (method.equals("getInformationSchema")) { // method 'getInformationSchema' will return Set<Table> Connection connection = null; try {/*from w w w.j a va 2 s . c o m*/ DatabaseConnectionInfo databaseConnectionInfo = (DatabaseConnectionInfo) object; String driver = databaseConnectionInfo.getDriver(); String address = replacer.replaceValues(databaseConnectionInfo.getUrl(), channelId); String user = replacer.replaceValues(databaseConnectionInfo.getUsername(), channelId); String password = replacer.replaceValues(databaseConnectionInfo.getPassword(), channelId); // Although these properties are not persisted, they used by the JdbcConnectorService String tableNamePatternExp = databaseConnectionInfo.getTableNamePatternExpression(); String selectLimit = databaseConnectionInfo.getSelectLimit(); String schema = null; Class.forName(driver); int oldLoginTimeout = DriverManager.getLoginTimeout(); DriverManager.setLoginTimeout(30); connection = DriverManager.getConnection(address, user, password); DriverManager.setLoginTimeout(oldLoginTimeout); DatabaseMetaData dbMetaData = connection.getMetaData(); // the sorted set to hold the table information SortedSet<Table> tableInfoList = new TreeSet<Table>(); // Use a schema if the user name matches one of the schemas. // Fix for Oracle: MIRTH-1045 ResultSet schemasResult = null; try { schemasResult = dbMetaData.getSchemas(); while (schemasResult.next()) { String schemaResult = schemasResult.getString(1); if (user.equalsIgnoreCase(schemaResult)) { schema = schemaResult; } } } finally { if (schemasResult != null) { schemasResult.close(); } } // based on the table name pattern, attempt to retrieve the table information List<String> tablePatternList = translateTableNamePatternExpression(tableNamePatternExp); List<String> tableNameList = new ArrayList<String>(); // go through each possible table name patterns and query for the tables for (String tableNamePattern : tablePatternList) { ResultSet rs = null; try { rs = dbMetaData.getTables(null, schema, tableNamePattern, TABLE_TYPES); // based on the result set, loop through to store the table name so it can be used to // retrieve the table's column information while (rs.next()) { tableNameList.add(rs.getString("TABLE_NAME")); } } finally { if (rs != null) { rs.close(); } } } // for each table, grab their column information for (String tableName : tableNameList) { ResultSet rs = null; ResultSet backupRs = null; boolean fallback = false; try { // apparently it's much more efficient to use ResultSetMetaData to retrieve // column information. So each driver is defined with their own unique SELECT // statement to query the table columns and use ResultSetMetaData to retrieve // the column information. If driver is not defined with the select statement // then we'll define to the generic method of getting column information, but // this could be extremely slow List<Column> columnList = new ArrayList<Column>(); if (StringUtils.isEmpty(selectLimit)) { logger.debug("No select limit is defined, using generic method"); rs = dbMetaData.getColumns(null, null, tableName, null); // retrieve all relevant column information for (int i = 0; rs.next(); i++) { Column column = new Column(rs.getString("COLUMN_NAME"), rs.getString("TYPE_NAME"), rs.getInt("COLUMN_SIZE")); columnList.add(column); } } else { logger.debug( "Select limit is defined, using specific select query : '" + selectLimit + "'"); // replace the '?' with the appropriate schema.table name, and use ResultSetMetaData to // retrieve column information final String schemaTableName = StringUtils.isNotEmpty(schema) ? schema + "." + tableName : tableName; final String queryString = selectLimit.trim().replaceAll("\\?", schemaTableName); Statement statement = connection.createStatement(); try { rs = statement.executeQuery(queryString); ResultSetMetaData rsmd = rs.getMetaData(); // retrieve all relevant column information for (int i = 1; i < rsmd.getColumnCount() + 1; i++) { Column column = new Column(rsmd.getColumnName(i), rsmd.getColumnTypeName(i), rsmd.getPrecision(i)); columnList.add(column); } } catch (SQLException sqle) { logger.info("Failed to execute '" + queryString + "', fall back to generic approach to retrieve column information"); fallback = true; } finally { if (statement != null) { statement.close(); } } // failed to use selectLimit method, so we need to fall back to generic // if this generic approach fails, then there's nothing we can do if (fallback) { // Re-initialize in case some columns were added before failing columnList = new ArrayList<Column>(); logger.debug("Using fallback method for retrieving columns"); backupRs = dbMetaData.getColumns(null, null, tableName, null); // retrieve all relevant column information for (int i = 0; backupRs.next(); i++) { Column column = new Column(backupRs.getString("COLUMN_NAME"), backupRs.getString("TYPE_NAME"), backupRs.getInt("COLUMN_SIZE")); columnList.add(column); } } } // create table object and add to the list of table definitions Table table = new Table(tableName, columnList); tableInfoList.add(table); } finally { if (rs != null) { rs.close(); } if (backupRs != null) { backupRs.close(); } } } return tableInfoList; } catch (Exception e) { throw new Exception("Could not retrieve database tables and columns.", e); } finally { if (connection != null) { connection.close(); } } } return null; }
From source file:br.gov.jfrj.siga.ex.bl.ExBL.java
/** * Obtem a lista de formas de documentos a partir dos modelos selecionados e * das restries de tipo (interno, externo) e de tipo da forma (expediente, * processo)/*from ww w .j av a2s. c o m*/ * * @param modelos * @param tipoDoc * @param tipoForma * @return * @throws Exception */ public SortedSet<ExFormaDocumento> obterFormasDocumento(List<ExModelo> modelos, ExTipoDocumento tipoDoc, ExTipoFormaDoc tipoForma) { SortedSet<ExFormaDocumento> formasSet = new TreeSet<ExFormaDocumento>(); SortedSet<ExFormaDocumento> formasFinal = new TreeSet<ExFormaDocumento>(); // Por enquanto, os parmetros tipoForma e tipoDoc no podem ser // preenchidos simultaneamente. Melhorar isso. if (tipoDoc != null && tipoForma != null) { formasSet.addAll(SetUtils.intersection(tipoDoc.getExFormaDocumentoSet(), tipoForma.getExFormaDocSet())); } else if (tipoDoc != null) formasSet.addAll(tipoDoc.getExFormaDocumentoSet()); else if (tipoForma != null) formasSet.addAll(tipoForma.getExFormaDocSet()); else formasSet = null; for (ExModelo mod : modelos) { if (mod.getExFormaDocumento() == null) continue; if (formasSet == null || formasSet.contains(mod.getExFormaDocumento())) formasFinal.add(mod.getExFormaDocumento()); } return formasFinal; }
From source file:br.gov.jfrj.siga.ex.bl.ExBL.java
public void cancelarMovimentacao(final DpPessoa cadastrante, final DpLotacao lotaCadastrante, final ExMobil mob) { try {//from ww w . j a va 2s .co m boolean indexar = false; SortedSet<ExMobil> set = null; ExMovimentacao movACancelar = mob.getUltimaMovimentacaoNaoCancelada(); switch ((int) (long) movACancelar.getExTipoMovimentacao().getIdTpMov()) { case (int) ExTipoMovimentacao.TIPO_MOVIMENTACAO_SOBRESTAR: case (int) ExTipoMovimentacao.TIPO_MOVIMENTACAO_DESOBRESTAR: set = mob.getMobilETodosOsApensos(); break; case (int) ExTipoMovimentacao.TIPO_MOVIMENTACAO_TRANSFERENCIA: case (int) ExTipoMovimentacao.TIPO_MOVIMENTACAO_TRANSFERENCIA_EXTERNA: case (int) ExTipoMovimentacao.TIPO_MOVIMENTACAO_RECEBIMENTO: set = mob.getMobilETodosOsApensos(); break; case (int) ExTipoMovimentacao.TIPO_MOVIMENTACAO_DESPACHO: case (int) ExTipoMovimentacao.TIPO_MOVIMENTACAO_DESPACHO_TRANSFERENCIA: case (int) ExTipoMovimentacao.TIPO_MOVIMENTACAO_DESPACHO_TRANSFERENCIA_EXTERNA: indexar = true; set = new TreeSet<ExMobil>(); set.add(mob); break; case (int) ExTipoMovimentacao.TIPO_MOVIMENTACAO_REDEFINICAO_NIVEL_ACESSO: indexar = true; set = mob.getMobilETodosOsApensos(); break; default: set = new TreeSet<ExMobil>(); set.add(mob); } iniciarAlteracao(); for (ExMobil m : set) { if (m.getUltimaMovimentacao().getExTipoMovimentacao() .getIdTpMov() == ExTipoMovimentacao.TIPO_MOVIMENTACAO_AGENDAMENTO_DE_PUBLICACAO_BOLETIM) { cancelarPedidoBI(m.doc()); } final ExMovimentacao ultMov = m.getUltimaMovimentacao(); final ExMovimentacao ultMovNaoCancelada = m.getUltimaMovimentacaoNaoCancelada(movACancelar); /* * O correto seria a varivel abaixo guardar a movimentao * anterior movimentao acima. No necessariamente ser a * penltima. */ final ExMovimentacao penultMovNaoCancelada = m.getPenultimaMovimentacaoNaoCancelada(); final ExMovimentacao mov = criarNovaMovimentacao( ExTipoMovimentacao.TIPO_MOVIMENTACAO_CANCELAMENTO_DE_MOVIMENTACAO, cadastrante, lotaCadastrante, m, null, null, null, null, null, null); gravarMovimentacao(mov); mov.setExMovimentacaoRef(ultMovNaoCancelada); mov.setExNivelAcesso(ultMovNaoCancelada.getExNivelAcesso()); if (ultMovNaoCancelada.getExTipoMovimentacao() .getIdTpMov() == ExTipoMovimentacao.TIPO_MOVIMENTACAO_AGENDAMENTO_DE_PUBLICACAO) PublicacaoDJEBL.cancelarRemessaPublicacao(mov); if (ultMovNaoCancelada.getExTipoMovimentacao() .getIdTpMov() == ExTipoMovimentacao.TIPO_MOVIMENTACAO_CANCELAMENTO_JUNTADA && ultMovNaoCancelada.getExMovimentacaoRef() != null) { mov.setExMobilRef(ultMovNaoCancelada.getExMovimentacaoRef().getExMobilRef()); } if (penultMovNaoCancelada != null) { // if (mov.getLotaResp() == null) mov.setLotaResp(penultMovNaoCancelada.getLotaResp()); // if (mov.getResp() == null) mov.setResp(penultMovNaoCancelada.getResp()); // if (mov.getLotaDestinoFinal() == null) mov.setLotaDestinoFinal(penultMovNaoCancelada.getLotaDestinoFinal()); // if (mov.getDestinoFinal() == null) mov.setDestinoFinal(penultMovNaoCancelada.getDestinoFinal()); mov.setExClassificacao(penultMovNaoCancelada.getExClassificacao()); } else { mov.setExClassificacao(null); if (ultMovNaoCancelada != null) { // if (mov.getLotaResp() == null) mov.setLotaResp(ultMovNaoCancelada.getLotaResp()); // if (mov.getResp() == null) mov.setResp(ultMovNaoCancelada.getResp()); // if (mov.getLotaDestinoFinal() == null) mov.setLotaDestinoFinal(ultMovNaoCancelada.getLotaDestinoFinal()); // if (mov.getDestinoFinal() == null) mov.setDestinoFinal(ultMovNaoCancelada.getDestinoFinal()); } else { // if (mov.getLotaResp() == null) mov.setLotaResp(ultMov.getLotaResp()); // if (mov.getResp() == null) mov.setResp(ultMov.getResp()); // if (mov.getLotaDestinoFinal() == null) mov.setLotaDestinoFinal(ultMov.getLotaDestinoFinal()); // if (mov.getDestinoFinal() == null) mov.setDestinoFinal(ultMov.getDestinoFinal()); } } gravarMovimentacaoCancelamento(mov, ultMovNaoCancelada); if (ultMovNaoCancelada.getExTipoMovimentacao() .getIdTpMov() == ExTipoMovimentacao.TIPO_MOVIMENTACAO_ANOTACAO) { atualizarDnmAnotacao(m); } if (ultMovNaoCancelada.getExTipoMovimentacao() .getIdTpMov() == ExTipoMovimentacao.TIPO_MOVIMENTACAO_RECLASSIFICACAO || ultMovNaoCancelada.getExTipoMovimentacao() .getIdTpMov() == ExTipoMovimentacao.TIPO_MOVIMENTACAO_AVALIACAO_COM_RECLASSIFICACAO) for (ExMobil mobRemarcar : mob.doc().getExMobilSet()) { ExDocumento docPai = mobRemarcar.getMobilPrincipal().getExDocumento(); if (!docPai.equals(mob.doc())) atualizarMarcas(docPai); } concluirAlteracaoParcial(m); } concluirAlteracao(null); if (indexar) alimentaFilaIndexacao(mob.getExDocumento(), true); } catch (final Exception e) { cancelarAlteracao(); throw new AplicacaoException("Erro ao cancelar movimentao.", 0, e); // throw e; } }
From source file:org.wrml.runtime.schema.generator.SchemaGenerator.java
/** * Generate a {@link JavaBytecodeClass} from the specified {@link Schema}. * <p/>/* w w w.j a va2 s . c o m*/ * Like a *big* regex (regular expression), we can compile all of the * WRML schema metadata (as if it is a single *big* String input) into a * loaded Java class so that the rest of the WRML *runtime* can use * (Prototype-optimized) reflection to access WRML's type system. * * @param schema The Schema to represent as a Java class. * @return The Java class representation of the specified schema. */ public JavaBytecodeClass generateSchemaInterface(final Schema schema) { /* * Create the simple POJO that will return the transformation * information. By the end of this method, this will be full of Java * bytecode-oriented information gleaned from this method's schema * parameter. */ final JavaBytecodeClass javaBytecodeClass = new JavaBytecodeClass(); final JavaBytecodeAnnotation wrmlAnnotation = new JavaBytecodeAnnotation( SchemaGenerator.ANNOTATION_INTERNAL_NAME_WRML); wrmlAnnotation.setAttributeValue(AnnotationParameterName.uniqueName.name(), schema.getUniqueName().getFullName()); javaBytecodeClass.getAnnotations().add(wrmlAnnotation); final SortedSet<String> keySlotNameSet = new TreeSet<>(); /* * If the schema declares any key slots, note them with a * class-level annotation. */ final List<String> keySlotNames = schema.getKeySlotNames(); if (keySlotNames != null && keySlotNames.size() > 0) { keySlotNameSet.addAll(keySlotNames); } if (!keySlotNameSet.isEmpty()) { final String[] keySlotNamesArray = new String[keySlotNameSet.size()]; wrmlAnnotation.setAttributeValue(AnnotationParameterName.keySlotNames.name(), keySlotNameSet.toArray(keySlotNamesArray)); } /* * If the schema declares any comparable slots, note them with a * class-level annotation. */ final List<String> comparableSlotNames = schema.getComparableSlotNames(); if (comparableSlotNames != null && comparableSlotNames.size() > 0) { final String[] comparableSlotNamesArray = new String[comparableSlotNames.size()]; wrmlAnnotation.setAttributeValue(AnnotationParameterName.comparableSlotNames.name(), comparableSlotNames.toArray(comparableSlotNamesArray)); } wrmlAnnotation.setAttributeValue(AnnotationParameterName.titleSlotName.name(), schema.getTitleSlotName()); /* * In Java, all interfaces extend java.lang.Object, so this can * remain constant for Schema too. */ javaBytecodeClass.setSuperName(SchemaGenerator.OBJECT_INTERNAL_NAME); /* * Go from schema id (URI) to internal Java class name. This is a * simple matter of stripping the leading forward slash from the * URI's path. Internally (in the bytecode), Java's class names use * forward slash (/) instead of full stop dots (.). */ final URI schemaUri = schema.getUri(); final String interfaceInternalName = uriToInternalTypeName(schemaUri); // if (schema.getUniqueName() == null) // { // schema.setUniqueName(new UniqueName(schemaUri.getPath())); // } javaBytecodeClass.setInternalName(interfaceInternalName); /* * Add the class-level Description annotation to capture the * schema's description. */ final String schemaDescription = schema.getDescription(); if (schemaDescription != null && !schemaDescription.trim().isEmpty()) { final JavaBytecodeAnnotation schemaDescriptionAnnotation = new JavaBytecodeAnnotation( SchemaGenerator.ANNOTATION_INTERNAL_NAME_DESCRIPTION); schemaDescriptionAnnotation.setAttributeValue(AnnotationParameterName.value.name(), schemaDescription); javaBytecodeClass.getAnnotations().add(schemaDescriptionAnnotation); } String schemaTitle = schema.getTitle(); if (schemaTitle == null || schemaTitle.trim().isEmpty()) { schemaTitle = schema.getUniqueName().getLocalName(); } final JavaBytecodeAnnotation schemaTitleAnnotation = new JavaBytecodeAnnotation( SchemaGenerator.ANNOTATION_INTERNAL_NAME_TITLE); schemaTitleAnnotation.setAttributeValue(AnnotationParameterName.value.name(), schemaTitle); javaBytecodeClass.getAnnotations().add(schemaTitleAnnotation); final URI schemaThumbnailImageLocation = schema.getThumbnailLocation(); if (schemaThumbnailImageLocation != null) { final JavaBytecodeAnnotation schemaThumbnailImageAnnotation = new JavaBytecodeAnnotation( SchemaGenerator.ANNOTATION_INTERNAL_NAME_THUMBNAIL_IMAGE); schemaThumbnailImageAnnotation.setAttributeValue(AnnotationParameterName.value.name(), schemaThumbnailImageLocation.toString()); javaBytecodeClass.getAnnotations().add(schemaThumbnailImageAnnotation); } boolean isAggregate = false; /* * Turn the schema's base schema list into our Java class's base * (aka extended) interfaces. */ final List<URI> baseSchemaUris = schema.getBaseSchemaUris(); for (final URI baseSchemaUri : baseSchemaUris) { final String baseSchemaInternalName = uriToInternalTypeName(baseSchemaUri); javaBytecodeClass.getInterfaces().add(baseSchemaInternalName); if (!isAggregate && getSchemaLoader().getAggregateDocumentSchemaUri().equals(baseSchemaUri)) { isAggregate = true; final List<Slot> slots = schema.getSlots(); for (final Slot slot : slots) { final Value value = slot.getValue(); if (!(value instanceof LinkValue || value instanceof ModelValue || value instanceof MultiSelectValue)) { keySlotNameSet.add(slot.getName()); } } } } // Add the Model base interface javaBytecodeClass.getInterfaces().add(SchemaGenerator.MODEL_INTERFACE_INTERNAL_NAME); /* * Add the class-level Tags annotation to capture the schema's tags. */ final List<String> schemaTags = schema.getTags(); if (schemaTags != null && schemaTags.size() > 0) { final JavaBytecodeAnnotation tagsAnnotation = new JavaBytecodeAnnotation( SchemaGenerator.ANNOTATION_INTERNAL_NAME_TAGS); final String[] tagsArray = new String[schemaTags.size()]; tagsAnnotation.setAttributeValue(AnnotationParameterName.value.name(), schemaTags.toArray(tagsArray)); javaBytecodeClass.getAnnotations().add(tagsAnnotation); } final Long schemaVersion = schema.getVersion(); if (schemaVersion != null) { final JavaBytecodeAnnotation versionAnnotation = new JavaBytecodeAnnotation( SchemaGenerator.ANNOTATION_INTERNAL_NAME_VERSION); versionAnnotation.setAttributeValue(AnnotationParameterName.value.name(), schemaVersion); javaBytecodeClass.getAnnotations().add(versionAnnotation); } final Boolean maybeReadOnly = schema.isReadOnly(); if (maybeReadOnly != null && maybeReadOnly) { final JavaBytecodeAnnotation readOnlyAnnotation = new JavaBytecodeAnnotation( SchemaGenerator.ANNOTATION_INTERNAL_NAME_READ_ONLY); javaBytecodeClass.getAnnotations().add(readOnlyAnnotation); } /* * Generate the interface method signatures. */ generateSchemaInterfaceMethods(schema, javaBytecodeClass, isAggregate); // TODO: "Open slots" with signatures. Track the open slots via // the JavaBytecode types. // // TODO: The signature will need to be changed for generics: // Example: // // Java: public interface Test<T extends List<?>> extends List<T> // Class File: public abstract interface org.wrml.schema.Test // extends java.util.List // Signature: // <T::Ljava/util/List<*>;>Ljava/lang/Object;Ljava/util/List<TT;>; // javaBytecodeClass.setSignature(null); generateSchemaInterfaceBytecode(javaBytecodeClass); return javaBytecodeClass; }
From source file:edu.ku.brc.specify.tasks.subpane.wb.wbuploader.Uploader.java
/** * Imposes additional ordering constraints created by the matchChildren property of UploadTable. * I.e. if A precedes B and B is in C.matchChildren, then A must precede C. *//*w w w. j a v a 2 s .c o m*/ protected void reOrderUploadTables() throws UploaderException { SortedSet<Pair<UploadTable, UploadTable>> moves = new TreeSet<Pair<UploadTable, UploadTable>>( new Comparator<Pair<UploadTable, UploadTable>>() { private boolean isAncestorOf(UploadTable t1, UploadTable t2) { logDebug("isAncestorOf(" + t1 + ", " + t2 + ")"); if (t1.equals(t2)) { return true; } for (Vector<ParentTableEntry> ptes : t2.getParentTables()) { for (ParentTableEntry pte : ptes) { if (isAncestorOf(t1, pte.getImportTable())) { return true; } } } return false; } public int compare(Pair<UploadTable, UploadTable> p1, Pair<UploadTable, UploadTable> p2) { if (p1.getFirst() == p2.getFirst() && p1.getSecond() == p2.getSecond()) { return 0; } if (isAncestorOf(p1.getSecond(), p2.getSecond())) { return -1; } if (isAncestorOf(p2.getSecond(), p1.getSecond())) { return 1; } return 0; } }); if (debugging) { logDebug("reOrderUploadTables(): initial order:"); for (UploadTable ut : uploadTables) { logDebug(" " + ut.getTable().getName()); } } for (UploadTable ut : uploadTables) { logDebug("Table: " + ut.getTable().getName()); for (UploadTable mc : ut.getSpecialChildren()) { if (ut.needToMatchChild(mc.getTblClass())) { logDebug(" Child: " + mc.getTable().getName()); for (ParentTableEntry pte : mc.getAncestors()) { if (uploadTables.indexOf(ut) < uploadTables.indexOf(pte.getImportTable())) { logDebug("reordering: " + pte.getImportTable().getTable().getName() + " must precede " + ut.getTable().getName()); moves.add(new Pair<UploadTable, UploadTable>(ut, pte.getImportTable())); } } } } } for (Pair<UploadTable, UploadTable> move : moves) { int fromIdx = uploadTables.indexOf(move.getSecond()); int toIdx = uploadTables.indexOf(move.getFirst()); this.logDebug("reording: " + move.getSecond().getTable().getName() + "(" + fromIdx + ") -> " + move.getFirst().getTable().getName() + "(" + toIdx + ")"); if (toIdx > fromIdx) { log.error("Can't meet ordering constraints: " + move.getSecond().getTable().getName() + "," + move.getFirst().getTable().getName()); throw new UploaderException("The Dataset is not uploadable.", UploaderException.ABORT_IMPORT); } uploadTables.remove(fromIdx); uploadTables.insertElementAt(move.getSecond(), toIdx); } }
From source file:org.wso2.carbon.apimgt.impl.utils.APIUtil.java
public static Map<String, Object> searchAPIsByURLPattern(Registry registry, String searchTerm, int start, int end) throws APIManagementException { SortedSet<API> apiSet = new TreeSet<API>(new APINameComparator()); List<API> apiList = new ArrayList<API>(); final String searchValue = searchTerm.trim(); Map<String, Object> result = new HashMap<String, Object>(); int totalLength = 0; String criteria;//from w w w .j a va2 s.c o m Map<String, List<String>> listMap = new HashMap<String, List<String>>(); GenericArtifact[] genericArtifacts = new GenericArtifact[0]; GenericArtifactManager artifactManager = null; try { artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY); PaginationContext.init(0, 10000, "ASC", APIConstants.API_OVERVIEW_NAME, Integer.MAX_VALUE); if (artifactManager != null) { for (int i = 0; i < 20; i++) { //This need to fix in future.We don't have a way to get max value of // "url_template" entry stores in registry,unless we search in each API criteria = APIConstants.API_URI_PATTERN + i; listMap.put(criteria, new ArrayList<String>() { { add(searchValue); } }); genericArtifacts = (GenericArtifact[]) ArrayUtils.addAll(genericArtifacts, artifactManager.findGenericArtifacts(listMap)); } if (genericArtifacts == null || genericArtifacts.length == 0) { result.put("apis", apiSet); result.put("length", 0); return result; } totalLength = genericArtifacts.length; StringBuilder apiNames = new StringBuilder(); for (GenericArtifact artifact : genericArtifacts) { if (apiNames.indexOf(artifact.getAttribute(APIConstants.API_OVERVIEW_NAME)) < 0) { String status = artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS); if (isAllowDisplayAPIsWithMultipleStatus()) { if (APIConstants.PUBLISHED.equals(status) || APIConstants.DEPRECATED.equals(status)) { API api = APIUtil.getAPI(artifact, registry); if (api != null) { apiList.add(api); apiNames.append(api.getId().getApiName()); } } } else { if (APIConstants.PUBLISHED.equals(status)) { API api = APIUtil.getAPI(artifact, registry); if (api != null) { apiList.add(api); apiNames.append(api.getId().getApiName()); } } } } totalLength = apiList.size(); } if (totalLength <= ((start + end) - 1)) { end = totalLength; } for (int i = start; i < end; i++) { apiSet.add(apiList.get(i)); } } } catch (APIManagementException e) { handleException("Failed to search APIs with input url-pattern", e); } catch (GovernanceException e) { handleException("Failed to search APIs with input url-pattern", e); } result.put("apis", apiSet); result.put("length", totalLength); return result; }
From source file:org.sakaiproject.tool.messageforums.DiscussionForumTool.java
/** * @return List of DiscussionForumBean/*from w w w . jav a 2 s . co m*/ */ public List getForums() { LOG.debug("getForums()"); if (forums != null && forums.size() > 0) { return forums; } forums = new ArrayList<DiscussionForumBean>(); int unreadMessagesCount = 0; userId = getUserId(); boolean hasOverridingPermissions = false; if (SecurityService.isSuperUser() || isInstructor()) { hasOverridingPermissions = true; } // MSGCNTR-661 - the template settings are no longer affecting the // availability, so we need this to always be true boolean isAreaAvailable = true; if (isAreaAvailable) { // query the database for all of the forums that are associated with the current site List<DiscussionForum> tempForums = forumManager.getForumsForMainPage(); if (tempForums == null || tempForums.size() < 1) { if (SecurityService.isSuperUser() && ServerConfigurationService.getBoolean("forums.setDefault.forum", true)) { //initialize area: forumManager.getDiscussionForumArea(); //try again: tempForums = forumManager.getForumsForMainPage(); if (tempForums == null || tempForums.size() < 1) { return null; } } else { return null; } } // establish some values that we will check multiple times to shave a few processing cycles boolean readFullDescription = "true" .equalsIgnoreCase(ServerConfigurationService.getString("mc.defaultLongDescription")); // run through the topics once to get their parent forums, create the decorated topics that will be used later, and // possibly set the message count SortedSet<DiscussionForum> tempSortedForums = new TreeSet<DiscussionForum>( new ForumBySortIndexAscAndCreatedDateDesc()); Map<Long, DiscussionTopicBean> topicBeans = new HashMap<Long, DiscussionTopicBean>(); Set<Long> topicIdsForCounts = new HashSet<Long>(); for (DiscussionForum forum : tempForums) { if ((!forum.getDraft() && forum.getAvailability()) || hasOverridingPermissions) { // this is the start of the big forum if tempSortedForums.add(forum); for (Iterator itor = forum.getTopicsSet().iterator(); itor.hasNext();) { DiscussionTopic currTopic = (DiscussionTopic) itor.next(); if ((currTopic.getDraft().equals(Boolean.FALSE) && currTopic.getAvailability()) || hasOverridingPermissions) { // this is the start of the big topic if DiscussionTopicBean decoTopic = new DiscussionTopicBean(currTopic, (DiscussionForum) currTopic.getOpenForum(), uiPermissionsManager, forumManager); if (readFullDescription) decoTopic.setReadFullDesciption(true); // set the message count for moderated topics, otherwise it will be set later if (uiPermissionsManager.isRead(decoTopic.getTopic(), (DiscussionForum) currTopic.getOpenForum(), userId)) { if (currTopic.getModerated() && !uiPermissionsManager.isModeratePostings(currTopic, (DiscussionForum) currTopic.getOpenForum())) { decoTopic.setTotalNoMessages( forumManager.getTotalViewableMessagesWhenMod(currTopic)); decoTopic.setUnreadNoMessages( forumManager.getNumUnreadViewableMessagesWhenMod(currTopic)); } else { topicIdsForCounts.add(currTopic.getId()); } } else { decoTopic.setTotalNoMessages(0); decoTopic.setUnreadNoMessages(0); } topicBeans.put(currTopic.getId(), decoTopic); } // end the big topic if } } // end the big forum if } // get the total message count of non-moderated topics and add them to the discussion topic bean and // initialize the unread number of messages to all of them. List<Object[]> topicMessageCounts = forumManager.getMessageCountsForMainPage(topicIdsForCounts); for (Object[] counts : topicMessageCounts) { DiscussionTopicBean decoTopic = topicBeans.get(counts[0]); decoTopic.setTotalNoMessages((Integer) counts[1]); decoTopic.setUnreadNoMessages((Integer) counts[1]); } // get the total read message count for the current user of non-moderated and add them to the discussion // topic bean as the number of unread messages. I could've combined this with the previous query but // stupid Hibernate (3.x) won't let us properly outer join mapped entitys that do not have a direct // association. BLURG! Any topic not in the returned list means the user hasn't read any of the messages // in that topic which is why I set the default unread message count to all the messages in the previous // loop. topicMessageCounts = forumManager.getReadMessageCountsForMainPage(topicIdsForCounts); for (Object[] counts : topicMessageCounts) { DiscussionTopicBean decoTopic = topicBeans.get(counts[0]); decoTopic.setUnreadNoMessages(decoTopic.getTotalNoMessages() - (Integer) counts[1]); } // get the assignments for use later try { assignments = new ArrayList<SelectItem>(); assignments.add(new SelectItem(DEFAULT_GB_ITEM, getResourceBundleString(SELECT_ASSIGN))); //Code to get the gradebook service from ComponentManager GradebookService gradebookService = getGradebookService(); if (getGradebookExist()) { List gradeAssignmentsBeforeFilter = gradebookService .getAssignments(ToolManager.getCurrentPlacement().getContext()); for (int i = 0; i < gradeAssignmentsBeforeFilter.size(); i++) { Assignment thisAssign = (Assignment) gradeAssignmentsBeforeFilter.get(i); if (!thisAssign.isExternallyMaintained()) { try { assignments.add( new SelectItem(Integer.toString(assignments.size()), thisAssign.getName())); } catch (Exception e) { LOG.error("DiscussionForumTool - processDfMsgGrd:" + e); e.printStackTrace(); } } } } } catch (SecurityException se) { LOG.debug("SecurityException caught while getting assignments.", se); } catch (Exception e1) { LOG.error("DiscussionForumTool&processDfMsgGrad:" + e1); e1.printStackTrace(); } // now loop through the forums that we found earlier and turn them into forums ready to be displayed to the end user int sortIndex = 1; for (DiscussionForum forum : tempSortedForums) { // manually set the sort index now that the list is sorted forum.setSortIndex(Integer.valueOf(sortIndex)); sortIndex++; DiscussionForumBean decoForum = new DiscussionForumBean(forum, uiPermissionsManager, forumManager); if (readFullDescription) decoForum.setReadFullDesciption(true); if (forum.getTopics() != null) { for (Iterator itor = forum.getTopics().iterator(); itor.hasNext();) { DiscussionTopic topic = (DiscussionTopic) itor.next(); DiscussionTopicBean decoTopic = topicBeans.get(topic.getId()); if (decoTopic != null) decoForum.addTopic(decoTopic); } //itterate over all topics in the decoratedForum to add the unread message //counts to update the sypnoptic tool for (Iterator iterator = decoForum.getTopics().iterator(); iterator.hasNext();) { DiscussionTopicBean dTopicBean = (DiscussionTopicBean) iterator.next(); //if user can read this forum topic, count the messages as well if (uiPermissionsManager.isRead(dTopicBean.getTopic(), decoForum.getForum(), userId)) { unreadMessagesCount += dTopicBean.getUnreadNoMessages(); } } } decoForum.setGradeAssign(DEFAULT_GB_ITEM); for (int i = 0; i < assignments.size(); i++) { if (assignments.get(i).getLabel().equals(forum.getDefaultAssignName())) { decoForum.setGradeAssign(Integer.valueOf(i).toString()); break; } } forums.add(decoForum); } } //update synotpic info for forums only: setForumSynopticInfoHelper(userId, getSiteId(), unreadMessagesCount, SynopticMsgcntrManager.NUM_OF_ATTEMPTS); return forums; }