List of usage examples for java.lang Integer compareTo
public int compareTo(Integer anotherInteger)
From source file:org.opendatakit.persistence.engine.pgres.DatastoreImpl.java
/** * Relation manipulation APIs/*from w ww. j av a 2 s . co m*/ */ @Override public void assertRelation(CommonFieldsBase relation, User user) throws ODKDatastoreException { JdbcTemplate jc = getJdbcConnection(); TransactionStatus status = null; try { DefaultTransactionDefinition paramTransactionDefinition = new DefaultTransactionDefinition(); // do serializable read on the information schema... paramTransactionDefinition.setIsolationLevel(DefaultTransactionDefinition.ISOLATION_SERIALIZABLE); paramTransactionDefinition.setReadOnly(true); status = tm.getTransaction(paramTransactionDefinition); // see if relation already is defined and update it with dimensions... if (updateRelation(jc, relation, null)) { // it exists -- we're done! tm.commit(status); status = null; return; } else { tm.commit(status); // Try a new transaction to create the table paramTransactionDefinition.setIsolationLevel(DefaultTransactionDefinition.ISOLATION_SERIALIZABLE); paramTransactionDefinition.setReadOnly(false); status = tm.getTransaction(paramTransactionDefinition); // total number of columns must be less than MAX_BIND_PARAMS int countColumns = 0; // need to create the table... StringBuilder b = new StringBuilder(); b.append(K_CREATE_TABLE); b.append(K_BQ); b.append(relation.getSchemaName()); b.append(K_BQ); b.append("."); b.append(K_BQ); b.append(relation.getTableName()); b.append(K_BQ); b.append(K_OPEN_PAREN); boolean firstTime = true; for (DataField f : relation.getFieldList()) { if (!firstTime) { b.append(K_CS); } ++countColumns; firstTime = false; b.append(K_BQ); b.append(f.getName()); b.append(K_BQ); DataField.DataType type = f.getDataType(); switch (type) { case BINARY: b.append(" BYTEA"); break; case LONG_STRING: b.append(" TEXT");// b.append(" CHARACTER SET utf8"); break; case STRING: b.append(" VARCHAR("); Long len = f.getMaxCharLen(); if (len == null) { len = PersistConsts.DEFAULT_MAX_STRING_LENGTH; } b.append(len.toString()); b.append(K_CLOSE_PAREN); // b.append(" CHARACTER SET utf8"); break; case BOOLEAN: b.append(" BOOLEAN"); break; case INTEGER: Integer int_digits = f.getNumericPrecision(); if (int_digits == null) { int_digits = DEFAULT_INT_NUMERIC_PRECISION; } if (int_digits.compareTo(9) > 0) { b.append(" BIGINT"); } else { b.append(" INTEGER"); } break; case DECIMAL: if (f.isDoublePrecision()) { b.append(" FLOAT(53)"); } else { Integer dbl_digits = f.getNumericPrecision(); Integer dbl_fract = f.getNumericScale(); if (dbl_digits == null) { dbl_digits = DEFAULT_DBL_NUMERIC_PRECISION; } if (dbl_fract == null) { dbl_fract = DEFAULT_DBL_NUMERIC_SCALE; } b.append(" DECIMAL("); b.append(dbl_digits.toString()); b.append(K_CS); b.append(dbl_fract.toString()); b.append(K_CLOSE_PAREN); } break; case DATETIME: b.append(" TIMESTAMP WITHOUT TIME ZONE"); break; case URI: b.append(" VARCHAR("); len = f.getMaxCharLen(); if (len == null) { len = PersistConsts.URI_STRING_LEN; } b.append(len.toString()); b.append(")");// b.append(" CHARACTER SET utf8"); break; } if (f == relation.primaryKey) { b.append(" UNIQUE "); } if (f.getNullable()) { b.append(" NULL "); } else { b.append(" NOT NULL "); } } b.append(K_CLOSE_PAREN); if (countColumns > MAX_BIND_PARAMS) { throw new IllegalArgumentException("Table size exceeds bind parameter limit"); } String createTableStmt = b.toString(); LogFactory.getLog(DatastoreImpl.class).info("Attempting: " + createTableStmt); jc.execute(createTableStmt); LogFactory.getLog(DatastoreImpl.class) .info("create table success (before updateRelation): " + relation.getTableName()); String idx; // create other indicies for (DataField f : relation.getFieldList()) { if ((f.getIndexable() != IndexType.NONE) && (f != relation.primaryKey)) { idx = relation.getTableName() + "_" + shortPrefix(f.getName()); createIndex(jc, relation, idx, f); } } // and update the relation with actual dimensions... updateRelation(jc, relation, createTableStmt); tm.commit(status); } } catch (Exception e) { if (status != null) { tm.rollback(status); } throw new ODKDatastoreException(e); } }
From source file:org.opendatakit.common.persistence.engine.pgres.DatastoreImpl.java
/** * Relation manipulation APIs//from ww w. j a v a 2 s.c o m */ @Override public void assertRelation(CommonFieldsBase relation, User user) throws ODKDatastoreException { JdbcTemplate jc = getJdbcConnection(); TransactionStatus status = null; try { DefaultTransactionDefinition paramTransactionDefinition = new DefaultTransactionDefinition(); // do serializable read on the information schema... paramTransactionDefinition.setIsolationLevel(DefaultTransactionDefinition.ISOLATION_SERIALIZABLE); paramTransactionDefinition.setReadOnly(true); status = tm.getTransaction(paramTransactionDefinition); // see if relation already is defined and update it with dimensions... if (updateRelation(jc, relation, null)) { // it exists -- we're done! tm.commit(status); status = null; return; } else { tm.commit(status); // Try a new transaction to create the table paramTransactionDefinition.setIsolationLevel(DefaultTransactionDefinition.ISOLATION_SERIALIZABLE); paramTransactionDefinition.setReadOnly(false); status = tm.getTransaction(paramTransactionDefinition); // need to create the table... StringBuilder b = new StringBuilder(); b.append(K_CREATE_TABLE); b.append(K_BQ); b.append(relation.getSchemaName()); b.append(K_BQ); b.append("."); b.append(K_BQ); b.append(relation.getTableName()); b.append(K_BQ); b.append(K_OPEN_PAREN); boolean firstTime = true; for (DataField f : relation.getFieldList()) { if (!firstTime) { b.append(K_CS); } firstTime = false; b.append(K_BQ); b.append(f.getName()); b.append(K_BQ); DataField.DataType type = f.getDataType(); switch (type) { case BINARY: b.append(" BYTEA"); break; case LONG_STRING: b.append(" TEXT");// b.append(" CHARACTER SET utf8"); break; case STRING: b.append(" VARCHAR("); Long len = f.getMaxCharLen(); if (len == null) { len = PersistConsts.DEFAULT_MAX_STRING_LENGTH; } b.append(len.toString()); b.append(K_CLOSE_PAREN); // b.append(" CHARACTER SET utf8"); break; case BOOLEAN: b.append(" BOOLEAN"); break; case INTEGER: Integer int_digits = f.getNumericPrecision(); if (int_digits == null) { int_digits = DEFAULT_INT_NUMERIC_PRECISION; } Integer isSerial = f.getNumericScale(); // logger.warn("********************"); // logger.warn(int_digits + " ---" + isSerial); if (int_digits.compareTo(9) > 0) { if (isSerial != null && isSerial == 1) { b.append(" SERIAL"); continue; // logger.warn("^^^^^^^^^^^^^^^^"); } else { b.append(" BIGINT"); } } else { b.append(" INTEGER"); } break; case DECIMAL: Integer dbl_digits = f.getNumericPrecision(); Integer dbl_fract = f.getNumericScale(); if (dbl_digits == null) { dbl_digits = DEFAULT_DBL_NUMERIC_PRECISION; } if (dbl_fract == null) { dbl_fract = DEFAULT_DBL_NUMERIC_SCALE; } b.append(" DECIMAL("); b.append(dbl_digits.toString()); b.append(K_CS); b.append(dbl_fract.toString()); b.append(K_CLOSE_PAREN); break; case DATETIME: b.append(" TIMESTAMP WITHOUT TIME ZONE"); break; case URI: b.append(" VARCHAR("); len = f.getMaxCharLen(); if (len == null) { len = PersistConsts.URI_STRING_LEN; } b.append(len.toString()); b.append(")");// b.append(" CHARACTER SET utf8"); break; } if (f == relation.primaryKey) { b.append(" UNIQUE "); } if (f.getNullable()) { b.append(" NULL "); } else { b.append(" NOT NULL "); } } b.append(K_CLOSE_PAREN); String createTableStmt = b.toString(); LogFactory.getLog(DatastoreImpl.class).info("Attempting: " + createTableStmt); jc.execute(createTableStmt); LogFactory.getLog(DatastoreImpl.class) .info("create table success (before updateRelation): " + relation.getTableName()); String idx; // create other indicies for (DataField f : relation.getFieldList()) { if ((f.getIndexable() != IndexType.NONE) && (f != relation.primaryKey)) { idx = relation.getTableName() + "_" + shortPrefix(f.getName()); createIndex(jc, relation, idx, f); } } // and update the relation with actual dimensions... updateRelation(jc, relation, createTableStmt); tm.commit(status); } } catch (Exception e) { if (status != null) { tm.rollback(status); } throw new ODKDatastoreException(e); } }
From source file:org.opendatakit.common.persistence.engine.sqlserver.DatastoreImpl.java
/** * Relation manipulation APIs/*ww w .j av a 2 s . com*/ */ @Override public void assertRelation(CommonFieldsBase relation, User user) throws ODKDatastoreException { JdbcTemplate jc = getJdbcConnection(); TransactionStatus status = null; try { DefaultTransactionDefinition paramTransactionDefinition = new DefaultTransactionDefinition(); // do serializable read on the information schema... paramTransactionDefinition.setIsolationLevel(DefaultTransactionDefinition.ISOLATION_SERIALIZABLE); paramTransactionDefinition.setReadOnly(true); status = tm.getTransaction(paramTransactionDefinition); // see if relation already is defined and update it with dimensions... if (updateRelation(jc, relation, null)) { // it exists -- we're done! tm.commit(status); status = null; return; } else { tm.commit(status); // Try a new transaction to create the table paramTransactionDefinition.setIsolationLevel(DefaultTransactionDefinition.ISOLATION_SERIALIZABLE); paramTransactionDefinition.setReadOnly(false); status = tm.getTransaction(paramTransactionDefinition); // total number of columns must be less than MAX_BIND_PARAMS int countColumns = 0; // need to create the table... StringBuilder b = new StringBuilder(); b.append(K_CREATE_TABLE); b.append(K_BQ); b.append(relation.getSchemaName()); b.append(K_BQ); b.append("."); b.append(K_BQ); b.append(relation.getTableName()); b.append(K_BQ); b.append(K_OPEN_PAREN); boolean firstTime = true; for (DataField f : relation.getFieldList()) { if (!firstTime) { b.append(K_CS); } ++countColumns; firstTime = false; String nullClause; if (f.getNullable()) { nullClause = K_NULL; } else { nullClause = K_NOT_NULL; } b.append(K_BQ); b.append(f.getName()); b.append(K_BQ); DataField.DataType type = f.getDataType(); switch (type) { case BINARY: b.append(" varbinary(max)").append(nullClause); break; case LONG_STRING: b.append(" nvarchar(max)").append(nullClause); break; case STRING: b.append(" nvarchar("); Long len = f.getMaxCharLen(); if (len == null) { len = PersistConsts.DEFAULT_MAX_STRING_LENGTH; } if (len > MAX_IN_ROW_NVARCHAR) { // store value out-of-row b.append("max"); } else { b.append(len.toString()); } b.append(K_CLOSE_PAREN).append(nullClause); break; case BOOLEAN: b.append(" bit").append(nullClause); break; case INTEGER: Integer int_digits = f.getNumericPrecision(); if (int_digits == null) { int_digits = DEFAULT_INT_NUMERIC_PRECISION; } if (int_digits.compareTo(9) > 0) { b.append(" bigint").append(nullClause); } else { b.append(" integer").append(nullClause); } break; case DECIMAL: if (f == relation.primaryKey) { throw new IllegalStateException("cannot use decimal columns as primary keys"); } if (f.isDoublePrecision()) { b.append(" float(53) ").append(nullClause); } else { Integer dbl_digits = f.getNumericPrecision(); Integer dbl_fract = f.getNumericScale(); if (dbl_digits == null) { dbl_digits = DEFAULT_DBL_NUMERIC_PRECISION; } if (dbl_fract == null) { dbl_fract = DEFAULT_DBL_NUMERIC_SCALE; } b.append(" decimal("); b.append(dbl_digits.toString()); b.append(K_CS); b.append(dbl_fract.toString()); b.append(K_CLOSE_PAREN).append(nullClause); } break; case DATETIME: b.append(" datetime2(7)").append(nullClause); break; case URI: b.append(" nvarchar("); len = f.getMaxCharLen(); if (len == null) { len = PersistConsts.URI_STRING_LEN; } b.append(len.toString()); b.append(")").append(nullClause); break; } if (f == relation.primaryKey) { b.append(" PRIMARY KEY NONCLUSTERED "); } } b.append(K_CLOSE_PAREN); if (countColumns > MAX_BIND_PARAMS) { throw new IllegalArgumentException("Table size exceeds bind parameter limit"); } String createTableStmt = b.toString(); LogFactory.getLog(DatastoreImpl.class).info("Attempting: " + createTableStmt); jc.execute(createTableStmt); LogFactory.getLog(DatastoreImpl.class) .info("create table success (before updateRelation): " + relation.getTableName()); boolean alreadyClustered = false; String idx; // create other indicies for (DataField f : relation.getFieldList()) { if ((f.getIndexable() != IndexType.NONE) && (f != relation.primaryKey)) { idx = relation.getTableName() + "_" + shortPrefix(f.getName()); alreadyClustered = createIndex(jc, relation, idx, f, alreadyClustered); } } // and update the relation with actual dimensions... updateRelation(jc, relation, createTableStmt); tm.commit(status); } } catch (Exception e) { if (status != null) { tm.rollback(status); } throw new ODKDatastoreException(e); } }
From source file:com.eyeq.pivot4j.ui.impl.RenderStrategyImpl.java
/** * @param model// ww w.j a v a 2 s .c o m * @param renderer * @param axis * @return */ protected TableHeaderNode createAxisTree(PivotModel model, PivotRenderer renderer, Axis axis) { List<CellSetAxis> axes = model.getCellSet().getAxes(); if (axes.size() < 2) { return null; } CellSetAxis cellSetAxis = axes.get(axis.axisOrdinal()); List<Position> positions = cellSetAxis.getPositions(); if (positions == null || positions.isEmpty()) { return null; } List<Hierarchy> hierarchies = new ArrayList<Hierarchy>(); List<Aggregator> aggregators = new ArrayList<Aggregator>(); List<Aggregator> hierarchyAggregators = new ArrayList<Aggregator>(); List<Aggregator> memberAggregators = new ArrayList<Aggregator>(); Map<AggregatorPosition, List<Aggregator>> aggregatorMap = new HashMap<AggregatorPosition, List<Aggregator>>(); aggregatorMap.put(AggregatorPosition.Grand, aggregators); aggregatorMap.put(AggregatorPosition.Hierarchy, hierarchyAggregators); aggregatorMap.put(AggregatorPosition.Member, memberAggregators); Map<Hierarchy, List<Level>> levelsMap = new HashMap<Hierarchy, List<Level>>(); Comparator<Level> levelComparator = new Comparator<Level>() { @Override public int compare(Level l1, Level l2) { Integer d1 = l1.getDepth(); Integer d2 = l2.getDepth(); return d1.compareTo(d2); } }; boolean containsMeasure = false; List<Member> firstMembers = positions.get(0).getMembers(); int index = 0; for (Member member : firstMembers) { if (member instanceof Measure) { containsMeasure = true; break; } index++; } AggregatorFactory aggregatorFactory = renderer.getAggregatorFactory(); List<String> aggregatorNames = null; List<String> hierarchyAggregatorNames = null; List<String> memberAggregatorNames = null; if (aggregatorFactory != null && (!containsMeasure || index == firstMembers.size() - 1)) { aggregatorNames = renderer.getAggregators(axis, AggregatorPosition.Grand); hierarchyAggregatorNames = renderer.getAggregators(axis, AggregatorPosition.Hierarchy); memberAggregatorNames = renderer.getAggregators(axis, AggregatorPosition.Member); } if (aggregatorNames == null) { aggregatorNames = Collections.emptyList(); } if (hierarchyAggregatorNames == null) { hierarchyAggregatorNames = Collections.emptyList(); } if (memberAggregatorNames == null) { memberAggregatorNames = Collections.emptyList(); } TableAxisContext nodeContext = new TableAxisContext(axis, hierarchies, levelsMap, aggregatorMap, renderer); TableHeaderNode axisRoot = new TableHeaderNode(nodeContext); Set<Measure> grandTotalMeasures = new LinkedHashSet<Measure>(); Set<Measure> totalMeasures = new LinkedHashSet<Measure>(); Map<Hierarchy, List<AggregationTarget>> memberParentMap = new HashMap<Hierarchy, List<AggregationTarget>>(); Position lastPosition = null; for (Position position : positions) { TableHeaderNode lastChild = null; List<Member> members = position.getMembers(); int memberCount = members.size(); for (int i = memberCount - 1; i >= 0; i--) { Member member = members.get(i); if (member instanceof Measure) { Measure measure = (Measure) member; if (!totalMeasures.contains(measure)) { totalMeasures.add(measure); } if (!grandTotalMeasures.contains(measure)) { grandTotalMeasures.add(measure); } } else if (member != null && member.getDepth() > 0 && nodeContext.getParentMember(member) == null) { member = new RaggedMemberWrapper(member, model.getCube()); } if (hierarchies.size() < memberCount) { hierarchies.add(0, member.getHierarchy()); } List<Level> levels = levelsMap.get(member.getHierarchy()); if (levels == null) { levels = new ArrayList<Level>(); levelsMap.put(member.getHierarchy(), levels); } if (!levels.contains(member.getLevel())) { levels.add(0, member.getLevel()); Collections.sort(levels, levelComparator); } TableHeaderNode childNode = new TableHeaderNode(nodeContext); childNode.setMember(member); childNode.setHierarchy(member.getHierarchy()); childNode.setPosition(position); if (lastChild != null) { childNode.addChild(lastChild); } lastChild = childNode; if (!hierarchyAggregatorNames.isEmpty() && lastPosition != null) { int start = memberCount - 1; if (containsMeasure) { start--; } if (i < start) { Member lastMember = lastPosition.getMembers().get(i); if (OlapUtils.equals(lastMember.getHierarchy(), member.getHierarchy()) && !OlapUtils.equals(lastMember, member) || !OlapUtils.equals(position, lastPosition, i)) { for (String aggregatorName : hierarchyAggregatorNames) { createAggregators(aggregatorName, nodeContext, hierarchyAggregators, axisRoot, null, lastPosition.getMembers().subList(0, i + 1), totalMeasures); } } } } if (!memberAggregatorNames.isEmpty()) { List<AggregationTarget> memberParents = memberParentMap.get(member.getHierarchy()); if (memberParents == null) { memberParents = new ArrayList<AggregationTarget>(); memberParentMap.put(member.getHierarchy(), memberParents); } AggregationTarget lastSibling = null; if (!memberParents.isEmpty()) { lastSibling = memberParents.get(memberParents.size() - 1); } Member parentMember; if (member instanceof RaggedMemberWrapper) { parentMember = ((RaggedMemberWrapper) member).getTopMember(); } else { parentMember = axisRoot.getReference().getParentMember(member); } if (parentMember != null) { if (lastSibling == null || axisRoot.getReference().getAncestorMembers(parentMember) .contains(lastSibling.getParent())) { memberParents.add(new AggregationTarget(parentMember, member.getLevel())); } else if (!OlapUtils.equals(parentMember, lastSibling.getParent())) { while (!memberParents.isEmpty()) { int lastIndex = memberParents.size() - 1; AggregationTarget lastParent = memberParents.get(lastIndex); if (OlapUtils.equals(lastParent.getParent(), parentMember)) { break; } memberParents.remove(lastIndex); List<Member> path = new ArrayList<Member>(lastPosition.getMembers().subList(0, i)); path.add(lastParent.getParent()); Level parentLevel = lastParent.getParent().getLevel(); if (!levels.contains(parentLevel)) { levels.add(0, parentLevel); Collections.sort(levels, levelComparator); } for (String aggregatorName : memberAggregatorNames) { createAggregators(aggregatorName, nodeContext, memberAggregators, axisRoot, lastParent.getLevel(), path, totalMeasures); } } } } if (lastPosition != null && !OlapUtils.equals(position, lastPosition, i)) { Hierarchy hierarchy = nodeContext.getHierarchies().get(i); Level rootLevel = nodeContext.getLevels(hierarchy).get(0); for (AggregationTarget target : memberParents) { Member memberParent = target.getParent(); if (memberParent.getLevel().getDepth() < rootLevel.getDepth()) { continue; } List<Member> path = new ArrayList<Member>(lastPosition.getMembers().subList(0, i)); path.add(memberParent); for (String aggregatorName : memberAggregatorNames) { createAggregators(aggregatorName, nodeContext, memberAggregators, axisRoot, target.getLevel(), path, totalMeasures); } } memberParents.clear(); } } } if (lastChild != null) { axisRoot.addChild(lastChild); } lastPosition = position; } if (lastPosition != null) { int memberCount = lastPosition.getMembers().size(); int start = memberCount - 1; if (containsMeasure) { start--; } for (int i = start; i >= 0; i--) { if (!memberAggregatorNames.isEmpty()) { Hierarchy hierarchy = nodeContext.getHierarchies().get(i); Level rootLevel = nodeContext.getLevels(hierarchy).get(0); List<AggregationTarget> memberParents = memberParentMap.get(hierarchy); for (AggregationTarget target : memberParents) { Member member = target.getParent(); if (member.getLevel().getDepth() < rootLevel.getDepth()) { continue; } List<Member> path = new ArrayList<Member>(lastPosition.getMembers().subList(0, i)); path.add(member); for (String aggregatorName : memberAggregatorNames) { createAggregators(aggregatorName, nodeContext, memberAggregators, axisRoot, target.getLevel(), path, totalMeasures); } } } if (!hierarchyAggregatorNames.isEmpty()) { for (String aggregatorName : hierarchyAggregatorNames) { createAggregators(aggregatorName, nodeContext, hierarchyAggregators, axisRoot, null, lastPosition.getMembers().subList(0, i), totalMeasures); } } } if (!aggregatorNames.isEmpty()) { List<Member> members = Collections.emptyList(); for (String aggregatorName : aggregatorNames) { createAggregators(aggregatorName, nodeContext, aggregators, axisRoot, null, members, grandTotalMeasures); } } } if (logger.isDebugEnabled()) { logger.debug("Original axis tree root for " + axis); axisRoot.walkTree(new TreeNodeCallback<TableAxisContext>() { @Override public int handleTreeNode(TreeNode<TableAxisContext> node) { String label = node.toString(); logger.trace(StringUtils.leftPad(label, node.getLevel() + label.length(), ' ')); return CONTINUE; } }); } return axisRoot; }
From source file:org.jahia.utils.maven.plugin.contentgenerator.wise.FileAndFolderService.java
public Set<FileBO> generateFiles(Integer nbFilesToGenerate, String currentNodePath, List<String> fileNames, Integer nbUsers, File filesDirectory, List<TagBO> tags, String wiseInstanceName) { // logger.debug("Generating " + nbFiles + " files"); SortedSet<FileBO> files = new TreeSet<FileBO>(); List<String> fileNamesAvailable = new ArrayList<String>(fileNames); Integer nbAvailableFiles = fileNames.size(); int currentFilenameIndex = 0; String imageExtensions[] = { ".png", ".gif", ".jpeg", ".jpg" }; String officeDocumentExtensions[] = { ".doc", ".xls", ".ppt", ".docx", ".xlsx", ".pptx" }; String creator = "root"; String owner = "root"; String editor = "root"; String reader = "root"; int idCreator; int idOwner;// ww w . j av a2 s .co m int idEditor; int idReader; int nbOfTags = tags.size(); int randFilenameIndex; String extractedContent = ""; FileBO newFile = null; while (files.size() < nbFilesToGenerate) { // logger.debug("Generating file " + (files.size() + 1) + "/" + nbFilesToGenerate); String fileName = ""; if (nbFilesToGenerate.compareTo(nbAvailableFiles) >= 0) { fileName = fileNames.get(currentFilenameIndex); currentFilenameIndex++; } else { int remainingNbAvailableFiles = fileNamesAvailable.size() - 1; randFilenameIndex = rand.nextInt(remainingNbAvailableFiles); fileName = fileNamesAvailable.get(randFilenameIndex); fileNamesAvailable.remove(randFilenameIndex); } String mixin = ""; if (nbUsers != null && (nbUsers.compareTo(0) > 0)) { idCreator = rand.nextInt(nbUsers - 1); creator = "user" + idCreator; idOwner = rand.nextInt(nbUsers - 1); owner = "user" + idOwner; idEditor = rand.nextInt(nbUsers - 1); editor = "user" + idEditor; idReader = rand.nextInt(nbUsers - 1); reader = "user" + idReader; } // Choose correct mixin depending on the file extension String fileExtension = getFileExtension(fileName); if (Arrays.asList(imageExtensions).contains(fileExtension)) { mixin = " jmix:image"; } else if (Arrays.asList(officeDocumentExtensions).contains(fileExtension)) { mixin = " jmix:document"; } // Detect MIME type File f = new File(filesDirectory + sep + fileName); String mimeType = getMimeType(f); // Extract file content Metadata metadata = new Metadata(); if (mimeType != null) { metadata.set(Metadata.CONTENT_TYPE, mimeType); } try { extractedContent = new Tika().parseToString(f); } catch (FileNotFoundException e) { logger.error("File not found during text extraction " + f.getAbsoluteFile()); e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TikaException e) { // TODO Auto-generated catch block e.printStackTrace(); } String description = getCurrentOftenDescriptionWord() + " " + getCurrentSeldomDescriptionWord(); // Random choice of tag int randomTagIndex = rand.nextInt(nbOfTags - 1); TagBO tag = tags.get(randomTagIndex); // Random creation date String creationDate = getRandomJcrDate(timestampDifference); newFile = new FileBO(fileName, mixin, mimeType, currentNodePath + "/" + fileName, creator, owner, editor, reader, extractedContent, description, tag.getTagName(), wiseInstanceName, creationDate); files.add(newFile); } return files; }
From source file:com.ephesoft.dcma.tablefinder.share.DataTableService.java
/** * Sorts table columns list on the basis of their column start coordinates. * /* w ww. jav a2 s .c om*/ * @param tableColumnList {@link List}<{@link TableColumnVO}> */ private void sortTableColumns(final List<TableColumnVO> tableColumnList) { LOGGER.info("Sorting table columns based on their start end coordinates."); if (CollectionUtils.isNotEmpty(tableColumnList)) { Collections.sort(tableColumnList, new Comparator<TableColumnVO>() { @Override public int compare(final TableColumnVO object1, final TableColumnVO object2) { int comparison; if (null == object1 || null == object2) { comparison = TableExtractionConstants.EQUAL_COMPARISON; } else { String startCoordinate = object1.getColumnStartCoordinate(); String endCoordinate = object2.getColumnEndCoordinate(); Integer startCoordinateObject1 = null; Integer startCoordinateObject2 = null; if (NumberUtils.isDigits(startCoordinate) && NumberUtils.isDigits(endCoordinate)) { startCoordinateObject1 = Integer.parseInt(startCoordinate); startCoordinateObject2 = Integer.parseInt(endCoordinate); } // Comparing start coordinates of column coordinates of two input table columns. if (null == startCoordinateObject1 && null == startCoordinateObject2) { comparison = TableExtractionConstants.EQUAL_COMPARISON; } else if (null == startCoordinateObject1) { comparison = TableExtractionConstants.LESS_COMPARISON; } else if (null == startCoordinateObject2) { comparison = TableExtractionConstants.GREATER_COMPARISON; } else { comparison = startCoordinateObject1.compareTo(startCoordinateObject2); } } return comparison; } }); } }
From source file:edu.ku.brc.specify.config.Scriptlet.java
/** * @param catalogNumber//w ww. j a va 2s. c om * @return for specimen indicated by catalogNumber, the Collectors (excluding the first Collector formatted by the default Collector aggregator. */ public String getSecondaryCollectors(final Object catalogNumber) { DataProviderSessionIFace session = DataProviderFactory.getInstance().createSession(); try { String result = ""; UIFieldFormatterIFace formatter = DBTableIdMgr.getInstance() .getInfoById(CollectionObject.getClassTableId()).getFieldByName("catalogNumber").getFormatter(); Object dbCatNum = formatter.formatFromUI(catalogNumber); List<?> list = session.getDataList(CollectionObject.class, "catalogNumber", dbCatNum); if (list.size() > 0) { CollectingEvent ce = (CollectingEvent) ((CollectionObject) list.get(0)).getCollectingEvent(); Set<Collector> collectors = ce.getCollectors(); if (collectors.size() > 1) { Collector firstCollector = null; for (Collector collector : collectors) { if (firstCollector == null || collector.getOrderNumber() < firstCollector.getOrderNumber()) { firstCollector = collector; } } if (firstCollector != null) { collectors.remove(firstCollector); Vector<Collector> sortedCollectors = new Vector<Collector>(collectors); Collections.sort(sortedCollectors, new Comparator<Collector>() { /* (non-Javadoc) * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ @Override public int compare(Collector arg0, Collector arg1) { Integer order0 = arg0.getOrderNumber() != null ? arg0.getOrderNumber() : -1; ; Integer order1 = arg1.getOrderNumber() != null ? arg1.getOrderNumber() : -1; return order0.compareTo(order1); } }); result = DataObjFieldFormatMgr.getInstance().aggregate(collectors, Collector.class); } } else { result = ""; } } else { log.error("Couldn't locate CatalogNumber [" + catalogNumber + "]"); } return result; } finally { session.close(); } }
From source file:net.sourceforge.fenixedu.applicationTier.Servico.teacher.onlineTests.InsertTestQuestion.java
protected void run(String executionCourseId, String testId, String[] metadataId, Integer questionOrder, Double questionValue, CorrectionFormula formula) throws FenixServiceException { for (String element : metadataId) { Metadata metadata = FenixFramework.getDomainObject(element); if (metadata == null) { throw new InvalidArgumentsServiceException(); }/*from w ww .j a v a2s .c o m*/ Question question = null; if (metadata.getVisibleQuestions() != null && metadata.getVisibleQuestions().size() != 0) { question = metadata.getVisibleQuestions().iterator().next(); } else { throw new InvalidArgumentsServiceException(); } if (question == null) { throw new InvalidArgumentsServiceException(); } Test test = FenixFramework.getDomainObject(testId); if (test == null) { throw new InvalidArgumentsServiceException(); } List<TestQuestion> testQuestionList = new ArrayList<TestQuestion>(test.getTestQuestionsSet()); Collections.sort(testQuestionList, new BeanComparator("testQuestionOrder")); if (testQuestionList != null) { if (questionOrder == null || questionOrder.equals(Integer.valueOf(-1))) { questionOrder = Integer.valueOf(testQuestionList.size() + 1); } else { questionOrder = Integer.valueOf(questionOrder.intValue() + 1); } for (TestQuestion iterTestQuestion : testQuestionList) { Integer iterQuestionOrder = iterTestQuestion.getTestQuestionOrder(); if (questionOrder.compareTo(iterQuestionOrder) <= 0) { iterTestQuestion.setTestQuestionOrder(Integer.valueOf(iterQuestionOrder.intValue() + 1)); } } } Double thisQuestionValue = questionValue; if (questionValue == null) { ParseSubQuestion parseQuestion = new ParseSubQuestion(); if (thisQuestionValue == null) { thisQuestionValue = new Double(0); } try { InfoQuestion infoQuestion = InfoQuestion.newInfoFromDomain(question); question = parseQuestion.parseSubQuestion(question); if (infoQuestion.getQuestionValue() != null) { thisQuestionValue = infoQuestion.getQuestionValue(); } else { for (SubQuestion subQuestion : question.getSubQuestions()) { if (subQuestion.getQuestionValue() != null) { thisQuestionValue = new Double(thisQuestionValue.doubleValue() + subQuestion.getQuestionValue().doubleValue()); } } } } catch (Exception e) { throw new FenixServiceException(e); } } TestQuestion testQuestion = new TestQuestion(); test.setLastModifiedDate(Calendar.getInstance().getTime()); testQuestion.setQuestion(question); testQuestion.setTest(test); testQuestion.setTestQuestionOrder(questionOrder); testQuestion.setTestQuestionValue(thisQuestionValue); testQuestion.setCorrectionFormula(formula); } }
From source file:org.telegram.ui.ChatProfileActivity.java
private void updateOnlineCount() { if (info == null) { return;//w w w .j av a 2 s .co m } onlineCount = 0; int currentTime = ConnectionsManager.Instance.getCurrentTime(); sortedUsers.clear(); int i = 0; for (TLRPC.TL_chatParticipant participant : info.participants) { TLRPC.User user = MessagesController.Instance.users.get(participant.user_id); if (user != null && user.status != null && (user.status.expires > currentTime || user.status.was_online > currentTime || user.id == UserConfig.clientUserId) && (user.status.expires > 10000 || user.status.was_online > 10000)) { onlineCount++; } sortedUsers.add(i); i++; } Collections.sort(sortedUsers, new Comparator<Integer>() { @Override public int compare(Integer lhs, Integer rhs) { TLRPC.User user1 = MessagesController.Instance.users.get(info.participants.get(rhs).user_id); TLRPC.User user2 = MessagesController.Instance.users.get(info.participants.get(lhs).user_id); Integer status1 = 0; Integer status2 = 0; if (user1 != null && user1.status != null) { if (user1.id == UserConfig.clientUserId) { status1 = ConnectionsManager.Instance.getCurrentTime() + 50000; } else { status1 = user1.status.expires; if (status1 == 0) { status1 = user1.status.was_online; } } } if (user2 != null && user2.status != null) { if (user2.id == UserConfig.clientUserId) { status2 = ConnectionsManager.Instance.getCurrentTime() + 50000; } else { status2 = user2.status.expires; if (status2 == 0) { status2 = user2.status.was_online; } } } return status1.compareTo(status2); } }); if (listView != null) { listView.invalidateViews(); } }
From source file:edu.harvard.i2b2.crc.dao.setfinder.querybuilder.temporal.TemporalPanel.java
@Override public int compareTo(Object element) { if (element.getClass().equals((TemporalPanel.class))) { TemporalPanel tp2 = (TemporalPanel) element; Integer tp1Score = this.getTimingScore(); Integer tp2Score = tp2.getTimingScore(); int compare = tp1Score.compareTo(tp2Score); if (compare == 0) { tp1Score = this.getEstimatedTotal(); tp2Score = tp2.getEstimatedTotal(); compare = tp1Score.compareTo(tp2Score); if (compare == 0) { tp1Score = this.basePanel.getPanelNumber(); tp2Score = tp2.basePanel.getPanelNumber(); compare = tp1Score.compareTo(tp2Score); if (compare == 0) { return this.toString().compareTo(tp2.toString()); } else return compare; } else return compare; } else// w w w .j a va2 s . co m return compare; } else { return this.toString().compareTo(element.toString()); } }