List of usage examples for java.util Vector indexOf
public int indexOf(Object o)
From source file:fr.sanofi.fcl4transmart.controllers.listeners.geneExpression.SetSubjectsIdListener.java
@Override public void handleEvent(Event event) { // TODO Auto-generated method stub Vector<String> values = this.setSubjectsIdUI.getValues(); Vector<String> samples = this.setSubjectsIdUI.getSamples(); for (String v : values) { if (v.compareTo("") == 0) { this.setSubjectsIdUI.displayMessage("All identifiers have to be set"); return; }//from w w w. ja v a 2 s . c o m } File file = new File(this.dataType.getPath().toString() + File.separator + this.dataType.getStudy().toString() + ".subject_mapping.tmp"); try { FileWriter fw = new FileWriter(file); BufferedWriter out = new BufferedWriter(fw); out.write( "study_id\tsite_id\tsubject_id\tSAMPLE_ID\tPLATFORM\tTISSUETYPE\tATTR1\tATTR2\tcategory_cd\n"); File stsmf = ((GeneExpressionData) this.dataType).getStsmf(); if (stsmf == null) { for (int i = 0; i < samples.size(); i++) { out.write(this.dataType.getStudy().toString() + "\t" + "\t" + values.elementAt(i) + "\t" + samples.elementAt(i) + "\t" + "\t" + "\t" + "\t" + "\t" + "\n"); } } else { try { BufferedReader br = new BufferedReader(new FileReader(stsmf)); String line = br.readLine(); while ((line = br.readLine()) != null) { String[] fields = line.split("\t", -1); String sample = fields[3]; String subject; if (samples.contains(sample)) { subject = values.get(samples.indexOf(sample)); } else { br.close(); return; } out.write(fields[0] + "\t" + fields[1] + "\t" + subject + "\t" + sample + "\t" + fields[4] + "\t" + fields[5] + "\t" + fields[6] + "\t" + fields[7] + "\t" + fields[8] + "\n"); } br.close(); } catch (Exception e) { this.setSubjectsIdUI.displayMessage("File error: " + e.getLocalizedMessage()); out.close(); e.printStackTrace(); } } out.close(); try { File fileDest; if (stsmf != null) { String fileName = stsmf.getName(); stsmf.delete(); fileDest = new File(this.dataType.getPath() + File.separator + fileName); } else { fileDest = new File(this.dataType.getPath() + File.separator + this.dataType.getStudy().toString() + ".subject_mapping"); } FileUtils.moveFile(file, fileDest); ((GeneExpressionData) this.dataType).setSTSMF(fileDest); } catch (IOException ioe) { this.setSubjectsIdUI.displayMessage("File error: " + ioe.getLocalizedMessage()); return; } } catch (Exception e) { this.setSubjectsIdUI.displayMessage("Error: " + e.getLocalizedMessage()); e.printStackTrace(); } this.setSubjectsIdUI.displayMessage("Subject to sample mapping file updated"); WorkPart.updateSteps(); WorkPart.updateFiles(); UsedFilesPart.sendFilesChanged(dataType); }
From source file:edu.ku.brc.specify.dbsupport.SpecifyDeleteHelper.java
/** * @param si//from w w w . j a va 2 s.c om * @param level * @param excludeCls * @param excludeFromRequirement * @return * @throws SQLException */ public boolean checkRequiredRecs(final StackItem si, final int level, final int id, final Class<?> excludeCls, final int[] excludeFromRequirement) throws SQLException { Vector<Integer> ids = getIds(si.getSql() + id, level); if (si.getTableInfo().getClassObj().equals(excludeCls)) { for (int exid : excludeFromRequirement) { int idx = ids.indexOf(exid); if (idx != -1) { ids.remove(idx); //assuming no dups in ids } } } if (ids.size() > 0) { return true; } // for (StackItem s : si.getStack()) // { // if (checkRequiredRecs(s, level+1, excludeCls, excludeFromRequirement)) // { // return true; // } // } return false; }
From source file:edu.ku.brc.specify.tasks.subpane.wb.XLSExport.java
public void writeData(final List<?> data) throws Exception { HSSFWorkbook workBook = new HSSFWorkbook(); HSSFSheet workSheet = workBook.createSheet(); DocumentSummaryInformation mappings = null; int rowNum = 0; if (config.getFirstRowHasHeaders() && !config.getAppendData()) { writeHeaders(workSheet);//from w w w .j a v a 2s . com rowNum++; String[] headers = config.getHeaders(); for (int i = 0; i < headers.length; i++) { workSheet.setColumnWidth(i, StringUtils.isNotEmpty(headers[i]) ? (256 * headers[i].length()) : 2560); } WorkbenchTemplate wbTemplate = null; if (data.get(0) instanceof WorkbenchTemplate) { wbTemplate = (WorkbenchTemplate) data.get(0); } else { wbTemplate = ((WorkbenchRow) data.get(0)).getWorkbench().getWorkbenchTemplate(); } mappings = writeMappings(wbTemplate); } //assuming data is never empty. boolean hasTemplate = data.get(0) instanceof WorkbenchTemplate; boolean hasRows = hasTemplate ? data.size() > 1 : data.size() > 0; if (hasRows) { int[] disciplinees; WorkbenchRow wbRow = (WorkbenchRow) data.get(hasTemplate ? 1 : 0); Workbench workBench = wbRow.getWorkbench(); WorkbenchTemplate template = workBench.getWorkbenchTemplate(); int numCols = template.getWorkbenchTemplateMappingItems().size(); int geoDataCol = -1; Vector<Integer> imgCols = new Vector<Integer>(); disciplinees = bldColTypes(template); for (Object rowObj : data) { if (rowObj instanceof WorkbenchTemplate) { continue; } WorkbenchRow row = (WorkbenchRow) rowObj; HSSFRow hssfRow = workSheet.createRow(rowNum++); int colNum; boolean rowHasGeoData = false; for (colNum = 0; colNum < numCols; colNum++) { HSSFCell cell = hssfRow.createCell(colNum); cell.setCellType(disciplinees[colNum]); setCellValue(cell, row.getData(colNum)); } if (row.getBioGeomancerResults() != null && !row.getBioGeomancerResults().equals("")) { geoDataCol = colNum; rowHasGeoData = true; HSSFCell cell = hssfRow.createCell(colNum++); cell.setCellType(HSSFCell.CELL_TYPE_STRING); setCellValue(cell, row.getBioGeomancerResults()); } // if (row.getCardImage() != null) if (row.getRowImage(0) != null) { if (!rowHasGeoData) { colNum++; } int imgIdx = 0; WorkbenchRowImage img = row.getRowImage(imgIdx++); while (img != null) { if (imgCols.indexOf(colNum) < 0) { imgCols.add(colNum); } HSSFCell cell = hssfRow.createCell(colNum++); cell.setCellType(HSSFCell.CELL_TYPE_STRING); String cellValue = img.getCardImageFullPath(); String attachToTbl = img.getAttachToTableName(); if (attachToTbl != null) { cellValue += "\t" + attachToTbl; } setCellValue(cell, cellValue); img = row.getRowImage(imgIdx++); } } } if (imgCols.size() > 0 || geoDataCol != -1) { writeExtraHeaders(workSheet, imgCols, geoDataCol); } } try { // Write the workbook File file = new File(getConfig().getFileName()); if (file.canWrite() || (!file.exists() && file.createNewFile())) { FileOutputStream fos = new FileOutputStream(file); workBook.write(fos); fos.close(); //Now write the mappings. //NOT (hopefully) the best way to write the mappings, but (sadly) the easiest way. //May need to do this another way if this slows performance for big wbs. if (mappings != null) { InputStream is = new FileInputStream(file); POIFSFileSystem poifs = new POIFSFileSystem(is); is.close(); mappings.write(poifs.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME); fos = new FileOutputStream(file); poifs.writeFilesystem(fos); fos.close(); } } else { UIRegistry.displayErrorDlgLocalized("WB_EXPORT_PERM_ERR"); } } catch (Exception e) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(XLSExport.class, e); throw (e); } }
From source file:fr.sanofi.fcl4transmart.controllers.listeners.clinicalData.SetLabelsOntologyListener.java
@Override public void handleEvent(Event event) { // TODO Auto-generated method stub Vector<String> headers = this.setLabelsOntologyUI.getHeaders(); Vector<String> newLabels = this.setLabelsOntologyUI.getNewLabels(); Vector<String> codes = this.setLabelsOntologyUI.getCodes(); if (((ClinicalData) this.dataType).getCMF() == null) { this.setLabelsOntologyUI.displayMessage("Error: no column mapping file"); return;//from www . j av a 2 s.com } File file = new File(this.dataType.getPath().toString() + File.separator + this.dataType.getStudy().toString() + ".columns.tmp"); try { FileWriter fw = new FileWriter(file); BufferedWriter out = new BufferedWriter(fw); out.write( "Filename\tCategory Code\tColumn Number\tData Label\tData Label Source\tControlled Vocab Code\n"); try { BufferedReader br = new BufferedReader(new FileReader(((ClinicalData) this.dataType).getCMF())); String line = br.readLine(); while ((line = br.readLine()) != null) { if (line.split("\t", -1)[3].compareTo("SUBJ_ID") == 0 || line.split("\t", -1)[3].compareTo("VISIT_NAME") == 0 || line.split("\t", -1)[3].compareTo("SITE_ID") == 0 || line.split("\t", -1)[3].compareTo("\\") == 0 || line.split("\t", -1)[3].compareTo("DATA_LABEL") == 0 || line.split("\t", -1)[3].compareTo("OMIT") == 0) { out.write(line + "\n"); } else { File rawFile = new File(this.dataType.getPath() + File.separator + line.split("\t", -1)[0]); String header = FileHandler.getColumnByNumber(rawFile, Integer.parseInt(line.split("\t", -1)[2])); String newLabel = newLabels.elementAt(headers.indexOf(rawFile.getName() + " - " + header)); if (newLabel.compareTo("") == 0) { newLabel = header; } out.write(line.split("\t", -1)[0] + "\t" + line.split("\t", -1)[1] + "\t" + line.split("\t", -1)[2] + "\t" + newLabel + "\t\t" + codes.elementAt(headers.indexOf(rawFile.getName() + " - " + header)) + "\n"); } } br.close(); } catch (Exception e) { this.setLabelsOntologyUI.displayMessage("Error: " + e.getLocalizedMessage()); e.printStackTrace(); out.close(); } out.close(); String fileName = ((ClinicalData) this.dataType).getCMF().getName(); FileUtils.deleteQuietly(((ClinicalData) this.dataType).getCMF()); try { File fileDest = new File(this.dataType.getPath() + File.separator + fileName); FileUtils.moveFile(file, fileDest); ((ClinicalData) this.dataType).setCMF(fileDest); } catch (Exception ioe) { this.setLabelsOntologyUI.displayMessage("File error: " + ioe.getLocalizedMessage()); return; } } catch (Exception e) { this.setLabelsOntologyUI.displayMessage("Error: " + e.getLocalizedMessage()); e.printStackTrace(); } this.setLabelsOntologyUI.displayMessage("Column mapping file updated"); WorkPart.updateSteps(); WorkPart.updateFiles(); }
From source file:edu.ku.brc.specify.tasks.ReportsBaseTask.java
/** * @param mimeType/*from www. ja v a2 s .c o m*/ * @param reportType * @param defaultIcon * @param classTableId * @return List of command defs for valid report AppResources. * * Needed to 'override' static method in BaseTask to deal with imported reports. */ protected List<TaskCommandDef> getAppResCommandsByMimeType(final String mimeType, final String reportType, final String defaultIcon, final Integer classTableId) { List<TaskCommandDef> result = new LinkedList<TaskCommandDef>(); Vector<Integer> excludedTableIds = new Vector<Integer>(); excludedTableIds.add(79); Vector<String> subReports = new Vector<String>(); for (AppResourceIFace ap : AppContextMgr.getInstance().getResourceByMimeType(mimeType)) { Properties params = ap.getMetaDataMap(); Integer appId = ap instanceof SpAppResource ? ((SpAppResource) ap).getId() : null; if (appId != null) { params.put("spappresourceid", appId); } String tableid = params.getProperty("tableid"); //$NON-NLS-1$ if (StringUtils.isNotEmpty(tableid)) { String subReps = params.getProperty("subreports"); if (subReps != null) { String[] subRepNames = StringUtils.split(subReps, ","); for (String subRepName : subRepNames) { subReports.add(subRepName.trim()); } } String rptType = params.getProperty("reporttype"); //$NON-NLS-1$ Integer tblId = Integer.parseInt(tableid); if (excludedTableIds.indexOf(tblId) == -1 && (classTableId == null || tblId.equals(classTableId)) && (StringUtils.isEmpty(reportType) || (StringUtils.isNotEmpty(rptType) && reportType.equals(rptType)))) { params.put("name", ap.getName()); //$NON-NLS-1$ params.put("title", ap.getDescription() == null ? ap.getName() : ap.getDescription()); //$NON-NLS-1$ params.put("file", ap.getName()); //$NON-NLS-1$ params.put("mimetype", mimeType); //$NON-NLS-1$ Object param = params.get("isimport"); if (param != null && param.equals("1")) { params.put("appresource", ap); } param = params.get("hasrsdropparam"); if (param != null) { params.put(RECORDSET_PARAM, param); } String localIconName = params.getProperty("icon"); //$NON-NLS-1$ if (StringUtils.isEmpty(localIconName)) { localIconName = defaultIcon; } result.add(new TaskCommandDef(ap.getDescription(), localIconName, params)); } } } if (subReports.size() > 0) { for (int r = result.size() - 1; r >= 0; r--) { TaskCommandDef def = result.get(r); if (subReports.indexOf(def.getName()) != -1) { result.remove(r); } } } return result; }
From source file:com.fluidops.iwb.deepzoom.CXMLServlet.java
@SuppressWarnings(value = "DM_CONVERT_CASE", justification = "checked") private void renderCollection(Map<URI, Map<URI, Set<Value>>> graph, Vector<URI> predicates, HashMap<URI, Integer> facetCountMap, String collection, String collectionName, PrintStream httpOut, String q, HttpServletRequest req, int maxEntities, int maxFacets) throws FileNotFoundException, IOException { PrintStream resultCache = new PrintStream(new FileOutputStream(getCacheFile("resultCache", hash(q))), false, "UTF-8"); PrintStream out = new PrintStream(new DualOutputStream(httpOut, resultCache), false, "UTF-8"); out.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); //out.println("<?xml-stylesheet type=\"text/xsl\" href=\"/int/pivot/pivot.xsl\"?>"); out.println("<Collection Name=\"" + XML.escape(collectionName) + "\" SchemaVersion=\"1.0\""); out.println(" xmlns=\"http://schemas.microsoft.com/collection/metadata/2009\""); out.println(" xmlns:p=\"http://schemas.microsoft.com/livelabs/pivot/collection/2009\""); out.println(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""); out.println(" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">"); Dimension d = new Dimension(200, 200); Writer collectionWriter = null; try {//from w ww .j a v a 2 s . com collectionWriter = new OutputStreamWriter( new FileOutputStream(getCacheFile("collectionCache", hash(q))), "UTF-8"); } catch (IOException e) { logger.warn(e.getMessage()); } collectionWriter.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<Collection MaxLevel=\"8\" TileSize=\"256\" Format=\"jpg\" NextItemId=\"1001\" ServerFormat=\"Default\" xmlns=\"http://schemas.microsoft.com/deepzoom/2009\">\n" + "<Items>\n"); // render facet categories out.println("<FacetCategories>"); List<URI> displayedFacets = new LinkedList<URI>(); // We limit the number of displayed facets (maxPivotFacets) // We rank facets by the number of entities that have a value for the given facet // The ranking only needs to be performed if maxFacets>0 (0 disables limitation) // and the number of facets is actually greater than maxFacets if (facetCountMap != null && maxFacets > 0 && facetCountMap.size() > maxFacets) { Set<Entry<URI, Integer>> s = facetCountMap.entrySet(); for (int i = 0; i < maxFacets; i++) { int max = 0; Entry<URI, Integer> maxEntry = null; for (Entry<URI, Integer> e : s) { if (e.getValue() > max) { maxEntry = e; max = e.getValue(); } } if (maxEntry == null) break; displayedFacets.add(maxEntry.getKey()); s.remove(maxEntry); } } else displayedFacets = predicates; Vector<URI> facetNames = new Vector<URI>(); Vector<String> facetLabels = new Vector<String>(); // we may use any sort order here; currently, we sort alphabetically, // with the exception that the type facet is always on top Collections.sort(predicates, new Comparator<URI>() { public int compare(URI o1, URI o2) { if (o1.equals(RDF.TYPE)) return -1; else if (o2.equals(RDF.TYPE)) return 1; else return o1.stringValue().compareTo(o2.stringValue()); } }); for (URI predicate : predicates) { ReadDataManager dm = EndpointImpl.api().getDataManager(); if (dm.getLabel(predicate).equals("name") || facetNames.contains(predicate)) continue; // labels of names are unfortunately not unique, but must not occur as duplicates facetNames.add(predicate); if (displayedFacets.contains(predicate)) { String name = dm.getLabel(predicate); name = escape(name).trim(); // TODO: only quick fix, has to be handled properly // facet labels need to be unique, disregarding capitalization if (!facetLabels.contains(name.toLowerCase())) { facetLabels.add(name.toLowerCase()); String type; URI range = predicateTypes.get(predicate); if (range == null) range = XMLSchema.STRING; if (range.equals(XMLSchema.DATETIME) || range.equals(XMLSchema.DATE)) type = "DateTime"; else if (range.equals(XMLSchema.FLOAT) || range.equals(XMLSchema.DOUBLE) || range.equals(XMLSchema.INT) || range.equals(XMLSchema.INTEGER) || range.equals(XMLSchema.LONG)) type = "Number"; else type = "String"; //default out.println("<FacetCategory Name=\"" + XML.escape(name) + "\" Type=\"" + type + "\" p:IsFilterVisible=\"true\" p:IsMetaDataVisible=\"false\" />"); out.println("<FacetCategory Name=\"" + XML.escape(name) + ":\" Type=\"Link\" p:IsFilterVisible=\"false\" p:IsMetaDataVisible=\"true\" />"); } } } out.println( "<FacetCategory Name=\"Home\" Type=\"Link\" p:IsFilterVisible=\"false\" p:IsMetaDataVisible=\"true\" />"); out.println("</FacetCategories>"); // render items in collection String collectionID = "collection" + hash(q) + ".xml"; out.println("<Items ImgBase=\"" + collection + "/" + collectionID + "\">"); int counter = 0; Vector<String> imageVector = new Vector<String>(); // queryImageVector.put(hash(q), imageVector); ImageLoader loader = new ImageLoader(api().getRequestMapper().getInternalUrlWithoutContext(req)); for (Entry<URI, Map<URI, Set<Value>>> entry : graph.entrySet()) { Resource entity = entry.getKey(); if (counter >= maxEntities) break; Map<URI, Set<Value>> facets = entry.getValue(); // We assume that all entities are URIs. Perhaps need to re-evaluate this assumption URI uri = (URI) entity; String img = null; if (IWBCmsUtil.isUploadedFile(uri) && ImageResolver.isImage(uri.stringValue())) img = getImageURLForValue(uri); else { // verify if there is an image in the facets using image properties // given by ImageResolver (e.g. foaf:img) for (URI imageProperty : ImageResolver.getDefaultImageResolver().getImageProperties()) { Set<Value> imgForProperty = facets.get(imageProperty); if (imgForProperty != null && imgForProperty.size() > 0) { img = getImageURLForValue(imgForProperty.iterator().next()); break; // found an image } } // fallback, no image found: indicates that ID card should be generated if (img == null) img = "id:" + entity.stringValue() + ".jpg"; } String filename = ImageLoader.filename(img); if (!imageVector.contains(img)) //only need to load the image once { loader.createImageThreaded(uri, facets, img, collection); imageVector.add(img); int imgID = imageVector.indexOf(img); collectionWriter.write("<I Id=\"" + imgID + "\" N=\"" + imgID + "\" Source=\"dzimages/" + ImageLoader.subdir(filename) + "/" + ((filename.lastIndexOf(".") > -1) ? filename.substring(0, filename.lastIndexOf(".")) : filename) + ".xml\">" + "<Size Width=\"" + d.width + "\" Height=\"" + d.height + "\"/></I>"); } int imgID = imageVector.indexOf(img); ReadDataManager dm = EndpointImpl.api().getDataManager(); String label = cleanLabel(dm.getLabel(uri)); if (label.length() == 0) continue; out.println("<Item Img=\"#" + imgID + "\" Id=\"" + counter + "\" Href=\"" + EndpointImpl.api().getRequestMapper().getRequestStringFromValue(uri) + "\" Name=\"" + label + "\">"); String facetString = "";// temp string as we do not know whether there are any facet values for (Entry<URI, Set<Value>> facetEntry : facets.entrySet()) { URI predicate = facetEntry.getKey(); if (predicate.equals(Vocabulary.DBPEDIA_ONT.THUMBNAIL)) continue; String name = dm.getLabel(predicate); if (name.equals("name")) continue; Set<Value> facetValues = facetEntry.getValue(); String values = ""; String exploreValues = ""; int facetValueCounter = 0; for (Value value : facetValues) { if (value == null) continue; if (facetValueCounter++ > 1000) break; //TODO: temp hack to prevent scalability problems, improve logic label = cleanLabel(dm.getLabel(value)); if (label.equals("")) continue; String href = EndpointImpl.api().getRequestMapper().getRequestStringFromValue(value); if ((value instanceof Literal) && !Config.getConfig().getLinkLiterals()) { href = "#"; } if (label.toLowerCase().startsWith("category:")) { label = label.substring(9); } URI range = predicateTypes.get(predicate); if (range == null) values += "<String Value=\"" + label + "\"/>"; else if (range.equals(XMLSchema.FLOAT) || range.equals(XMLSchema.DOUBLE) || range.equals(XMLSchema.INT) || range.equals(XMLSchema.INTEGER) || range.equals(XMLSchema.LONG)) { try { // Need to be compliant with xsd:decimal values += "<Number Value=\"" + (new BigDecimal(Double.parseDouble(label))).toPlainString() + "\"/>"; } catch (Exception e) { logger.warn("Parsing problem with: " + label); } } else if (range.equals(XMLSchema.DATETIME) || range.equals(XMLSchema.DATE)) { Date date = null; // Loop over supported date formats for (DateFormat formatter : formatters) { try { date = (Date) formatter.parse(label); break; } // If date format is not supported.. catch (ParseException e) { logger.debug("Date format not supported: " + label + ". Using today instead."); } } if (date != null) { DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); values += "<DateTime Value=\"" + format.format(date) + "\"/>"; } } else values += "<String Value=\"" + label + "\"/>"; exploreValues += "<Link Href=\"" + href + "\" Name=\"" + label + "\"/>"; } name = escape(name).trim(); // values = values.replace("]", ""); if (values.length() > 0 && displayedFacets.contains(predicate)) facetString += "<Facet Name=\"" + XML.escape(name) + "\">" + values + "</Facet>"; if (exploreValues.length() > 0 && displayedFacets.contains(predicate)) facetString += "<Facet Name=\"" + XML.escape(name) + ":\">" + exploreValues + "</Facet>"; } /* //Query for related elements, currently not used String href = "CONSTRUCT { ?uri <http://dbpedia.org/ontology/thumbnail> ?img . ?uri ?p ?o . } WHERE { { ?uri ?relationship <"+uri.stringValue()+"> } UNION { <"+uri.stringValue()+"> ?relationship ?uri } . ?uri <http://dbpedia.org/ontology/thumbnail> ?img . ?uri ?p ?o }"; try { href=URLEncoder.encode(href, "UTF-8"); } catch (UnsupportedEncodingException e) { logger.error(e.getMessage(), e); } facetString+="<Facet Name=\"Related\"><Link Href=\"query.cxml?q="+href+"\" Name=\"Explore Related\"/></Facet>"; */ if (!facetString.isEmpty()) out.println("<Facets>" + facetString + "</Facets>"); out.println("</Item>"); counter++; } if (counter == 0) { // should show some image indicating that nothing has been found, for now we just show a text out.println("<Item Img=\"#0\" Id=\"0\" Name=\"Nothing found\">"); out.println("</Item>"); URI uri = ValueFactoryImpl.getInstance().createURI("http://www.fluidops.com/Nothing Found"); // id: indicates that ID card should be generated String img = "id:" + uri.stringValue() + ".jpg"; String filename = ImageLoader.filename(img); Map<URI, Set<Value>> facets = new HashMap<URI, Set<Value>>(); loader.createImageThreaded(uri, facets, img, collection); imageVector.add(img); int imgID = 0; collectionWriter.write("<I Id=\"" + imgID + "\" N=\"" + imgID + "\" Source=\"dzimages/" + ImageLoader.subdir(filename) + "/" + ((filename.lastIndexOf(".") > -1) ? filename.substring(0, filename.lastIndexOf(".")) : filename) + ".xml\">" + "<Size Width=\"" + d.width + "\" Height=\"" + d.height + "\"/></I>"); } try { writeImageListToFile("imageCache", hash(q), imageVector); } catch (IOException e) { logger.warn(e.getMessage(), e); } // We wait until all image loading threads have finished, but at most one minute long wait = 0; while (loader.threadCounter > 0 && wait < 60000) { try { Thread.sleep(10); wait += 10; } catch (InterruptedException e1) { logger.debug(e1.toString()); } } collectionWriter.write("</Items>\n</Collection>"); collectionWriter.close(); out.println("</Items>"); out.println("</Collection>"); out.close(); }
From source file:edu.ku.brc.specify.tasks.subpane.wb.DataImportDialog.java
/** * Parses the given import xls file according to the users selection and creates/updates the * Preview table, showing the user how the import options effect the way the data will be * imported into the spreadsheet./*from w w w .j a v a2 s . c o m*/ * * @param table - the table to display the data * @return JTable - the table to display the data */ private JTable setXLSTableData(final JTable table) { int numRows = 0; int numCols = 0; String[] headers = {}; Vector<Vector<String>> tableDataVector = new Vector<Vector<String>>(); Vector<String> rowData = new Vector<String>(); Vector<String> headerVector = new Vector<String>(); DateWrapper scrDateFormat = AppPrefsCache.getDateWrapper("ui", "formatting", "scrdateformat"); try { log.debug("setXLSTableData - file - " + configXLS.getFile().toString()); InputStream input = new FileInputStream(configXLS.getFile()); POIFSFileSystem fs = new POIFSFileSystem(input); HSSFWorkbook workBook = new HSSFWorkbook(fs); HSSFSheet sheet = workBook.getSheetAt(0); Vector<Integer> badHeads = new Vector<Integer>(); Vector<Integer> emptyCols = new Vector<Integer>(); ((ConfigureXLS) config).checkHeadsAndCols(sheet, badHeads, emptyCols); if (badHeads.size() > 0 && doesFirstRowHaveHeaders) { if (table != null) { ((ConfigureXLS) config).showBadHeadingsMsg(badHeads, emptyCols, getTitle()); } this.doesFirstRowHaveHeaders = false; try { ignoreActions = true; this.containsHeaders.setSelected(false); } finally { ignoreActions = false; } if (table != null) { return table; } } boolean firstRow = true; //quick fix to prevent ".0" at end of catalog numbers etc NumberFormat nf = NumberFormat.getInstance(); nf.setMinimumFractionDigits(0); nf.setMaximumFractionDigits(20); nf.setGroupingUsed(false); //gets rid of commas int maxCols = 0; // Iterate over each row in the sheet Iterator<?> rows = sheet.rowIterator(); while (rows.hasNext()) { numCols = 0; rowData = new Vector<String>(); HSSFRow row = (HSSFRow) rows.next(); //log.debug(row.getLastCellNum()+" "+row.getPhysicalNumberOfCells()); int maxSize = Math.max(row.getPhysicalNumberOfCells(), row.getLastCellNum()); if (maxSize > maxCols) { maxCols = maxSize; } while (numCols < maxSize) { if (emptyCols.indexOf(new Integer(numCols)) == -1) { HSSFCell cell = row.getCell(numCols); String value = null; // if cell is blank, set value to "" if (cell == null) { value = ""; } else { int type = cell.getCellType(); switch (type) { case HSSFCell.CELL_TYPE_NUMERIC: // The best I can do at this point in the app is to guess if a // cell is a date. // Handle dates carefully while using HSSF. Excel stores all // dates as numbers, internally. // The only way to distinguish a date is by the formatting of // the cell. (If you // have ever formatted a cell containing a date in Excel, you // will know what I mean.) // Therefore, for a cell containing a date, cell.getCellType() // will return // HSSFCell.CELL_TYPE_NUMERIC. However, you can use a utility // function, // HSSFDateUtil.isCellDateFormatted(cell), to check if the cell // can be a date. // This function checks the format against a few internal // formats to decide the issue, // but by its very nature it is prone to false negatives. if (HSSFDateUtil.isCellDateFormatted(cell)) { value = scrDateFormat.getSimpleDateFormat().format(cell.getDateCellValue()); //value = scrDateFormat.getSimpleDateFormat().format(cell.getDateCellValue()); } else { double numeric = cell.getNumericCellValue(); value = nf.format(numeric); } break; case HSSFCell.CELL_TYPE_STRING: value = cell.getRichStringCellValue().getString(); break; case HSSFCell.CELL_TYPE_BLANK: value = ""; break; case HSSFCell.CELL_TYPE_BOOLEAN: value = Boolean.toString(cell.getBooleanCellValue()); break; case HSSFCell.CELL_TYPE_FORMULA: value = UIRegistry.getResourceString("WB_FORMULA_IMPORT_NO_PREVIEW"); break; default: value = ""; log.error("unsuported cell type"); break; } } if (firstRow && doesFirstRowHaveHeaders) { checkUserColInfo(value, numCols); } if (isUserCol(numCols)) { rowData.add(value.toString()); } } numCols++; } if (doesFirstRowHaveHeaders && firstRow) { headerVector = rowData; headers = new String[rowData.size()]; } else if (!doesFirstRowHaveHeaders && firstRow) { //headers = createDummyHeaders(rowData.size()); tableDataVector.add(rowData); } else { tableDataVector.add(rowData); } firstRow = false; numRows++; } maxCols -= emptyCols.size(); if (!doesFirstRowHaveHeaders) { headerVector = createDummyHeadersAsVector(maxCols); headers = new String[maxCols]; } for (int i = 0; i < headerVector.size(); i++) { headers[i] = headerVector.elementAt(i); } printArray(headers); String[][] tableData = new String[tableDataVector.size()][maxCols]; for (int i = 0; i < tableDataVector.size(); i++) { Vector<String> v = tableDataVector.get(i); for (int j = 0; j < v.size(); j++) { tableData[i][j] = v.get(j).toString(); } } if (checkForErrors(headers, tableData)) { errorPanel.showDataImportStatusPanel(true); } else { errorPanel.showDataImportStatusPanel(false); } if ((doesFirstRowHaveHeaders ? numRows - 1 : numRows) > WorkbenchTask.MAX_ROWS) { hasTooManyRows = true; showTooManyRowsErrorDialog(); } else { hasTooManyRows = false; } log.debug(headers); log.debug(tableData); model = new PreviewTableModel(headers, tableData); JTable result = null; if (table == null) { result = new JTable(); result.setColumnSelectionAllowed(false); result.setRowSelectionAllowed(false); result.setCellSelectionEnabled(false); result.getTableHeader().setReorderingAllowed(false); result.setPreferredScrollableViewportSize(new Dimension(500, 100)); result.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); } else { result = table; } result.setModel(model); result.setDefaultRenderer(String.class, new BiColorTableCellRenderer(false)); model.fireTableDataChanged(); model.fireTableStructureChanged(); return result; } catch (Exception ex) { UIRegistry.displayErrorDlgLocalized(UIRegistry.getResourceString("WB_ERROR_READING_IMPORT_FILE")); if (table != null) { String[] columnNames = {}; String[][] blankData = { {} }; model = new PreviewTableModel(columnNames, blankData); table.setModel(model); table.setColumnSelectionAllowed(false); table.setRowSelectionAllowed(false); table.setCellSelectionEnabled(false); table.getTableHeader().setReorderingAllowed(false); table.setPreferredScrollableViewportSize(new Dimension(500, 100)); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table.setDefaultRenderer(String.class, new BiColorTableCellRenderer(false)); model.fireTableDataChanged(); model.fireTableStructureChanged(); return table; } //log.error("Error attempting to parse input xls file:" + ex); //ex.printStackTrace(); } return null; }
From source file:edu.ku.brc.specify.tasks.subpane.wb.wbuploader.Uploader.java
/** * @return the table to attach images to. *//* ww w .j av a 2 s . c o m*/ public UploadTable getAttachToTable() { int priority = -1; Vector<Class<?>> attachable = getAttachableTables(); UploadTable result = null; boolean isAgentOnly = true; for (UploadTable ut : uploadTables) { if (!ut.getTblClass().equals(Agent.class) || ut.getTblClass().equals(Address.class)) { isAgentOnly = false; } int newPriority = attachable.indexOf(ut.getTblClass()); if (newPriority > priority) { priority = newPriority; result = ut; } } if (result instanceof UploadTableTree) { while (((UploadTableTree) result).getChild() != null) { result = ((UploadTableTree) result).getChild(); } } if (result == null && isAgentOnly) { for (UploadTable ut : uploadTables) { if (ut.getTblClass().equals(Agent.class)) { return ut; } } } return result; }
From source file:org.apache.jasper.compiler.JspUtil.java
/** * Checks if all mandatory attributes are present and if all attributes * present have valid names. Checks attributes specified as XML-style * attributes as well as attributes specified using the jsp:attribute * standard action. //from www . j a va 2 s . co m */ public static void checkAttributes(String typeOfTag, Node n, ValidAttribute[] validAttributes, ErrorDispatcher err) throws JasperException { Attributes attrs = n.getAttributes(); Mark start = n.getStart(); boolean valid = true; // AttributesImpl.removeAttribute is broken, so we do this... int tempLength = (attrs == null) ? 0 : attrs.getLength(); Vector temp = new Vector(tempLength, 1); for (int i = 0; i < tempLength; i++) { String qName = attrs.getQName(i); if ((!qName.equals("xmlns")) && (!qName.startsWith("xmlns:"))) temp.addElement(qName); } // Add names of attributes specified using jsp:attribute Node.Nodes tagBody = n.getBody(); if (tagBody != null) { int numSubElements = tagBody.size(); for (int i = 0; i < numSubElements; i++) { Node node = tagBody.getNode(i); if (node instanceof Node.NamedAttribute) { String attrName = node.getAttributeValue("name"); temp.addElement(attrName); // Check if this value appear in the attribute of the node if (n.getAttributeValue(attrName) != null) { err.jspError(n, "jsp.error.duplicate.name.jspattribute", attrName); } } else { // Nothing can come before jsp:attribute, and only // jsp:body can come after it. break; } } } /* * First check to see if all the mandatory attributes are present. * If so only then proceed to see if the other attributes are valid * for the particular tag. */ String missingAttribute = null; for (int i = 0; i < validAttributes.length; i++) { int attrPos; if (validAttributes[i].mandatory) { attrPos = temp.indexOf(validAttributes[i].name); if (attrPos != -1) { temp.remove(attrPos); valid = true; } else { valid = false; missingAttribute = validAttributes[i].name; break; } } } // If mandatory attribute is missing then the exception is thrown if (!valid) err.jspError(start, "jsp.error.mandatory.attribute", typeOfTag, missingAttribute); // Check to see if there are any more attributes for the specified tag. int attrLeftLength = temp.size(); if (attrLeftLength == 0) return; // Now check to see if the rest of the attributes are valid too. String attribute = null; for (int j = 0; j < attrLeftLength; j++) { valid = false; attribute = (String) temp.elementAt(j); for (int i = 0; i < validAttributes.length; i++) { if (attribute.equals(validAttributes[i].name)) { valid = true; break; } } if (!valid) err.jspError(start, "jsp.error.invalid.attribute", typeOfTag, attribute); } // XXX *could* move EL-syntax validation here... (sb) }
From source file:org.apache.jmeter.util.JMeterUtils.java
/** * Sets the selection of the JComboBox to the Object 'name' from the list in * namVec./*from ww w . j a va2s .c om*/ * NOTUSED? * @param properties not used at the moment * @param combo {@link JComboBox} to work on * @param namVec List of names, which are displayed in <code>combo</code> * @param name Name, that is to be selected. It has to be in <code>namVec</code> */ @Deprecated public static void selJComboBoxItem(Properties properties, JComboBox<?> combo, Vector<?> namVec, String name) { int idx = namVec.indexOf(name); combo.setSelectedIndex(idx); // Redisplay. combo.updateUI(); }