List of usage examples for java.util HashSet toArray
<T> T[] toArray(T[] a);
From source file:com.odoo.core.orm.OModel.java
private String[] updateProjection(String[] projection) { HashSet<String> names = new HashSet<>(); String[] allProjection = projection; if (allProjection == null) { allProjection = projection();/*from ww w . j av a2 s.c o m*/ } else { for (String col : projection) { OColumn column = getColumn(col); if (column.isFunctionalColumn() && column.canFunctionalStore()) { names.add(column.getName()); } } } names.addAll(Arrays.asList(allProjection)); names.addAll( Arrays.asList(new String[] { OColumn.ROW_ID, "id", "_write_date", "_is_dirty", "_is_active" })); return names.toArray(new String[names.size()]); }
From source file:org.sakaiproject.entitybroker.providers.MembershipEntityProvider.java
/** * Look for a batch membership operation * /* w w w. ja v a 2 s . co m*/ * @param params * @param userId * @return */ protected String[] checkForBatch(Map<String, Object> params, String userId) { HashSet<String> userIds = new HashSet<String>(); if (userId != null) { userIds.add(userId); } if (params != null) { List<String> batchUserIds = getListFromValue(params.get("userIds")); for (String batchUserId : batchUserIds) { String uid = userEntityProvider.findAndCheckUserId(batchUserId, null); if (uid != null) { userIds.add(uid); } } } if (log.isDebugEnabled()) log.debug("Received userIds=" + userIds); return userIds.toArray(new String[userIds.size()]); }
From source file:com.todoroo.astrid.actfm.sync.ActFmSyncService.java
/** * Fetch all tags//from w w w . j a v a2 s . c om * @param serverTime * @return new serverTime */ public int fetchTags(int serverTime) throws JSONException, IOException { if (!checkForToken()) return 0; JSONObject result = actFmInvoker.invoke("tag_list", "token", token, "modified_after", serverTime); JSONArray tags = result.getJSONArray("list"); HashSet<Long> remoteIds = new HashSet<Long>(tags.length()); for (int i = 0; i < tags.length(); i++) { JSONObject tagObject = tags.getJSONObject(i); actFmDataService.saveTagData(tagObject); remoteIds.add(tagObject.getLong("id")); } if (serverTime == 0) { Long[] remoteIdArray = remoteIds.toArray(new Long[remoteIds.size()]); tagDataService.deleteWhere(Criterion.not(TagData.REMOTE_ID.in(remoteIdArray))); } return result.optInt("time", 0); }
From source file:org.tellervo.desktop.bulkdataentry.command.PopulateFromODKCommand.java
public void execute(MVCEvent argEvent) { try {//from w w w .ja va 2s .c om MVC.splitOff(); // so other mvc events can execute } catch (IllegalThreadException e) { // this means that the thread that called splitOff() was not an MVC thread, and the next event's won't be blocked anyways. e.printStackTrace(); } catch (IncorrectThreadException e) { // this means that this MVC thread is not the main thread, it was already splitOff() previously e.printStackTrace(); } PopulateFromODKFileEvent event = (PopulateFromODKFileEvent) argEvent; ArrayList<ODKParser> filesProcessed = new ArrayList<ODKParser>(); ArrayList<ODKParser> filesFailed = new ArrayList<ODKParser>(); Path instanceFolder = null; // Launch the ODK wizard to collect parameters from user ODKImportWizard wizard = new ODKImportWizard(BulkImportModel.getInstance().getMainView()); if (wizard.wasCancelled()) return; if (wizard.isRemoteAccessSelected()) { // Doing remote server download of ODK files try { // Request a zip file of ODK files from the server ensuring the temp file is deleted on exit URI uri; uri = new URI( App.prefs.getPref(PrefKey.WEBSERVICE_URL, "invalid url!") + "/" + "odk/fetchInstances.php"); String file = getRemoteODKFiles(uri); if (file == null) { // Download was cancelled return; } new File(file).deleteOnExit(); // Unzip to a temporary folder, again ensuring it is deleted on exit instanceFolder = Files.createTempDirectory("odk-unzip"); instanceFolder.toFile().deleteOnExit(); log.debug("Attempting to open zip file: '" + file + "'"); ZipFile zipFile = new ZipFile(file); try { Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); File entryDestination = new File(instanceFolder.toFile(), entry.getName()); entryDestination.deleteOnExit(); if (entry.isDirectory()) { entryDestination.mkdirs(); } else { entryDestination.getParentFile().mkdirs(); InputStream in = zipFile.getInputStream(entry); OutputStream out = new FileOutputStream(entryDestination); IOUtils.copy(in, out); IOUtils.closeQuietly(in); out.close(); } } } finally { zipFile.close(); } } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { // Accessing ODK files from local folder instanceFolder = new File(wizard.getODKInstancesFolder()).toPath(); } // Check the instance folder specified exists File folder = instanceFolder.toFile(); if (!folder.exists()) { log.error("Instances folder does not exist"); return; } // Compile a hash set of all media files in the instance folder and subfolders File file = null; File[] mediaFileArr = null; if (wizard.isIncludeMediaFilesSelected()) { HashSet<File> mediaFiles = new HashSet<File>(); // Array of file extensions to consider as media files String[] mediaExtensions = { "jpg", "mpg", "snd", "mp4", "m4a" }; for (String ext : mediaExtensions) { SuffixFileFilter filter = new SuffixFileFilter("." + ext); Iterator<File> it = FileUtils.iterateFiles(folder, filter, TrueFileFilter.INSTANCE); while (it.hasNext()) { file = it.next(); mediaFiles.add(file); } } // Copy files to consolidate to a new folder mediaFileArr = mediaFiles.toArray(new File[mediaFiles.size()]); String copyToFolder = wizard.getCopyToLocation(); for (int i = 0; i < mediaFileArr.length; i++) { file = mediaFileArr[i]; File target = new File(copyToFolder + file.getName()); try { FileUtils.copyFile(file, target, true); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } mediaFileArr[i] = target; } } SampleModel smodel = event.sampleModel; ElementModel emodel = event.elementModel; ObjectModel model = event.objectModel; try { if (smodel.getTableModel().getRowCount() == 1 && smodel.getTableModel().getAllSingleRowModels().get(0) .getProperty(SingleSampleModel.TITLE) == null) { // Empty table first smodel.getTableModel().getAllSingleRowModels().clear(); } } catch (Exception ex) { log.debug("Error deleting empty rows"); } try { if (emodel.getTableModel().getRowCount() == 1 && emodel.getTableModel().getAllSingleRowModels().get(0) .getProperty(SingleElementModel.TITLE) == null) { // Empty table first emodel.getTableModel().getAllSingleRowModels().clear(); } } catch (Exception ex) { log.debug("Error deleting empty rows"); } try { if (model.getTableModel().getRowCount() == 1 && model.getTableModel().getAllSingleRowModels().get(0) .getProperty(SingleObjectModel.OBJECT_CODE) == null) { // Empty table first model.getTableModel().getAllSingleRowModels().clear(); } } catch (Exception ex) { log.debug("Error deleting empty rows"); } SuffixFileFilter fileFilter = new SuffixFileFilter(".xml"); Iterator<File> iterator = FileUtils.iterateFiles(folder, fileFilter, TrueFileFilter.INSTANCE); while (iterator.hasNext()) { file = iterator.next(); filesFound++; try { ODKParser parser = new ODKParser(file); filesProcessed.add(parser); if (!parser.isValidODKFile()) { filesFailed.add(parser); continue; } else if (parser.getFileType() == null) { filesFailed.add(parser); continue; } else if (parser.getFileType() == ODKFileType.OBJECTS) { addObjectToTableFromParser(parser, model, wizard, mediaFileArr); } else if (parser.getFileType() == ODKFileType.ELEMENTS_AND_SAMPLES) { addElementFromParser(parser, emodel, wizard, mediaFileArr); addSampleFromParser(parser, smodel, wizard, mediaFileArr); } else { filesFailed.add(parser); continue; } } catch (FileNotFoundException e) { otherErrors += "<p color=\"red\">Error loading file:</p>\n" + ODKParser.formatFileNameForReport(file); otherErrors += "<br/> - File not found<br/><br/>"; } catch (IOException e) { otherErrors += "<p color=\"red\">Error loading file:</p>\n" + ODKParser.formatFileNameForReport(file); otherErrors += "<br/> - IOException - " + e.getLocalizedMessage() + "<br/><br/>"; } catch (Exception e) { otherErrors += "<p color=\"red\">Error parsing file:</p>\n" + ODKParser.formatFileNameForReport(file); otherErrors += "<br/> - Exception - " + e.getLocalizedMessage() + "<br/><br/>"; } } // Create a CSV file of metadata if the user requested it if (wizard.isCreateCSVFileSelected()) { try { createCSVFile(filesProcessed, wizard.getCSVFilename()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // Compile logs to display to user StringBuilder log = new StringBuilder(); log.append("<html>\n"); for (ODKParser parser : filesFailed) { log.append("<p color=\"red\">Error loading file:</p>\n" + ODKParser.formatFileNameForReport(parser.getFile())); log.append("<br/> - " + parser.getParseErrorMessage() + "<br/><br/>"); } for (ODKParser parser : filesProcessed) { if (filesFailed.contains(parser)) continue; if (parser.getParseErrorMessage() == "") continue; log.append("<p color=\"orange\">Warning loading file:</p>\n" + ODKParser.formatFileNameForReport(parser.getFile())); log.append("<br/> - " + parser.getParseErrorMessage() + "<br/><br/>"); } log.append(otherErrors); log.append("</html>"); ODKParserLogViewer logDialog = new ODKParserLogViewer(BulkImportModel.getInstance().getMainView()); logDialog.setLog(log.toString()); logDialog.setFileCount(filesFound, filesLoadedSuccessfully); // Display log if there were any errors or if no files were found if (filesFound > filesLoadedSuccessfully) { logDialog.setVisible(true); } else if (filesFound == 0 && wizard.isRemoteAccessSelected()) { Alert.error(BulkImportModel.getInstance().getMainView(), "Not found", "No ODK data files were found on the server. Please ensure you've used the 'send finalized form' option in ODK Collect and try again"); return; } else if (filesFound == 0) { Alert.error(BulkImportModel.getInstance().getMainView(), "Not found", "No ODK data files were found in the specified folder. Please check and try again."); return; } else if (wizard.isIncludeMediaFilesSelected()) { Alert.message(BulkImportModel.getInstance().getMainView(), "Download Complete", "The ODK download is complete. As requested, your media files have been temporarily copied to the local folder '" + wizard.getCopyToLocation() + "'. Please remember to move them to their final location"); } }
From source file:org.compass.core.lucene.engine.store.DefaultLuceneSearchEngineStore.java
public String[] internalCalcSubIndexes(String[] subIndexes, String[] aliases, Class[] types, boolean poly) { if (aliases == null && types == null) { return calcSubIndexes(subIndexes, aliases); }/*from w w w .ja v a2 s . c o m*/ HashSet<String> aliasesSet = new HashSet<String>(); if (aliases != null) { for (String alias : aliases) { ResourceMapping resourceMapping = mapping.getRootMappingByAlias(alias); if (resourceMapping == null) { throw new IllegalArgumentException("No root mapping found for alias [" + alias + "]"); } aliasesSet.add(resourceMapping.getAlias()); if (poly) { aliasesSet.addAll(Arrays.asList(resourceMapping.getExtendingAliases())); } } } if (types != null) { for (Class type : types) { ResourceMapping resourceMapping = mapping.getRootMappingByClass(type); if (resourceMapping == null) { throw new IllegalArgumentException("No root mapping found for class [" + type + "]"); } aliasesSet.add(resourceMapping.getAlias()); if (poly) { aliasesSet.addAll(Arrays.asList(resourceMapping.getExtendingAliases())); } } } return calcSubIndexes(subIndexes, aliasesSet.toArray(new String[aliasesSet.size()])); }
From source file:fastcall.FastCallSNP.java
private void updateTaxaBamPathMap(String bamListFileS) { Table t = new Table(bamListFileS); String[] existingBam = new String[t.getRowNumber()]; for (int i = 0; i < t.getRowNumber(); i++) existingBam[i] = t.content[i][0]; Arrays.sort(existingBam);//from ww w. ja v a 2 s . c o m HashSet<String> existingTaxaSet = new HashSet(); HashMap<String, String[]> updatedTaxaBamMap = new HashMap(); ArrayList<String> pathList = new ArrayList(); int cnt = 0; for (int i = 0; i < taxaNames.length; i++) { String[] bamNames = taxaBamPathMap.get(taxaNames[i]); ArrayList<String> bamList = new ArrayList(); for (int j = 0; j < bamNames.length; j++) { int index = Arrays.binarySearch(existingBam, bamNames[j]); if (index < 0) continue; bamList.add(bamNames[j]); existingTaxaSet.add(taxaNames[i]); pathList.add(bamNames[j]); } if (bamList.isEmpty()) continue; bamNames = bamList.toArray(new String[bamList.size()]); Arrays.sort(bamNames); updatedTaxaBamMap.put(taxaNames[i], bamNames); cnt += bamNames.length; } String[] updatedTaxaNames = existingTaxaSet.toArray(new String[existingTaxaSet.size()]); Arrays.sort(updatedTaxaNames); taxaNames = updatedTaxaNames; taxaBamPathMap = updatedTaxaBamMap; this.bamPaths = pathList.toArray(new String[pathList.size()]); Arrays.sort(bamPaths); System.out.println("Actual taxa number:\t" + String.valueOf(taxaNames.length)); System.out.println("Actual bam file number:\t" + String.valueOf(cnt)); System.out.println(); }
From source file:com.todoroo.astrid.actfm.sync.ActFmSyncService.java
public int fetchUsers() throws JSONException, IOException { if (!checkForToken()) return 0; JSONObject result = actFmInvoker.invoke("user_list", "token", token); JSONArray users = result.getJSONArray("list"); HashSet<Long> ids = new HashSet<Long>(); if (users.length() > 0) Preferences.setBoolean(R.string.p_show_friends_view, true); for (int i = 0; i < users.length(); i++) { JSONObject userObject = users.getJSONObject(i); ids.add(userObject.optLong("id")); actFmDataService.saveUserData(userObject); }/*from www. j a v a 2s . c o m*/ Long[] idsArray = ids.toArray(new Long[ids.size()]); actFmDataService.userDao.deleteWhere(Criterion.not(User.REMOTE_ID.in(idsArray))); return result.optInt("time", 0); }
From source file:com.healthcit.cacure.businessdelegates.QuestionAnswerManager.java
public DuplicateResultBean hasShortNameDuplicates(List<String> collectedShortNames) { HashSet<String> uniqShortnamesSet = new HashSet<String>(collectedShortNames); HashSet<String> duplShortnamesSet = new HashSet<String>(); if (uniqShortnamesSet.size() != collectedShortNames.size()) { for (String uniqSn : uniqShortnamesSet) { collectedShortNames.remove(uniqSn); }/* w w w. j ava 2s . co m*/ duplShortnamesSet.addAll(collectedShortNames); } Set<String> exactQuestionsShortNames = qstDao.getQuestionsShortNamesLike(uniqShortnamesSet, true); duplShortnamesSet.addAll(exactQuestionsShortNames); Set<String> exactTableShortNames = teDao.getTableShortNamesLike(uniqShortnamesSet, true); duplShortnamesSet.addAll(exactTableShortNames); if (duplShortnamesSet.isEmpty()) { return new DuplicateResultBean(DuplicateResultType.OK, null); } else { return new DuplicateResultBean(DuplicateResultType.NOT_UNIQUE, duplShortnamesSet.toArray(new String[0])); } }
From source file:org.pentaho.reporting.libraries.formula.function.DefaultFunctionRegistry.java
public void initialize(final Configuration configuration) { final Iterator functionKeys = configuration.findPropertyKeys(FUNCTIONS_PREFIX); final HashSet<FunctionCategory> categories = new HashSet<FunctionCategory>(); while (functionKeys.hasNext()) { final String classKey = (String) functionKeys.next(); if (classKey.endsWith(".class") == false) { continue; }//from ww w . ja va 2 s. com final String className = configuration.getConfigProperty(classKey); if (className.length() == 0) { continue; } final Object fn = ObjectUtilities.loadAndInstantiate(className, DefaultFunctionRegistry.class, Function.class); if (fn instanceof Function == false) { continue; } final Function function = (Function) fn; final int endIndex = classKey.length() - 6; // 6 = ".class".length(); final String descrKey = classKey.substring(0, endIndex) + ".description"; final String descrClassName = configuration.getConfigProperty(descrKey); final Object descr = ObjectUtilities.loadAndInstantiate(descrClassName, DefaultFunctionRegistry.class, FunctionDescription.class); final FunctionDescription description; if (descr instanceof FunctionDescription == false) { description = new DefaultFunctionDescription(function.getCanonicalName()); } else { description = (FunctionDescription) descr; } final FunctionCategory cat = description.getCategory(); categoryFunctions.add(cat, function.getCanonicalName()); functionMetaData.put(function.getCanonicalName(), description); functions.put(function.getCanonicalName(), className); categories.add(cat); } this.categories = categories.toArray(new FunctionCategory[categories.size()]); }
From source file:org.wandora.application.gui.OccurrenceTableSingleType.java
/** Creates a new instance of OccurrenceTableSingleType */ public OccurrenceTableSingleType(Topic topic, Topic type, Options options, Wandora wandora) throws TopicMapException { this.wandora = wandora; this.topic = topic; TopicMap tm = wandora.getTopicMap(); try {/* w w w .j av a 2 s .c o m*/ Options opts = options; if (opts == null) opts = wandora.getOptions(); if (opts != null) { tableType = opts.get(VIEW_OPTIONS_KEY); if (tableType == null || tableType.length() == 0) tableType = VIEW_SCHEMA; defaultRowHeight = opts.getInt(ROW_HEIGHT_OPTIONS_KEY); } } catch (Exception e) { e.printStackTrace(); } this.type = type; HashSet<Topic> langSet = new LinkedHashSet(); if (VIEW_USED.equalsIgnoreCase(tableType) || VIEW_USED_AND_SCHEMA.equalsIgnoreCase(tableType)) { Hashtable<Topic, String> occs = null; Topic langTopic = null; occs = topic.getData(type); for (Enumeration<Topic> keys = occs.keys(); keys.hasMoreElements();) { langTopic = keys.nextElement(); langSet.add(langTopic); } } if (VIEW_SCHEMA.equalsIgnoreCase(tableType) || VIEW_USED_AND_SCHEMA.equalsIgnoreCase(tableType)) { Collection<Topic> langTopics = tm.getTopicsOfType(LANGUAGE_SI); langSet.addAll(langTopics); } langs = langSet.toArray(new Topic[langSet.size()]); data = new String[langs.length]; originalData = new String[langs.length]; colors = new Color[langs.length]; for (int j = 0; j < langs.length; j++) { if (langs[j] != null) { data[j] = topic.getData(type, langs[j]); if (data[j] == null) data[j] = ""; originalData[j] = data[j]; colors[j] = wandora.topicHilights.getOccurrenceColor(topic, type, langs[j]); } } dataModel = new DataTableModel(); sorter = new TableRowSorter(dataModel); final TableCellRenderer oldRenderer = this.getTableHeader().getDefaultRenderer(); this.getTableHeader().setPreferredSize(new Dimension(100, 23)); this.getTableHeader().setDefaultRenderer(new TableCellRenderer() { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component c = oldRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); return c; } }); this.setAutoCreateColumnsFromModel(false); TableColumn column = new TableColumn(0, 40, new TopicCellRenderer(), new TopicCellEditor()); this.addColumn(column); column = new TableColumn(1, 400, new DataCellRenderer(), new DataCellEditor()); this.addColumn(column); this.setTableHeader(this.getTableHeader()); this.setModel(dataModel); this.setRowSorter(sorter); sorter.setSortsOnUpdates(true); updateRowHeights(); popupStruct = WandoraMenuManager.getOccurrenceTableMenu(this, options); JPopupMenu popup = UIBox.makePopupMenu(popupStruct, wandora); this.setComponentPopupMenu(popup); this.addMouseListener(this); this.setColumnSelectionAllowed(false); this.setRowSelectionAllowed(false); this.setDragEnabled(true); this.setTransferHandler(new OccurrencesTableTransferHandler()); this.setDropMode(DropMode.ON); this.createDefaultTableSelectionModel(); }