List of usage examples for java.util Formatter toString
public String toString()
From source file:adapters.HistogramChartAdapter.java
public String toLatex(double width, double height) { double xunit, yunit; double[] save = new double[4]; if (dataset.getSeriesCollection().getSeriesCount() == 0) throw new IllegalArgumentException("Empty chart"); if (YAxis.getTwinAxisPosition() < 0) YAxis.setTwinAxisPosition(0);// w w w . ja v a 2 s .com // Calcul des parametres d'echelle et de decalage double XScale = computeXScale(XAxis.getTwinAxisPosition()); double YScale = computeYScale(YAxis.getTwinAxisPosition()); // taille d'une unite en x et en cm dans l'objet "tikzpicture" xunit = width / ((Math.max(XAxis.getAxis().getRange().getUpperBound(), XAxis.getTwinAxisPosition()) * XScale) - (Math.min(XAxis.getAxis().getRange().getLowerBound(), XAxis.getTwinAxisPosition()) * XScale)); // taille d'une unite en y et en cm dans l'objet "tikzpicture" yunit = height / ((Math.max(YAxis.getAxis().getRange().getUpperBound(), YAxis.getTwinAxisPosition()) * YScale) - (Math.min(YAxis.getAxis().getRange().getLowerBound(), YAxis.getTwinAxisPosition()) * YScale)); Formatter formatter = new Formatter(Locale.US); /*Entete du document*/ if (latexDocFlag) { formatter.format("\\documentclass[12pt]{article}%n%n"); formatter.format("\\usepackage{tikz}%n\\usetikzlibrary{plotmarks}%n\\begin{document}%n%n"); } if (chart.getTitle() != null) formatter.format("%% PGF/TikZ picture from SSJ: %s%n", chart.getTitle().getText()); else formatter.format("%% PGF/TikZ picture from SSJ %n"); formatter.format("%% XScale = %s, YScale = %s, XShift = %s, YShift = %s%n", XScale, YScale, XAxis.getTwinAxisPosition(), YAxis.getTwinAxisPosition()); formatter.format("%% Therefore, thisFileXValue = (originalSeriesXValue+XShift)*XScale%n"); formatter.format("%% and thisFileYValue = (originalSeriesYValue+YShift)*YScale%n%n"); if (chart.getTitle() != null) formatter.format("\\begin{figure}%n"); formatter.format("\\begin{center}%n"); formatter.format("\\begin{tikzpicture}[x=%scm, y=%scm]%n", xunit, yunit); formatter.format("\\footnotesize%n"); if (grid) formatter.format("\\draw[color=lightgray] (%s, %s) grid[xstep = %s, ystep=%s] (%s, %s);%n", (Math.min(XAxis.getAxis().getRange().getLowerBound(), XAxis.getTwinAxisPosition()) - XAxis.getTwinAxisPosition()) * XScale, (Math.min(YAxis.getAxis().getRange().getLowerBound(), YAxis.getTwinAxisPosition()) - YAxis.getTwinAxisPosition()) * YScale, xstepGrid * XScale, ystepGrid * YScale, (Math.max(XAxis.getAxis().getRange().getUpperBound(), XAxis.getTwinAxisPosition()) - XAxis.getTwinAxisPosition()) * XScale, (Math.max(YAxis.getAxis().getRange().getUpperBound(), YAxis.getTwinAxisPosition()) - YAxis.getTwinAxisPosition()) * YScale); setTick0Flags(); formatter.format("%s", XAxis.toLatex(XScale)); formatter.format("%s", YAxis.toLatex(YScale)); formatter.format("%s", dataset.toLatex(XScale, YScale, XAxis.getTwinAxisPosition(), YAxis.getTwinAxisPosition(), XAxis.getAxis().getLowerBound(), XAxis.getAxis().getUpperBound(), YAxis.getAxis().getLowerBound(), YAxis.getAxis().getUpperBound())); formatter.format("\\end{tikzpicture}%n"); formatter.format("\\end{center}%n"); if (chart.getTitle() != null) { formatter.format("\\caption{"); formatter.format(chart.getTitle().getText()); formatter.format("}%n\\end{figure}%n"); } if (latexDocFlag) formatter.format("\\end{document}%n"); return formatter.toString(); }
From source file:umontreal.iro.lecuyer.charts.MultipleDatasetChart.java
/** * Same as in {@link XYChart}.// w w w.j a va 2 s.com * * @param width Chart's width in centimeters. * * @param height Chart's height in centimeters. * * */ public String toLatex(double width, double height) { double xunit, yunit; double[] save = new double[4]; if (datasetList.size() == 0) throw new IllegalArgumentException("Empty chart"); //Calcul des parametres d'echelle et de decalage double XScale = computeXScale(XAxis.getTwinAxisPosition()); double YScale = computeYScale(YAxis.getTwinAxisPosition()); xunit = width / ((Math.max(XAxis.getAxis().getRange().getUpperBound(), XAxis.getTwinAxisPosition()) * XScale) - (Math.min(XAxis.getAxis().getRange().getLowerBound(), XAxis.getTwinAxisPosition()) * XScale)); //taille d'une unite en x et en cm dans l'objet "tikzpicture" yunit = height / ((Math.max(YAxis.getAxis().getRange().getUpperBound(), YAxis.getTwinAxisPosition()) * YScale) - (Math.min(YAxis.getAxis().getRange().getLowerBound(), YAxis.getTwinAxisPosition()) * YScale)); //taille d'une unite en y et en cm dans l'objet "tikzpicture" Formatter formatter = new Formatter(Locale.US); /*Entete du document*/ if (latexDocFlag) { formatter.format("\\documentclass[12pt]{article}%n%n"); formatter.format("\\usepackage{tikz}%n\\usetikzlibrary{plotmarks}%n\\begin{document}%n%n"); } if (chart.getTitle() != null) formatter.format("%% PGF/TikZ picture from SSJ : %s%n", chart.getTitle().getText()); else formatter.format("%% PGF/TikZ picture from SSJ %n"); formatter.format("%% XScale = %s, YScale = %s, XShift = %s, YShift = %s%n", XScale, YScale, XAxis.getTwinAxisPosition(), YAxis.getTwinAxisPosition()); formatter.format("%% Therefore, thisFileXValue = (originalSeriesXValue+XShift)*XScale%n"); formatter.format("%% and thisFileYValue = (originalSeriesYValue+YShift)*YScale%n%n"); if (chart.getTitle() != null) formatter.format("\\begin{figure}%n"); formatter.format("\\begin{center}%n"); formatter.format("\\begin{tikzpicture}[x=%scm, y=%scm]%n", xunit, yunit); formatter.format("\\footnotesize%n"); if (grid) formatter.format("\\draw[color=lightgray] (%s, %s) grid[xstep = %s, ystep=%s] (%s, %s);%n", (Math.min(XAxis.getAxis().getRange().getLowerBound(), XAxis.getTwinAxisPosition()) - XAxis.getTwinAxisPosition()) * XScale, (Math.min(YAxis.getAxis().getRange().getLowerBound(), YAxis.getTwinAxisPosition()) - YAxis.getTwinAxisPosition()) * YScale, xstepGrid * XScale, ystepGrid * YScale, (Math.max(XAxis.getAxis().getRange().getUpperBound(), XAxis.getTwinAxisPosition()) - XAxis.getTwinAxisPosition()) * XScale, (Math.max(YAxis.getAxis().getRange().getUpperBound(), YAxis.getTwinAxisPosition()) - YAxis.getTwinAxisPosition()) * YScale); formatter.format("%s", XAxis.toLatex(XScale)); formatter.format("%s", YAxis.toLatex(YScale)); for (int i = 0; i < datasetList.size(); i++) formatter.format("%s", datasetList.get(i).toLatex(XScale, YScale, XAxis.getTwinAxisPosition(), YAxis.getTwinAxisPosition(), XAxis.getAxis().getLowerBound(), XAxis.getAxis().getUpperBound(), YAxis.getAxis().getLowerBound(), YAxis.getAxis().getUpperBound())); formatter.format("\\end{tikzpicture}%n"); formatter.format("\\end{center}%n"); if (chart.getTitle() != null) { formatter.format("\\caption{"); formatter.format(chart.getTitle().getText()); formatter.format("}%n\\end{figure}%n"); } if (latexDocFlag) formatter.format("\\end{document}%n"); return formatter.toString(); }
From source file:fll.scheduler.TournamentSchedule.java
/** * Compute the general schedule and return it as a string */// w ww . j a v a 2s . c o m public String computeGeneralSchedule() { LocalTime minPerf = null; LocalTime maxPerf = null; // division -> date final Map<String, LocalTime> minSubjectiveTimes = new HashMap<>(); final Map<String, LocalTime> maxSubjectiveTimes = new HashMap<>(); for (final TeamScheduleInfo si : _schedule) { final String judgingStation = si.getJudgingGroup(); for (final SubjectiveTime stime : si.getSubjectiveTimes()) { final LocalTime currentMin = minSubjectiveTimes.get(judgingStation); if (null == currentMin) { minSubjectiveTimes.put(judgingStation, stime.getTime()); } else { if (stime.getTime().isBefore(currentMin)) { minSubjectiveTimes.put(judgingStation, stime.getTime()); } } final LocalTime currentMax = maxSubjectiveTimes.get(judgingStation); if (null == currentMax) { maxSubjectiveTimes.put(judgingStation, stime.getTime()); } else { if (stime.getTime().isAfter(currentMax)) { maxSubjectiveTimes.put(judgingStation, stime.getTime()); } } } for (int i = 0; i < getNumberOfRounds(); ++i) { if (null != si.getPerfTime(i)) { if (null == minPerf || si.getPerfTime(i).isBefore(minPerf)) { minPerf = si.getPerfTime(i); } if (null == maxPerf || si.getPerfTime(i).isAfter(maxPerf)) { maxPerf = si.getPerfTime(i); } } } } // print out the general schedule final Formatter output = new Formatter(); final Set<String> stations = new HashSet<String>(); stations.addAll(minSubjectiveTimes.keySet()); stations.addAll(maxSubjectiveTimes.keySet()); for (final String station : stations) { final LocalTime earliestStart = minSubjectiveTimes.get(station); final LocalTime latestStart = maxSubjectiveTimes.get(station); final Duration subjectiveDuration = Duration.ofMinutes(SolverParams.DEFAULT_SUBJECTIVE_MINUTES); final LocalTime latestEnd = latestStart.plus(subjectiveDuration); output.format( "Subjective times for judging station %s: %s - %s (assumes default subjective time of %d minutes)%n", station, formatTime(earliestStart), formatTime(latestEnd), SolverParams.DEFAULT_SUBJECTIVE_MINUTES); } if (null != minPerf && null != maxPerf) { final Duration performanceDuration = Duration.ofMinutes(SolverParams.DEFAULT_PERFORMANCE_MINUTES); final LocalTime performanceEnd = maxPerf.plus(performanceDuration); output.format("Performance times: %s - %s (assumes default performance time of %d minutes)%n", formatTime(minPerf), formatTime(performanceEnd), SolverParams.DEFAULT_PERFORMANCE_MINUTES); } return output.toString(); }
From source file:umontreal.iro.lecuyer.charts.XYLineChart.java
public String toLatex(double width, double height) { double xunit = 0, yunit = 0; double[] save = new double[4]; if (dataset.getSeriesCollection().getSeriesCount() == 0) throw new IllegalArgumentException("Empty chart"); //Calcul des parametres d'echelle et de decalage double XScale = computeXScale(XAxis.getTwinAxisPosition()); double YScale = computeYScale(YAxis.getTwinAxisPosition()); // taille d'une unite en x et en cm dans l'objet "tikzpicture" xunit = width / ((Math.max(XAxis.getAxis().getRange().getUpperBound(), XAxis.getTwinAxisPosition()) * XScale)//from w w w. ja v a 2 s .c o m - (Math.min(XAxis.getAxis().getRange().getLowerBound(), XAxis.getTwinAxisPosition()) * XScale)); // taille d'une unite en y et en cm dans l'objet "tikzpicture" yunit = height / ((Math.max(YAxis.getAxis().getRange().getUpperBound(), YAxis.getTwinAxisPosition()) * YScale) - (Math.min(YAxis.getAxis().getRange().getLowerBound(), YAxis.getTwinAxisPosition()) * YScale)); Formatter formatter = new Formatter(Locale.US); /*Entete du document*/ if (latexDocFlag) { formatter.format("\\documentclass[12pt]{article}%n%n"); formatter.format("\\usepackage{tikz}%n\\usetikzlibrary{plotmarks}%n\\begin{document}%n%n"); } if (chart.getTitle() != null) formatter.format("%% PGF/TikZ picture from SSJ: %s%n", chart.getTitle().getText()); else formatter.format("%% PGF/TikZ picture from SSJ %n"); formatter.format("%% XScale = %s, YScale = %s, XShift = %s, YShift = %s%n", XScale, YScale, XAxis.getTwinAxisPosition(), YAxis.getTwinAxisPosition()); formatter.format("%% Therefore, thisFileXValue = (originalSeriesXValue+XShift)*XScale%n"); formatter.format("%% and thisFileYValue = (originalSeriesYValue+YShift)*YScale%n%n"); if (chart.getTitle() != null) formatter.format("\\begin{figure}%n"); formatter.format("\\begin{center}%n"); formatter.format("\\begin{tikzpicture}[x=%scm, y=%scm]%n", xunit, yunit); formatter.format("\\footnotesize%n"); if (grid) formatter.format("\\draw[color=lightgray] (%s, %s) grid[xstep = %s, ystep=%s] (%s, %s);%n", (Math.min(XAxis.getAxis().getRange().getLowerBound(), XAxis.getTwinAxisPosition()) - XAxis.getTwinAxisPosition()) * XScale, (Math.min(YAxis.getAxis().getRange().getLowerBound(), YAxis.getTwinAxisPosition()) - YAxis.getTwinAxisPosition()) * YScale, xstepGrid * XScale, ystepGrid * YScale, (Math.max(XAxis.getAxis().getRange().getUpperBound(), XAxis.getTwinAxisPosition()) - XAxis.getTwinAxisPosition()) * XScale, (Math.max(YAxis.getAxis().getRange().getUpperBound(), YAxis.getTwinAxisPosition()) - YAxis.getTwinAxisPosition()) * YScale); setTick0Flags(); formatter.format("%s", XAxis.toLatex(XScale)); formatter.format("%s", YAxis.toLatex(YScale)); formatter.format("%s", dataset.toLatex(XScale, YScale, XAxis.getTwinAxisPosition(), YAxis.getTwinAxisPosition(), XAxis.getAxis().getLowerBound(), XAxis.getAxis().getUpperBound(), YAxis.getAxis().getLowerBound(), YAxis.getAxis().getUpperBound())); formatter.format("\\end{tikzpicture}%n"); formatter.format("\\end{center}%n"); if (chart.getTitle() != null) { formatter.format("\\caption{"); formatter.format(chart.getTitle().getText()); formatter.format("}%n\\end{figure}%n"); } if (latexDocFlag) formatter.format("\\end{document}%n"); return formatter.toString(); }
From source file:org.xwiki.rest.internal.resources.BaseSearchResult.java
/** * Search for keyword in the given scopes. Limit the search only to Objects. * * @param number number of results to be returned * @param start 0-based start offset/*from w ww. j a v a 2s .c o m*/ * @param orderField the field to be used to order the results * @param order "asc" or "desc" * @return the results */ protected List<SearchResult> searchObjects(String keywords, String wikiName, String space, boolean hasProgrammingRights, int number, int start, String orderField, String order, Boolean withPrettyNames) throws QueryException, IllegalArgumentException, UriBuilderException, XWikiException { XWikiContext xwikiContext = Utils.getXWikiContext(componentManager); XWiki xwikiApi = Utils.getXWikiApi(componentManager); String database = Utils.getXWikiContext(componentManager).getDatabase(); /* This try is just needed for executing the finally clause. */ try { List<SearchResult> result = new ArrayList<SearchResult>(); if (keywords == null) { return result; } Formatter f = new Formatter(); /* * If the order field is already one of the field hard coded in the base query, then do not add it to the * select clause. */ String addColumn = (orderField.equals("") || orderField.equals("fullName") || orderField.equals("name") || orderField.equals("space")) ? "" : ", doc." + orderField; if (space != null) { f.format("select distinct doc.fullName, doc.space, doc.name, obj.className, obj.number"); f.format(addColumn); f.format( " from XWikiDocument as doc, BaseObject as obj, StringProperty as sp, LargeStringProperty as lsp where doc.space = :space and obj.name=doc.fullName and sp.id.id = obj.id and lsp.id.id = obj.id and (upper(sp.value) like :keywords or upper(lsp.value) like :keywords) "); } else { f.format("select distinct doc.fullName, doc.space, doc.name, obj.className, obj.number"); f.format(addColumn); f.format( " from XWikiDocument as doc, BaseObject as obj, StringProperty as sp, LargeStringProperty as lsp where obj.name=doc.fullName and sp.id.id = obj.id and lsp.id.id = obj.id and (upper(sp.value) like :keywords or upper(lsp.value) like :keywords) "); } /* Build the order clause. */ String orderClause = null; if (StringUtils.isBlank(orderField)) { orderClause = "doc.fullName asc"; } else { /* Check if the order parameter is a valid "asc" or "desc" string, otherwise use "asc" */ if ("asc".equals(order) || "desc".equals(order)) { orderClause = String.format("doc.%s %s", orderField, order); } else { orderClause = String.format("doc.%s asc", orderField); } } /* Add some filters if the user doesn't have programming rights. */ if (hasProgrammingRights) { f.format(" order by %s", orderClause); } else { f.format( " and doc.space<>'XWiki' and doc.space<>'Admin' and doc.space<>'Panels' and doc.name<>'WebPreferences' order by %s", orderClause); } String query = f.toString(); List<Object> queryResult = null; /* This is needed because if the :space placeholder is not in the query, setting it would cause an exception */ if (space != null) { queryResult = queryManager.createQuery(query, Query.XWQL) .bindValue("keywords", String.format("%%%s%%", keywords.toUpperCase())) .bindValue("space", space).setLimit(number).execute(); } else { queryResult = queryManager.createQuery(query, Query.XWQL) .bindValue("keywords", String.format("%%%s%%", keywords.toUpperCase())).setLimit(number) .execute(); } /* Build the result. */ for (Object object : queryResult) { Object[] fields = (Object[]) object; String spaceName = (String) fields[1]; String pageName = (String) fields[2]; String className = (String) fields[3]; int objectNumber = (Integer) fields[4]; String id = Utils.getObjectId(wikiName, spaceName, pageName, className, objectNumber); String pageId = Utils.getPageId(wikiName, spaceName, pageName); String pageFullName = Utils.getPageFullName(wikiName, spaceName, pageName); /* * Check if the user has the right to see the found document. We also prevent guest users to access * object data in order to avoid leaking important information such as emails to crawlers. */ if (xwikiApi.hasAccessLevel("view", pageId) && xwikiContext.getUserReference() != null) { Document doc = xwikiApi.getDocument(pageFullName); String title = doc.getDisplayTitle(); SearchResult searchResult = objectFactory.createSearchResult(); searchResult.setType("object"); searchResult.setId(id); searchResult.setPageFullName(pageFullName); searchResult.setTitle(title); searchResult.setWiki(wikiName); searchResult.setSpace(spaceName); searchResult.setPageName(pageName); searchResult.setVersion(doc.getVersion()); searchResult.setClassName(className); searchResult.setObjectNumber(objectNumber); searchResult.setAuthor(doc.getAuthor()); Calendar calendar = Calendar.getInstance(); calendar.setTime(doc.getDate()); searchResult.setModified(calendar); if (withPrettyNames) { searchResult.setAuthorName(Utils.getAuthorName(doc.getAuthor(), componentManager)); } String pageUri = UriBuilder.fromUri(uriInfo.getBaseUri()).path(PageResource.class) .build(wikiName, spaceName, pageName).toString(); Link pageLink = new Link(); pageLink.setHref(pageUri); pageLink.setRel(Relations.PAGE); searchResult.getLinks().add(pageLink); String objectUri = UriBuilder.fromUri(uriInfo.getBaseUri()).path(ObjectResource.class) .build(wikiName, spaceName, pageName, className, objectNumber).toString(); Link objectLink = new Link(); objectLink.setHref(objectUri); objectLink.setRel(Relations.OBJECT); searchResult.getLinks().add(objectLink); result.add(searchResult); } } return result; } finally { Utils.getXWikiContext(componentManager).setDatabase(database); } }
From source file:com.zimbra.cs.util.ProxyConfOverride.java
public String formatLong(Object o) { Formatter f = new Formatter(); Long l = (Long) o;//from ww w.j ava 2 s .c om if (l % (1024 * 1024) == 0) f.format("%dm", l / (1024 * 1024)); else if (l % 1024 == 0) f.format("%dk", l / 1024); else f.format("%d", l); return f.toString(); }
From source file:com.itemanalysis.psychometrics.measurement.TestSummary.java
public String print() { StringBuilder sb = new StringBuilder(); Formatter f = new Formatter(sb); String f2 = "%.4f"; f.format("%n"); f.format("%n"); f.format("%-21s", " TEST LEVEL STATISTICS "); f.format("%n"); f.format("%-42s", "=========================================="); f.format("%n"); f.format("%-18s", "Number of Items = "); f.format("%-10d", this.numberOfItems()); f.format("%n"); f.format("%-22s", "Number of Examinees = "); f.format("%10d", stats.getN()); f.format("%n"); f.format("%-6s", "Min = "); f.format(f2, stats.getMin());/*from w ww . j av a2s . co m*/ f.format("%n"); f.format("%-6s", "Max = "); f.format(f2, stats.getMax()); f.format("%n"); f.format("%-7s", "Mean = "); f.format(f2, stats.getMean()); f.format("%n"); f.format("%-9s", "Median = "); f.format(f2, stats.getPercentile(50)); f.format("%n"); f.format("%-21s", "Standard Deviation = "); f.format(f2, stdDev.getResult()); f.format("%n"); f.format("%-22s", "Interquartile Range = "); f.format(f2, stats.getPercentile(75) - stats.getPercentile(25)); f.format("%n"); f.format("%-11s", "Skewness = "); f.format(f2, stats.getSkewness()); f.format("%n"); f.format("%-11s", "Kurtosis = "); f.format(f2, stats.getKurtosis()); f.format("%n"); f.format("%-7s", "KR21 = "); f.format(f2, this.kr21()); f.format("%n"); f.format("%-42s", "------------------------------------------"); f.format("%n"); f.format("%n"); f.format("%n"); if (reliabilitySampleSize > 0) { reliability = new ReliabilitySummary(relMatrix, variableAttributes, unbiased, deletedReliability); sb.append(reliability.toString()); if (deletedReliability) { f.format("%n"); f.format("%n"); f.format(reliability.itemDeletedString()); } } if (cutScores != null) { f.format("%n"); f.format("%n"); sb.append(this.computeDecisionConsistency().toString()); } if (showCsem) { f.format("%n"); f.format("%n"); sb.append(this.computeCSEM(reliability.value(), unbiased).print()); } //reliability of subscale defined part tests if (numberOfSubscales > 1) { reliability = new ReliabilitySummary(partRelMatrix, variableAttributes, unbiased, false); f.format("%n"); f.format("%n"); f.format("%n"); f.format("%59s", " ITEM GROUP DEFINED PART-TEST RELIABILITY"); f.format("%n"); sb.append(reliability.toString()); f.format("%-6s", "Number of part-tests = " + partRelMatrix.getNumberOfVariables()); f.format("%n"); } f.format("%n"); f.format("%n"); f.format("%n"); return f.toString(); }
From source file:com.zimbra.cs.util.ProxyConfOverride.java
@Override public void update() throws ServiceException, ProxyConfException { ArrayList<String> servers = new ArrayList<String>(); /* $(zmprov gamcs) */ List<Server> mcs = mProv.getAllServers(Provisioning.SERVICE_MEMCACHED); for (Server mc : mcs) { String serverName = mc.getAttr(Provisioning.A_zimbraServiceHostname, ""); int serverPort = mc.getIntAttr(Provisioning.A_zimbraMemcachedBindPort, 11211); try {//from ww w .j av a 2s. c o m InetAddress ip = ProxyConfUtil.getLookupTargetIPbyIPMode(serverName); Formatter f = new Formatter(); if (ip instanceof Inet4Address) { f.format("%s:%d", ip.getHostAddress(), serverPort); } else { f.format("[%s]:%d", ip.getHostAddress(), serverPort); } servers.add(f.toString()); f.close(); } catch (ProxyConfException pce) { mLog.error("Error resolving memcached host name: '" + serverName + "'", pce); } } if (servers.isEmpty()) { throw new ProxyConfException("No available memcached servers could be contacted"); } mValue = servers; }
From source file:com.zimbra.cs.util.ProxyConfOverride.java
@Override public void update() throws ServiceException, ProxyConfException { ArrayList<String> servers = new ArrayList<String>(); int numFailedHandlers = 0; String[] handlerNames = serverSource.getMultiAttr("zimbraReverseProxyAvailableLookupTargets"); if (handlerNames.length > 0) { for (String handlerName : handlerNames) { Server s = mProv.getServerByName(handlerName); if (s != null) { String sn = s.getAttr(Provisioning.A_zimbraServiceHostname, ""); int port = s.getIntAttr(Provisioning.A_zimbraExtensionBindPort, 7072); String proto = "http://"; int major = s.getIntAttr(Provisioning.A_zimbraServerVersionMajor, 0); int minor = s.getIntAttr(Provisioning.A_zimbraServerVersionMinor, 0); if ((major == 8 && minor >= 7) || (major > 8)) { proto = "https://"; }/*from ww w .ja va2s.c o m*/ boolean isTarget = s.getBooleanAttr(Provisioning.A_zimbraReverseProxyLookupTarget, false); if (isTarget) { try { InetAddress ip = ProxyConfUtil.getLookupTargetIPbyIPMode(sn); Formatter f = new Formatter(); if (ip instanceof Inet4Address) { f.format("%s%s:%d", proto, ip.getHostAddress(), port); } else { f.format("%s[%s]:%d", proto, ip.getHostAddress(), port); } servers.add(f.toString()); f.close(); mLog.debug("Route Lookup: Added server " + ip); } catch (ProxyConfException pce) { numFailedHandlers++; mLog.error("Error resolving service host name: '" + sn + "'", pce); } } } else { mLog.warn("Invalid value found in 'zimbraReverseProxyAvailableLookupTargets': " + handlerName + "\nPlease correct and run zmproxyconfgen again"); } } } else { List<Server> allServers = mProv.getAllServers(); for (Server s : allServers) { String sn = s.getAttr(Provisioning.A_zimbraServiceHostname, ""); int port = s.getIntAttr(Provisioning.A_zimbraExtensionBindPort, 7072); String proto = "http://"; int major = s.getIntAttr(Provisioning.A_zimbraServerVersionMajor, 0); int minor = s.getIntAttr(Provisioning.A_zimbraServerVersionMinor, 0); if ((major == 8 && minor >= 7) || (major > 8)) { proto = "https://"; } boolean isTarget = s.getBooleanAttr(Provisioning.A_zimbraReverseProxyLookupTarget, false); if (isTarget) { try { InetAddress ip = ProxyConfUtil.getLookupTargetIPbyIPMode(sn); Formatter f = new Formatter(); if (ip instanceof Inet4Address) { f.format("%s%s:%d", proto, ip.getHostAddress(), port); } else { f.format("%s[%s]:%d", proto, ip.getHostAddress(), port); } servers.add(f.toString()); f.close(); mLog.debug("Route Lookup: Added server " + ip); } catch (ProxyConfException pce) { numFailedHandlers++; mLog.error("Error resolving service host name: '" + sn + "'", pce); } } } } if (servers.isEmpty()) { if (numFailedHandlers > 0) { throw new ProxyConfException("No available nginx lookup handlers could be contacted"); } else { mLog.warn("No available nginx lookup handlers could be found"); } } mValue = servers; }
From source file:org.xwiki.rest.internal.resources.BaseSearchResult.java
/** * Search for keyword in the given scopes. Limit the search only to Pages. Search for keyword * * @param keywords the string that will be used in a "like" XWQL clause. * @param number number of results to be returned. * @param start 0-based start offset.//from ww w . ja v a2 s. co m * @param orderField the field to be used to order the results. * @param order "asc" or "desc" * @return the results. */ protected List<SearchResult> searchPages(List<SearchScope> searchScopes, String keywords, String wikiName, String space, boolean hasProgrammingRights, int number, int start, String orderField, String order, Boolean withPrettyNames) throws QueryException, IllegalArgumentException, UriBuilderException, XWikiException { XWiki xwikiApi = Utils.getXWikiApi(componentManager); String database = Utils.getXWikiContext(componentManager).getDatabase(); /* This try is just needed for executing the finally clause. */ try { List<SearchResult> result = new ArrayList<SearchResult>(); if (keywords == null) { return result; } Formatter f = new Formatter(); /* * If the order field is already one of the field hard coded in the base query, then do not add it to the * select clause. */ String addColumn = ""; if (!StringUtils.isBlank(orderField)) { addColumn = (orderField.equals("") || orderField.equals("fullName") || orderField.equals("name") || orderField.equals("space")) ? "" : ", doc." + orderField; } if (space != null) { f.format("select distinct doc.fullName, doc.space, doc.name, doc.language"); f.format(addColumn); f.format(" from XWikiDocument as doc where doc.space = :space and ( "); } else { f.format("select distinct doc.fullName, doc.space, doc.name, doc.language"); f.format(addColumn); f.format(" from XWikiDocument as doc where ( "); } /* Look for scopes related to pages */ int acceptedScopes = 0; for (int i = 0; i < searchScopes.size(); i++) { SearchScope scope = searchScopes.get(i); switch (scope) { case CONTENT: f.format("upper(doc.content) like :keywords "); acceptedScopes++; break; case NAME: f.format("upper(doc.fullName) like :keywords "); acceptedScopes++; break; case TITLE: f.format("upper(doc.title) like :keywords "); acceptedScopes++; break; } if (i != searchScopes.size() - 1) { f.format(" or "); } } /* If we don't find any scope related to pages then return empty results */ if (acceptedScopes == 0) { return result; } /* Build the order clause. */ String orderClause = null; if (StringUtils.isBlank(orderField)) { orderClause = "doc.fullName asc"; } else { /* Check if the order parameter is a valid "asc" or "desc" string, otherwise use "asc" */ if ("asc".equals(order) || "desc".equals(order)) { orderClause = String.format("doc.%s %s", orderField, order); } else { orderClause = String.format("doc.%s asc", orderField); } } /* Add some filters if the user doesn't have programming rights. */ if (hasProgrammingRights) { f.format(") order by %s", orderClause); } else { f.format( ") and doc.space<>'XWiki' and doc.space<>'Admin' and doc.space<>'Panels' and doc.name<>'WebPreferences' order by %s", orderClause); } String query = f.toString(); List<Object> queryResult = null; /* This is needed because if the :space placeholder is not in the query, setting it would cause an exception */ if (space != null) { queryResult = queryManager.createQuery(query, Query.XWQL) .bindValue("keywords", String.format("%%%s%%", keywords.toUpperCase())) .bindValue("space", space).setLimit(number).setOffset(start).execute(); } else { queryResult = queryManager.createQuery(query, Query.XWQL) .bindValue("keywords", String.format("%%%s%%", keywords.toUpperCase())).setLimit(number) .setOffset(start).execute(); } for (Object object : queryResult) { Object[] fields = (Object[]) object; String spaceName = (String) fields[1]; String pageName = (String) fields[2]; String language = (String) fields[3]; String pageId = Utils.getPageId(wikiName, spaceName, pageName); String pageFullName = Utils.getPageFullName(wikiName, spaceName, pageName); /* Check if the user has the right to see the found document */ if (xwikiApi.hasAccessLevel("view", pageId)) { Document doc = xwikiApi.getDocument(pageFullName); String title = doc.getDisplayTitle(); SearchResult searchResult = objectFactory.createSearchResult(); searchResult.setType("page"); searchResult.setId(pageId); searchResult.setPageFullName(pageFullName); searchResult.setTitle(title); searchResult.setWiki(wikiName); searchResult.setSpace(spaceName); searchResult.setPageName(pageName); searchResult.setVersion(doc.getVersion()); searchResult.setAuthor(doc.getAuthor()); Calendar calendar = Calendar.getInstance(); calendar.setTime(doc.getDate()); searchResult.setModified(calendar); if (withPrettyNames) { searchResult.setAuthorName(Utils.getAuthorName(doc.getAuthor(), componentManager)); } String pageUri = null; try { if (StringUtils.isBlank(language)) { pageUri = UriBuilder.fromUri(this.uriInfo.getBaseUri()).path(PageResource.class) .buildFromEncoded(URLEncoder.encode(wikiName, "UTF-8"), URLEncoder.encode(spaceName, "UTF-8"), URLEncoder.encode(pageName, "UTF-8")) .toString(); } else { searchResult.setLanguage(language); pageUri = UriBuilder.fromUri(this.uriInfo.getBaseUri()) .path(PageTranslationResource.class) .buildFromEncoded(URLEncoder.encode(wikiName, "UTF-8"), URLEncoder.encode(spaceName, "UTF-8"), URLEncoder.encode(pageName, "UTF-8"), language) .toString(); } } catch (UnsupportedEncodingException ex) { // This should never happen, UTF-8 is always valid. } Link pageLink = new Link(); pageLink.setHref(pageUri); pageLink.setRel(Relations.PAGE); searchResult.getLinks().add(pageLink); result.add(searchResult); } } return result; } finally { Utils.getXWikiContext(componentManager).setDatabase(database); } }