List of usage examples for java.util TreeMap values
public Collection<V> values()
From source file:delfos.group.results.groupevaluationmeasures.MAE_byMemberStdDev.java
@Override public GroupEvaluationMeasureResult getMeasureResult(GroupRecommenderSystemResult groupRecommenderSystemResult, DatasetLoader<? extends Rating> originalDatasetLoader, RelevanceCriteria relevanceCriteria, DatasetLoader<? extends Rating> trainingDatasetLoader, DatasetLoader<? extends Rating> testDatasetLoader) { TreeMap<Integer, MeanIterative> maeAllMembers = new TreeMap<>(); for (GroupOfUsers groupOfUsers : groupRecommenderSystemResult.getGroupsOfUsers()) { Collection<Recommendation> groupRecommendations = groupRecommenderSystemResult .getGroupOutput(groupOfUsers).getRecommendations().getRecommendations(); if (groupRecommendations.isEmpty()) { continue; }//from ww w . j av a 2 s. co m MeanIterative maeGroup = new MeanIterative(); Map<Integer, MeanIterative> maeMembers = new TreeMap<>(); for (User member : groupOfUsers.getMembers()) { maeMembers.put(member.getId(), new MeanIterative()); } Map<Integer, Map<Integer, ? extends Rating>> groupTrueRatings = new TreeMap<>(); groupOfUsers.getIdMembers().stream().forEach((idUser) -> { try { groupTrueRatings.put(idUser, testDatasetLoader.getRatingsDataset().getUserRatingsRated(idUser)); } catch (UserNotFound ex) { ERROR_CODES.USER_NOT_FOUND.exit(ex); } }); for (Recommendation recommendation : groupRecommendations) { if (Double.isNaN(recommendation.getPreference().doubleValue())) { continue; } int idItem = recommendation.getItem().getId(); for (int idUser : groupOfUsers.getIdMembers()) { if (groupTrueRatings.get(idUser).containsKey(idItem)) { double trueRating = groupTrueRatings.get(idUser).get(idItem).getRatingValue().doubleValue(); double predicted = recommendation.getPreference().doubleValue(); double absoluteError = Math.abs(predicted - trueRating); maeGroup.addValue(absoluteError); maeMembers.get(idUser).addValue(absoluteError); } } } maeAllMembers.putAll(maeMembers); } double[] maeByMember = maeAllMembers.values().parallelStream() .mapToDouble(meanMember -> meanMember.getMean()).filter(value -> !Double.isNaN(value)).toArray(); double maeByMemberStdDev = new StandardDeviation().evaluate(maeByMember); if (maeByMember.length == 0) { return new GroupEvaluationMeasureResult(this, Double.NaN); } else { return new GroupEvaluationMeasureResult(this, maeByMemberStdDev); } }
From source file:com.ichi2.anki.DeckPicker.java
public void confirmDeckDeletion(long did) { Resources res = getResources(); if (!colIsOpen()) { return;//from w w w .ja v a2 s . c o m } if (did == 1) { showSimpleSnackbar(R.string.delete_deck_default_deck, true); dismissAllDialogFragments(); return; } // Get the number of cards contained in this deck and its subdecks TreeMap<String, Long> children = getCol().getDecks().children(did); long[] dids = new long[children.size() + 1]; dids[0] = did; int i = 1; for (Long l : children.values()) { dids[i++] = l; } String ids = Utils.ids2str(dids); int cnt = getCol().getDb() .queryScalar("select count() from cards where did in " + ids + " or odid in " + ids); // Delete empty decks without warning if (cnt == 0) { deleteDeck(did); dismissAllDialogFragments(); return; } // Otherwise we show a warning and require confirmation String msg; String deckName = "\'" + getCol().getDecks().name(did) + "\'"; boolean isDyn = getCol().getDecks().isDyn(did); if (isDyn) { msg = String.format(res.getString(R.string.delete_cram_deck_message), deckName); } else { msg = res.getQuantityString(R.plurals.delete_deck_message, cnt, deckName, cnt); } showDialogFragment(DeckPickerConfirmDeleteDeckDialog.newInstance(msg)); }
From source file:org.commoncrawl.service.crawler.CrawlLog.java
private static CrawlSegmentDetail loadCrawlSegment(String fileName) throws IOException { TreeMap<String, CrawlSegmentHost> hosts = new TreeMap<String, CrawlSegmentHost>(); URL resourceURL = CrawlEnvironment.getHadoopConfig().getResource(fileName); if (resourceURL == null) { throw new FileNotFoundException(); }// w w w . ja v a 2 s .co m InputStream stream = resourceURL.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(stream))); String line = null; do { line = reader.readLine(); if (line != null) { if (Environment.detailLogEnabled()) LOG.info(line); try { URL theURL = new URL(line); CrawlSegmentHost host = hosts.get(theURL.getHost()); if (host == null) { host = createHost(theURL.getHost()); hosts.put(theURL.getHost(), host); } CrawlSegmentURL segmentURL = createSegmentURL(theURL); host.getUrlTargets().add(segmentURL); } catch (MalformedURLException e) { LOG.error("SKIPPING Malformed URL::" + line); } } } while (line != null); CrawlSegmentDetail crawlSegmentDetail = new CrawlSegmentDetail(); int urlCount = 0; crawlSegmentDetail.setSegmentId(1); for (CrawlSegmentHost host : hosts.values()) { crawlSegmentDetail.getHosts().add(host); urlCount += host.getUrlTargets().size(); } crawlSegmentDetail.setUrlCount(urlCount); // finally, sort by host (as will be the case in a proper map reduce // produced segment ... Collections.sort(crawlSegmentDetail.getHosts()); return crawlSegmentDetail; }
From source file:org.opennms.features.vaadin.pmatrix.calculator.PmatrixDpdCalculatorRepository.java
/** * Causes the dataPointMap to be persisted to a file * @param file file definition to persist the data set to * @return true if dataPointMap persisted correctly, false if not *//*from w ww . ja va 2 s.co m*/ public boolean persist() { File currentArchiveFile = null; File tmpCurrentArchiveFile = null; Resource tmpResource = null; if (!persistHistoricData) { LOG.debug("not persisting data as persistHistoricData=false"); return false; } if (archiveFileName == null || archiveFileDirectoryLocation == null) { LOG.error("cannot save historical data to file as incorrect file location:" + " archiveFileDirectoryLocation=" + archiveFileDirectoryLocation + " archiveFileName=" + archiveFileName); return false; } // set the date on which this file was persisted datePersisted = new Date(); // used to get file name suffix SimpleDateFormat dateFormatter = new SimpleDateFormat(dateFormatString); // persist data to temporary file <archiveFileName.tmp> String tmpArchiveFileName = archiveFileName + ".tmp"; String tmpArchiveFileLocation = archiveFileDirectoryLocation + File.separator + tmpArchiveFileName; LOG.debug("historical data will be written to temporary file :" + tmpArchiveFileLocation); try { tmpResource = resourceLoader.getResource(tmpArchiveFileLocation); tmpCurrentArchiveFile = new File(tmpResource.getURL().getFile()); } catch (IOException e) { LOG.error("cannot save historical data to file at archiveFileLocation='" + tmpArchiveFileLocation + "' due to error:", e); return false; } LOG.debug( "persisting historical data to temporary file location:" + tmpCurrentArchiveFile.getAbsolutePath()); // marshal the data PrintWriter writer = null; boolean marshalledCorrectly = false; try { // create directory if doesn't exist File directory = new File(tmpCurrentArchiveFile.getParentFile().getAbsolutePath()); directory.mkdirs(); // create file if doesn't exist writer = new PrintWriter(tmpCurrentArchiveFile, "UTF-8"); writer.close(); // see http://stackoverflow.com/questions/1043109/why-cant-jaxb-find-my-jaxb-index-when-running-inside-apache-felix // need to provide bundles class loader ClassLoader cl = org.opennms.features.vaadin.pmatrix.model.DataPointDefinition.class.getClassLoader(); JAXBContext jaxbContext = JAXBContext.newInstance( "org.opennms.features.vaadin.pmatrix.model:org.opennms.features.vaadin.pmatrix.calculator", cl); //JAXBContext jaxbContext = JAXBContext.newInstance("org.opennms.features.vaadin.pmatrix.model:org.opennms.features.vaadin.pmatrix.calculator"); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); // TODO CHANGE output pretty printed jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // marshal this Data Repository jaxbMarshaller.marshal(this, tmpCurrentArchiveFile); marshalledCorrectly = true; } catch (JAXBException e) { LOG.error("problem marshalling file: ", e); } catch (Exception e) { LOG.error("problem marshalling file: ", e); } finally { if (writer != null) writer.close(); } if (marshalledCorrectly == false) return false; // marshaling succeeded so rename tmp file String archiveFileLocation = archiveFileDirectoryLocation + File.separator + archiveFileName; LOG.info("historical data will be written to:" + archiveFileLocation); Resource resource = resourceLoader.getResource(archiveFileLocation); if (resource.exists()) { String oldArchiveFileName = archiveFileName + "." + dateFormatter.format(datePersisted); String oldArchiveFileLocation = archiveFileDirectoryLocation + File.separator + oldArchiveFileName; LOG.info("previous historical file at archiveFileLocation='" + archiveFileLocation + "' exists so being renamed to " + oldArchiveFileLocation); Resource oldresource = resourceLoader.getResource(oldArchiveFileLocation); try { currentArchiveFile = new File(resource.getURL().getFile()); File oldArchiveFile = new File(oldresource.getURL().getFile()); // rename current archive file to old archive file name if (!currentArchiveFile.renameTo(oldArchiveFile)) { throw new IOException("cannot rename current archive file:" + currentArchiveFile.getAbsolutePath() + " to " + oldArchiveFile.getAbsolutePath()); } // rename temporary archive file to current archive file name if (!tmpCurrentArchiveFile.renameTo(currentArchiveFile)) { throw new IOException("cannot rename temporary current archive file:" + tmpCurrentArchiveFile.getAbsolutePath() + " to " + currentArchiveFile.getAbsolutePath()); } } catch (IOException e) { LOG.error("Problem archiving old persistance file", e); } // remove excess files try { Resource directoryResource = resourceLoader.getResource(archiveFileDirectoryLocation); File archiveFolder = new File(directoryResource.getURL().getFile()); File[] listOfFiles = archiveFolder.listFiles(); String filename; //this will sort earliest to latest date TreeMap<Date, File> sortedFiles = new TreeMap<Date, File>(); for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile()) { filename = listOfFiles[i].getName(); if ((!filename.equals(archiveFileName)) && (!filename.equals(tmpArchiveFileName)) && (filename.startsWith(archiveFileName))) { String beforeTimeString = archiveFileName + "."; String timeSuffix = filename.substring(beforeTimeString.length()); if (!"".equals(timeSuffix)) { Date fileCreatedate = null; try { fileCreatedate = dateFormatter.parse(timeSuffix); } catch (ParseException e) { LOG.debug("cant parse file name suffix to time for filename:" + filename, e); } if (fileCreatedate != null) { sortedFiles.put(fileCreatedate, listOfFiles[i]); } } } } } while (sortedFiles.size() > archiveFileMaxNumber) { File removeFile = sortedFiles.remove(sortedFiles.firstKey()); LOG.debug("deleting archive file:'" + removeFile.getName() + "' so that number of archive files <=" + archiveFileMaxNumber); removeFile.delete(); } for (File archivedFile : sortedFiles.values()) { LOG.debug("not deleting archive file:'" + archivedFile.getName() + "' so that number of archive files <=" + archiveFileMaxNumber); } return true; } catch (IOException e) { LOG.error("Problem removing old persistance files", e); } } else { // if resource doesn't exist just rename the new tmp file to the archive file name try { currentArchiveFile = new File(resource.getURL().getFile()); // rename temporary archive file to current archive file name if (!tmpCurrentArchiveFile.renameTo(currentArchiveFile)) { throw new IOException("cannot rename temporary current archive file:" + tmpCurrentArchiveFile.getAbsolutePath() + " to " + currentArchiveFile.getAbsolutePath()); } return true; } catch (IOException e) { LOG.error("cannot rename temporary current archive ", e); } } return false; }
From source file:com.jtstand.swing.StatsPanel.java
public JFreeChart getChartValues(Iterator<TestStepInstance> values) { if (values == null || !values.hasNext()) { return null; }// w ww. j av a 2s.c om XYSeriesCollection dataset = new XYSeriesCollection(); int count = 0; TreeMap<String, XYSeries> map = new TreeMap<String, XYSeries>(); while (values.hasNext()) { TestStepInstance step = values.next(); Number num = getNumber(step); if (num != null) { String groupName = getGroupName(step); XYSeries pop = map.get(groupName); if (pop == null) { pop = new XYSeries(groupName); map.put(groupName, pop); } pop.add(++count, num.doubleValue()); } } for (Iterator<XYSeries> it = map.values().iterator(); it.hasNext();) { dataset.addSeries(it.next()); } // NumberAxis xAxis = new NumberAxis("#"); NumberAxis xAxis = new NumberAxis(); xAxis.setAutoRangeIncludesZero(false); NumberAxis yAxis = new NumberAxis(getValueString()); yAxis.setAutoRangeIncludesZero(false); XYLineAndShapeRenderer renderer6 = new XYLineAndShapeRenderer(); XYPlot plot = new XYPlot(dataset, xAxis, yAxis, renderer6); plot.setOrientation(PlotOrientation.VERTICAL); plot.setRangeCrosshairVisible(true); plot.setDomainCrosshairVisible(true); renderer6.setBaseToolTipGenerator(new StandardXYToolTipGenerator()); renderer6.setBaseSeriesVisibleInLegend(false); // StandardXYItemLabelGenerator itemlabels=new StandardXYItemLabelGenerator(); // renderer.setBaseItemLabelGenerator(itemlabels); // renderer.setBaseItemLabelsVisible(true); JFreeChart chart = new JFreeChart(null, JFreeChart.DEFAULT_TITLE_FONT, plot, isGrouping()); //chart.setTitle(title); placeLimitMarkers(plot, true); /* coloring */ if (isCategorization()) { // TreeMap<String, Color> cmap = new TreeMap<String, Color>(); int i = 0; for (Iterator<String> it = catstats.keySet().iterator(); it.hasNext(); i++) { String groupName = it.next(); Color c = ChartCategories.getColor(i); for (int j = 0; j < dataset.getSeriesCount(); j++) { XYSeries s = dataset.getSeries(j); if (s.getKey().equals(groupName)) { renderer6.setSeriesPaint(j, c); } } } } else { renderer6.setSeriesPaint(0, ChartCategories.getColor(0)); } chart.setTextAntiAlias(false); return chart; }
From source file:org.jahia.admin.sites.ManageSites.java
private void prepareMultipleImport(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException, ServletException { FileUpload fileUpload = ((ParamBean) jParams).getFileUpload(); if (fileUpload != null) { Set<String> filesName = fileUpload.getFileNames(); Iterator<String> iterator = filesName.iterator(); if (iterator.hasNext()) { String n = iterator.next(); File f = fileUpload.getFile(n); prepareFileImports(f, fileUpload.getFileSystemName(n), request); }//from w w w . jav a 2 s .c om } String importPath = jParams.getParameter("importpath"); if (StringUtils.isNotBlank(importPath)) { File f = new File(importPath); if (f.exists()) { prepareFileImports(f, f.getName(), request); } } if (jParams.getSessionState().getAttribute("importsInfos") != null) { if (!((List<?>) jParams.getSessionState().getAttribute("importsInfos")).isEmpty()) { try { TreeMap<String, JCRNodeWrapper> orderedTemplateSets = getTemplatesSets(); request.setAttribute("tmplSets", new ArrayList<JCRNodeWrapper>(orderedTemplateSets.values())); } catch (RepositoryException e) { logger.error("Error when getting templates", e); } JahiaAdministration.doRedirect(request, response, session, JSP_PATH + "import_choose.jsp"); return; } else { request.setAttribute("warningMsg", getMessage("org.jahia.admin.site.ManageSites.multipleimport.noValidSite")); } } else { final String msg = fileUpload.getFileNames().size() == 0 && StringUtils.isBlank(importPath) ? "org.jahia.admin.site.ManageSites.multipleimport.noFile" : "org.jahia.admin.site.ManageSites.multipleimport.noValidSite"; request.setAttribute("warningMsg", getMessage(msg)); } displayList(request, response, session); }
From source file:com.jefftharris.passwdsafe.NotificationMgr.java
/** Update the notification expirations for a password file */ private void doUpdatePasswdFileData(long uriId, PasswdFileData fileData, SQLiteDatabase db) throws SQLException { PasswdSafeUtil.dbginfo(TAG, "Update %s, id: %d", fileData.getUri(), uriId); TreeMap<ExpiryEntry, Long> entries = new TreeMap<>(); Cursor cursor = db.query(DB_TABLE_EXPIRYS, new String[] { DB_COL_EXPIRYS_ID, DB_COL_EXPIRYS_UUID, DB_COL_EXPIRYS_TITLE, DB_COL_EXPIRYS_GROUP, DB_COL_EXPIRYS_EXPIRE }, DB_MATCH_EXPIRYS_URI, new String[] { Long.toString(uriId) }, null, null, null); try {// ww w. j a va2s. c om while (cursor.moveToNext()) { ExpiryEntry entry = new ExpiryEntry(cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getLong(4)); entries.put(entry, cursor.getLong(0)); } } finally { cursor.close(); } boolean dbchanged = false; ContentValues values = null; for (PasswdRecord rec : fileData.getPasswdRecords()) { PasswdExpiration expiry = rec.getPasswdExpiry(); if (expiry == null) { continue; } PwsRecord pwsrec = rec.getRecord(); ExpiryEntry entry = new ExpiryEntry(rec.getUUID(), fileData.getTitle(pwsrec), fileData.getGroup(pwsrec), expiry.itsExpiration.getTime()); if (entries.remove(entry) == null) { if (values == null) { values = new ContentValues(); values.put(DB_COL_EXPIRYS_URI, uriId); } values.put(DB_COL_EXPIRYS_UUID, entry.itsUuid); values.put(DB_COL_EXPIRYS_TITLE, entry.itsTitle); values.put(DB_COL_EXPIRYS_GROUP, entry.itsGroup); values.put(DB_COL_EXPIRYS_EXPIRE, entry.itsExpiry); db.insertOrThrow(DB_TABLE_EXPIRYS, null, values); dbchanged = true; } } for (Long rmId : entries.values()) { db.delete(DB_TABLE_EXPIRYS, DB_MATCH_EXPIRYS_ID, new String[] { rmId.toString() }); dbchanged = true; } if (dbchanged) { loadEntries(db); } }
From source file:org.jahia.admin.sites.ManageSites.java
private void processFileImport(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException, ServletException { @SuppressWarnings("unchecked") List<Map<Object, Object>> importsInfos = (List<Map<Object, Object>>) session.getAttribute("importsInfos"); Map<Object, Object> siteKeyMapping = new HashMap<Object, Object>(); boolean stillBad = false; JahiaSitesService jahiaSitesService = ServicesRegistry.getInstance().getJahiaSitesService(); for (Map<Object, Object> infos : importsInfos) { File file = (File) infos.get("importFile"); infos.put("sitekey", StringUtils.left(request.getParameter(file.getName() + "siteKey") == null ? null : request.getParameter(file.getName() + "siteKey").trim(), 50)); infos.put("oldsitekey", request.getParameter(file.getName() + "oldSiteKey") == null ? null : request.getParameter(file.getName() + "oldSiteKey").trim()); if (infos.get("sitekey") != null && !infos.get("sitekey").equals(infos.get("oldsitekey"))) { siteKeyMapping.put(infos.get("oldsitekey"), infos.get("sitekey")); }//from ww w .j av a 2s . c o m infos.put("siteservername", StringUtils.left(request.getParameter(file.getName() + "siteServerName") == null ? null : request.getParameter(file.getName() + "siteServerName").trim(), 200)); infos.put("sitetitle", StringUtils.left(request.getParameter(file.getName() + "siteTitle") == null ? null : request.getParameter(file.getName() + "siteTitle").trim(), 100)); infos.put("selected", request.getParameter(file.getName() + "selected")); infos.put("templates", request.getParameter(file.getName() + "templates")); infos.put("legacyMapping", request.getParameter(file.getName() + "legacyMapping")); infos.put("legacyDefinitions", request.getParameter(file.getName() + "legacyDefinitions")); if (request.getParameter(file.getName() + "selected") != null) { try { if (NON_SITE_IMPORTS.contains(infos.get("importFileName"))) { } else { infos.put("siteTitleInvalid", StringUtils.isEmpty((String) infos.get("sitetitle"))); String siteKey = (String) infos.get("sitekey"); boolean valid = isSiteKeyValid(siteKey); infos.put("siteKeyInvalid", !valid); infos.put("siteKeyExists", valid && jahiaSitesService.getSiteByKey(siteKey) != null); String serverName = (String) infos.get("siteservername"); valid = isServerNameValid(serverName); infos.put("siteServerNameInvalid", !valid); infos.put("siteServerNameExists", valid && !Url.isLocalhost(serverName) && jahiaSitesService.getSite(serverName) != null); stillBad = (Boolean) infos.get("siteKeyInvalid") || (Boolean) infos.get("siteKeyExists") || (Boolean) infos.get("siteServerNameInvalid") || (Boolean) infos.get("siteServerNameExists"); } } catch (JahiaException e) { logger.error("Error while processing file import", e); } } else { infos.put("siteKeyInvalid", Boolean.FALSE); infos.put("siteKeyExists", Boolean.FALSE); infos.put("siteServerNameInvalid", Boolean.FALSE); infos.put("siteServerNameExists", Boolean.FALSE); } } if (stillBad) { try { TreeMap<String, JCRNodeWrapper> orderedTemplateSets = getTemplatesSets(); request.setAttribute("tmplSets", new ArrayList<JCRNodeWrapper>(orderedTemplateSets.values())); } catch (RepositoryException e) { logger.error(e.getMessage(), e); } JahiaAdministration.doRedirect(request, response, session, JSP_PATH + "import_choose.jsp"); } else { boolean doImportServerPermissions = false; for (Map<Object, Object> infos : importsInfos) { File file = (File) infos.get("importFile"); if (request.getParameter(file.getName() + "selected") != null && infos.get("importFileName").equals("serverPermissions.xml")) { doImportServerPermissions = true; break; } } request.setAttribute("doImportServerPermissions", Boolean.valueOf(doImportServerPermissions)); for (Map<Object, Object> infos : importsInfos) { File file = (File) infos.get("importFile"); if (request.getParameter(file.getName() + "selected") != null && infos.get("importFileName").equals("users.xml")) { try { ImportExportBaseService.getInstance().importUsers(file); } finally { file.delete(); } break; } } try { for (Map<Object, Object> infos : importsInfos) { File file = (File) infos.get("importFile"); if (request.getParameter(file.getName() + "selected") != null) { if (infos.get("type").equals("files")) { try { JahiaSite system = ServicesRegistry.getInstance().getJahiaSitesService() .getSiteByKey(JahiaSitesBaseService.SYSTEM_SITE_KEY); Map<String, String> pathMapping = JCRSessionFactory.getInstance() .getCurrentUserSession().getPathMapping(); pathMapping.put("/shared/files/", "/sites/" + system.getSiteKey() + "/files/"); pathMapping.put("/shared/mashups/", "/sites/" + system.getSiteKey() + "/portlets/"); ImportExportBaseService.getInstance().importSiteZip(file, system, infos); } catch (Exception e) { logger.error("Error when getting templates", e); } } else if (infos.get("type").equals("xml") && (infos.get("importFileName").equals("serverPermissions.xml") || infos.get("importFileName").equals("users.xml"))) { } else if (infos.get("type").equals("site")) { // site import String tpl = (String) infos.get("templates"); if ("".equals(tpl)) { tpl = null; } Object legacyImport = infos.get("legacyImport"); String legacyImportFilePath = null; String legacyDefinitionsFilePath = null; if (legacyImport != null && (Boolean) legacyImport) { legacyImportFilePath = (String) infos.get("legacyMapping"); if (legacyImportFilePath != null && "".equals(legacyImportFilePath.trim())) { legacyImportFilePath = null; } legacyDefinitionsFilePath = (String) infos.get("legacyDefinitions"); if (legacyDefinitionsFilePath != null && "".equals(legacyDefinitionsFilePath.trim())) { legacyDefinitionsFilePath = null; } } Locale defaultLocale = determineDefaultLocale(jParams, infos); try { JahiaSite site = jahiaSitesService.addSite(jParams.getUser(), (String) infos.get("sitetitle"), (String) infos.get("siteservername"), (String) infos.get("sitekey"), "", defaultLocale, tpl, null, "fileImport", file, (String) infos.get("importFileName"), false, false, (String) infos.get("originatingJahiaRelease"), legacyImportFilePath, legacyDefinitionsFilePath); session.setAttribute(ProcessingContext.SESSION_SITE, site); jParams.setSite(site); jParams.setSiteID(site.getID()); jParams.setSiteKey(site.getSiteKey()); jParams.setCurrentLocale(defaultLocale); } catch (Exception e) { logger.error("Cannot create site " + infos.get("sitetitle"), e); } } } } } finally { for (Map<Object, Object> infos : importsInfos) { FileUtils.deleteQuietly((File) infos.get("importFile")); } } CompositeSpellChecker.updateSpellCheckerIndex(); redirectAfterAdd(request, response, session); } }
From source file:io.vitess.jdbc.VitessMySQLDatabaseMetadata.java
@SuppressWarnings("StringBufferReplaceableByString") public ResultSet getPrimaryKeys(String catalog, String schema, String table) throws SQLException { if (null == table) { throw new SQLException("Table Name Cannot be Null"); }/*from w ww. ja v a 2 s . co m*/ ResultSet resultSet = null; VitessStatement vitessStatement = new VitessStatement(this.connection); ArrayList<ArrayList<String>> sortedData = new ArrayList<>(); try { resultSet = vitessStatement.executeQuery("SHOW KEYS FROM " + this.quotedId + table + this.quotedId + " " + "FROM " + this.quotedId + catalog + this.quotedId); TreeMap<String, ArrayList<String>> sortMap = new TreeMap<>(); while (resultSet.next()) { String keyType = resultSet.getString("Key_name"); ArrayList<String> row = new ArrayList<>(); if (null != keyType) { if (keyType.equalsIgnoreCase("PRIMARY") || keyType.equalsIgnoreCase("PRI")) { row.add(0, (catalog == null) ? "" : catalog); row.add(1, null); row.add(2, table); String columnName = resultSet.getString("Column_name"); row.add(3, columnName); row.add(4, resultSet.getString("Seq_in_index")); row.add(5, keyType); sortMap.put(columnName, row); } } } // Now pull out in column name sorted order for (ArrayList<String> row : sortMap.values()) { sortedData.add(row); } } finally { if (null != resultSet) { resultSet.close(); } vitessStatement.close(); } String[] columnNames = new String[] { "TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", "COLUMN_NAME", "KEY_SEQ", "PK_NAME" }; Query.Type[] columnType = new Query.Type[] { Query.Type.CHAR, Query.Type.CHAR, Query.Type.CHAR, Query.Type.CHAR, Query.Type.INT16, Query.Type.CHAR }; return new VitessResultSet(columnNames, columnType, sortedData, this.connection); }