List of usage examples for java.io StringWriter getBuffer
public StringBuffer getBuffer()
From source file:org.apache.geronimo.console.databasemanager.wizard.DatabasePoolPortlet.java
public void processAction(ActionRequest actionRequest, ActionResponse actionResponse) throws PortletException, IOException { String mode = actionRequest.getParameter(MODE_KEY); if (mode.equals(IMPORT_UPLOAD_MODE)) { processImportUpload(actionRequest, actionResponse); actionResponse.setRenderParameter(MODE_KEY, IMPORT_STATUS_MODE); return;/* ww w . j a va 2 s.c om*/ } PoolData data = new PoolData(); data.load(actionRequest); if (mode.equals("process-" + SELECT_RDBMS_MODE)) { DatabaseDriver info = getDatabaseInfo(actionRequest, data); if (info != null) { data.rarPath = info.getRAR().toString(); if (info.isSpecific()) { data.adapterDisplayName = "Unknown"; // will pick these up when we process the RA type in the render request data.adapterDescription = "Unknown"; actionResponse.setRenderParameter(MODE_KEY, EDIT_MODE); } else { data.driverClass = info.getDriverClassName(); data.urlPrototype = info.getURLPrototype(); actionResponse.setRenderParameter(MODE_KEY, BASIC_PARAMS_MODE); } } else { actionResponse.setRenderParameter(MODE_KEY, SELECT_RDBMS_MODE); } } else if (mode.equals("process-" + DOWNLOAD_MODE)) { String name = actionRequest.getParameter("driverName"); DriverDownloader.DriverInfo[] drivers = getDriverInfo(actionRequest); DriverDownloader.DriverInfo found = null; for (DriverDownloader.DriverInfo driver : drivers) { if (driver.getName().equals(name)) { found = driver; break; } } if (found != null) { data.jars = new String[] { found.getRepositoryURI() }; try { PluginInstallerGBean installer = KernelRegistry.getSingleKernel() .getGBean(PluginInstallerGBean.class); //WriteableRepository repo = PortletManager.getCurrentServer(actionRequest).getWritableRepositories()[0]; final PortletSession session = actionRequest.getPortletSession(); ProgressInfo progressInfo = new ProgressInfo(); progressInfo.setMainMessage("Downloading " + found.getName()); session.setAttribute(ProgressInfo.PROGRESS_INFO_KEY, progressInfo, PortletSession.APPLICATION_SCOPE); // Start the download monitoring new Thread(new Downloader(found, progressInfo, installer)).start(); actionResponse.setRenderParameter(MODE_KEY, DOWNLOAD_STATUS_MODE); } catch (GBeanNotFoundException e) { throw new PortletException(e); } catch (InternalKernelException e) { throw new PortletException(e); } catch (IllegalStateException e) { throw new PortletException(e); } } else { actionResponse.setRenderParameter(MODE_KEY, DOWNLOAD_MODE); } } else if (mode.equals("process-" + DOWNLOAD_STATUS_MODE)) { if (data.getDbtype() == null || data.getDbtype().equals("Other")) { actionResponse.setRenderParameter(MODE_KEY, BASIC_PARAMS_MODE); } else { actionResponse.setRenderParameter(MODE_KEY, EDIT_MODE); } } else if (mode.equals("process-" + BASIC_PARAMS_MODE)) { DatabaseDriver info; info = getDatabaseInfo(actionRequest, data); if (info != null) { data.url = populateURL(info.getURLPrototype(), info.getURLParameters(), data.getUrlProperties()); } if (attemptDriverLoad(actionRequest, data) != null) { actionResponse.setRenderParameter(MODE_KEY, CONFIRM_URL_MODE); } else { actionResponse.setRenderParameter("driverError", "Unable to load driver " + data.driverClass); actionResponse.setRenderParameter(MODE_KEY, BASIC_PARAMS_MODE); } } else if (mode.equals("process-" + CONFIRM_URL_MODE)) { String test = actionRequest.getParameter("test"); if (test == null || test.equals("true")) { try { String targetDBInfo = attemptConnect(actionRequest, data); actionResponse.setRenderParameter("targetDBInfo", targetDBInfo); actionResponse.setRenderParameter("connected", "true"); } catch (Exception e) { StringWriter writer = new StringWriter(); PrintWriter temp = new PrintWriter(writer); e.printStackTrace(temp); temp.flush(); temp.close(); addErrorMessage(actionRequest, getLocalizedString(actionRequest, "dbwizard.testConnection.connectionError"), writer.getBuffer().toString()); actionResponse.setRenderParameter("connected", "false"); } actionResponse.setRenderParameter(MODE_KEY, TEST_CONNECTION_MODE); } else { save(actionRequest, actionResponse, data, false); } } else if (mode.equals(SAVE_MODE)) { save(actionRequest, actionResponse, data, false); } else if (mode.equals(SHOW_PLAN_MODE)) { String plan = save(actionRequest, actionResponse, data, true); actionRequest.getPortletSession(true).setAttribute("deploymentPlan", plan); actionResponse.setRenderParameter(MODE_KEY, SHOW_PLAN_MODE); } else if (mode.equals(EDIT_EXISTING_MODE)) { final String name = actionRequest.getParameter("adapterAbstractName"); loadConnectionFactory(actionRequest, name, data.getAbstractName(), data); actionResponse.setRenderParameter("adapterAbstractName", name); actionResponse.setRenderParameter(MODE_KEY, EDIT_MODE); } else if (mode.equals(SELECT_RDBMS_MODE)) { if (data.getAdapterDisplayName() == null) { // Set a default for a new pool data.adapterDisplayName = "TranQL Generic JDBC Resource Adapter"; } actionResponse.setRenderParameter(MODE_KEY, mode); } else if (mode.equals(WEBLOGIC_IMPORT_MODE)) { String domainDir = actionRequest.getParameter("weblogicDomainDir"); String libDir = actionRequest.getParameter("weblogicLibDir"); try { DatabaseConversionStatus status = WebLogic81DatabaseConverter.convert(libDir, domainDir); actionRequest.getPortletSession(true).setAttribute("ImportStatus", new ImportStatus(status)); actionResponse.setRenderParameter(MODE_KEY, IMPORT_STATUS_MODE); } catch (Exception e) { log.error("Unable to import", e); actionResponse.setRenderParameter("from", actionRequest.getParameter("from")); actionResponse.setRenderParameter(MODE_KEY, IMPORT_START_MODE); } } else if (mode.equals(IMPORT_START_MODE)) { actionResponse.setRenderParameter("from", actionRequest.getParameter("from")); actionResponse.setRenderParameter(MODE_KEY, mode); } else if (mode.equals(IMPORT_EDIT_MODE)) { ImportStatus status = getImportStatus(actionRequest); int index = Integer.parseInt(actionRequest.getParameter("importIndex")); status.setCurrentPoolIndex(index); loadImportedData(actionRequest, data, status.getCurrentPool()); actionResponse.setRenderParameter(MODE_KEY, EDIT_MODE); } else if (mode.equals(IMPORT_COMPLETE_MODE)) { ImportStatus status = getImportStatus(actionRequest); log.warn("Import Results:"); //todo: create a screen for this log.warn(" " + status.getSkippedCount() + " ignored"); log.warn(" " + status.getStartedCount() + " reviewed but not deployed"); log.warn(" " + status.getPendingCount() + " not reviewed"); log.warn(" " + status.getFinishedCount() + " deployed"); actionRequest.getPortletSession().removeAttribute("ImportStatus"); } else if (mode.equals(DELETE_MODE)) { String name = actionRequest.getParameter("adapterAbstractName"); loadConnectionFactory(actionRequest, name, data.getAbstractName(), data); delete(actionRequest, actionResponse, data); } else { actionResponse.setRenderParameter(MODE_KEY, mode); } data.store(actionResponse); }
From source file:com.netspective.sparx.navigate.NavigationPage.java
/** * Main method for handling the logic and content of the page. Generally, a navigation page is broken into * several sections: header, metadata, body, and footer. If there are no forwards/redirects configured, the page * sections are handled by calling the following methods: <code>handlePageMetaData()</code>, <code>handlePageHeader()</code>, * <code>handlePageBody()</code>, and <code>handlePageFooter()</code> methods. * * @param writer Writer object to write the page output to * @param nc current navigation context *///ww w . j a v a 2 s.com public void handlePage(Writer writer, NavigationContext nc) throws ServletException, IOException { Flags flags = (Flags) nc.getActiveState().getFlags(); enterPage(nc); if (getBodyType().getValueIndex() == NavigationPageBodyType.FORWARD) { // if we're forwarding to another resource we don't want to put anything into the response otherwise // there will be an illegal state exception -- so, we don't create headers, footers, etc because that's // the user's responsibility in the forwarded resource. String forwardUrl = getForward().getTextValue(nc); ServletRequest req = nc.getRequest(); RequestDispatcher rd = req.getRequestDispatcher(forwardUrl); req.setAttribute(REQATTRNAME_NAVIGATION_CONTEXT, nc); rd.forward(req, nc.getResponse()); req.removeAttribute(REQATTRNAME_NAVIGATION_CONTEXT); } else if (bodyAffectsNavigationContext(nc)) { // render the body first and let it modify the navigation context StringWriter body = new StringWriter(); boolean hasError = false; try { handlePageBody(body, nc); } catch (Exception e) { getLog().error("Error occurred while handling the page.", e); if (!findErrorPage(nc, e)) nc.setErrorPageException(getOwner().getDefaultErrorPage(), e, e.getClass()); nc.getErrorPage().handlePageBody(writer, nc); hasError = true; } if (!hasError && !nc.isRedirected()) { if (flags.flagIsSet(Flags.HANDLE_META_DATA)) handlePageMetaData(writer, nc); if (flags.flagIsSet(Flags.HANDLE_HEADER)) handlePageHeader(writer, nc); writer.write(body.getBuffer().toString()); if (flags.flagIsSet(Flags.HANDLE_FOOTER)) handlePageFooter(writer, nc); } // try and do an early GC if possible body = null; } else { if (flags.flagIsSet(Flags.HANDLE_META_DATA)) handlePageMetaData(writer, nc); if (flags.flagIsSet(Flags.HANDLE_HEADER)) handlePageHeader(writer, nc); try { handlePageBody(writer, nc); } catch (Exception e) { getLog().error("Error occurred while handling the page.", e); if (!findErrorPage(nc, e)) nc.setErrorPageException(getOwner().getDefaultErrorPage(), e, e.getClass()); nc.getErrorPage().handlePageBody(writer, nc); } if (flags.flagIsSet(Flags.HANDLE_FOOTER)) handlePageFooter(writer, nc); } exitPage(nc); }
From source file:org.apache.axis.message.MessageElement.java
/** * get the message element as a string./* w w w. ja va2 s .co m*/ * This is not a cheap operation, as we have to serialise the * entire message element to the current context, then * convert it to a string. * Nor is it cached; repeated calls repeat the operation. * @return an XML fragment in a string. * @throws Exception if anything went wrong */ public String getAsString() throws Exception { SerializationContext serializeContext = null; StringWriter writer = new StringWriter(); MessageContext msgContext; if (context != null) { msgContext = context.getMessageContext(); } else { msgContext = MessageContext.getCurrentContext(); } serializeContext = new SerializationContext(writer, msgContext); serializeContext.setSendDecl(false); setDirty(false); output(serializeContext); writer.close(); return writer.getBuffer().toString(); }
From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.latex2html.PandocLatexToHtmlConverter.java
@Override public Document convert(File tex, String title) { logger.debug("Start convert() with file " + tex.toPath().toAbsolutePath().toString() + ", title: " + title); CommandLine cmdLine;//from www .java 2 s . co m if (execPath != null) { // Run the configured pandoc executable logger.info("Pandoc will be run from: " + execPath.toString()); cmdLine = new CommandLine(execPath.toFile()); } else { // Run in system PATH environment logger.info("Pandoc will be run within the PATH variable."); cmdLine = new CommandLine("pandoc"); } cmdLine.addArgument("--from=latex"); cmdLine.addArgument("--to=html5"); cmdLine.addArgument("--asciimathml"); // With this option, pandoc does not render latex formulas cmdLine.addArgument("${file}"); HashMap<String, Path> map = new HashMap<String, Path>(); map.put("file", Paths.get(tex.toURI())); cmdLine.setSubstitutionMap(map); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000); // max execution time 1 minute Executor executor = new DefaultExecutor(); executor.setExitValue(1); executor.setWatchdog(watchdog); StringWriter writer = new StringWriter(); WriterOutputStream writerOutputStream = new WriterOutputStream(writer, Charset.forName("UTF-8")); ExecuteStreamHandler pandocStreamHandler = new PumpStreamHandler(writerOutputStream, System.err); executor.setStreamHandler(pandocStreamHandler); logger.debug("Launching pandoc:"); logger.debug(cmdLine.toString()); try { executor.execute(cmdLine, resultHandler); } catch (IOException e) { logger.error("Pandoc's execution failed, exiting..."); logger.error(e.getMessage(), e); System.exit(-1); } try { resultHandler.waitFor(); int exitValue = resultHandler.getExitValue(); logger.debug("Pandoc execution's exit value: " + exitValue); ExecuteException executeException = resultHandler.getException(); if (executeException != null && executeException.getCause() != null) { String exceptionKlass = executeException.getCause().getClass().getCanonicalName(); String exceptionMessage = executeException.getCause().getMessage(); if (exceptionKlass.endsWith("IOException") || exceptionMessage.contains("Cannot run program \"pandoc\"")) { logger.error("Pandoc could not be found! Exiting..."); logger.debug(executeException); System.exit(1); } logger.debug(exceptionKlass + ": " + exceptionMessage); } } catch (InterruptedException e) { logger.error("pandoc conversion thread got interrupted, exiting..."); logger.error(e.getMessage(), e); System.exit(1); } // add html document structure to output // pandoc returns no document markup (html, head, body) // therefore we have to use a template String htmlOutput = "<!DOCTYPE html>\n" + "<html>\n" + "<head>\n" + // set title "<title>" + title + "</title>\n" + // include css "<link rel=\"stylesheet\" type=\"text/css\" href=\"main.css\"></link>\n" + "</head>\n" + "<body>"; try { htmlOutput += writer.getBuffer().toString(); writer.close(); } catch (IOException e) { logger.error("Error reading html result from StringBuffer..."); logger.error(e.getMessage(), e); System.exit(1); } // Close tags in template htmlOutput += "</body>\n" + "</html>"; // output loading as JDOM Document SAXBuilder sax = new SAXBuilder(); Document document = null; try { document = sax.build(new StringReader(htmlOutput)); } catch (JDOMException e) { logger.error("JDOM Parsing error"); logger.error(e.getMessage(), e); System.exit(1); } catch (IOException e) { logger.error("Error reading from String..."); logger.error(e.getMessage(), e); System.exit(1); } return document; }
From source file:cn.sinobest.jzpt.framework.utils.string.StringUtils.java
/** * String/*from w w w. j av a2s .com*/ * * @param cr * * @param e * * @param pkgStart * * @return */ public static String exceptionStack(final String cr, Throwable e, final String... pkgStart) { StringWriter w = new StringWriter(); e.printStackTrace(new PrintWriter(w) { @Override public void println() { } @Override public void write(String x) { x = rtrim(x, '\r', '\n', '\t'); if (x.length() == 0) { return; } if (pkgStart.length == 0) { super.write(x, 0, x.length()); super.write(cr, 0, cr.length()); return; } String y = x.trim(); if (!y.startsWith("at ")) { super.write(x, 0, x.length()); super.write(cr, 0, cr.length()); return; } for (String s : pkgStart) { if (matchChars(y, 3, s)) { super.write(x, 0, x.length()); super.write(cr, 0, cr.length()); return; } } } }); w.flush(); IOUtils.closeQuietly(w); return w.getBuffer().toString(); }
From source file:edu.cornell.med.icb.goby.stats.TestAnnotationAveragingWriter.java
@Test public void testCase8() { // Test multiple samples, multiple groups, one comparison String[] groups = new String[] { "group1", "group2" }; String[] samples = new String[] { "sample1", "sample2", "sample3", "sample4" }; int[] positions = new int[] { 6, 8, 14, 16 }; int[][] C = { { 5, 3, 9, 8 }, { 4, 6, 3, 2 }, { 8, 3, 8, 9 }, { 7, 4, 9, 7 } }; int[][] Cm = { { 9, 7, 1, 5 }, { 9, 7, 9, 3 }, { 2, 3, 2, 8 }, { 4, 1, 3, 6 } }; testSupport = new MethylCountProviderTestSupport(groups, samples, positions, "Case4", C, Cm); final StringWriter stringWriter = new StringWriter(); AnnotationAveragingWriter testWriter = new AnnotationAveragingWriter(stringWriter, genome, testSupport); testWriter.setWriteNumSites(false);/*from w w w. j ava2 s . c o m*/ testWriter.setContexts(DEFAULT_TEST_CONTEXTS); testWriter.setAnnotationFilename("test-data/vcf-averaging/annotations-1.tsv"); int[] a = { 0, 0, 1, 1 }; testWriter.setSampleIndexToGroupIndex(a); ArrayList<GroupComparison> groupComparisons = new ArrayList<GroupComparison>(); GroupComparison case8 = new GroupComparison("group1", "group2", 0, 1, 0); groupComparisons.add(case8); testWriter.setGroupComparisons(groupComparisons); testWriter.writeRecord(); testWriter.writeRecord(); testWriter.writeRecord(); testWriter.writeRecord(); testWriter.close(); assertEquals("Test Case 8 result: ", "Chromosome\tStart\tEnd\tFeature\tMR[sample1][CpG]\tMR[sample2][CpG]\tMR[sample3][CpG]\tMR[sample4][CpG]\tMR[sample1][CpA]\tMR[sample2][CpA]\tMR[sample3][CpA]\tMR[sample4][CpA]\tMR[sample1][CpC]\tMR[sample2][CpC]\tMR[sample3][CpC]\tMR[sample4][CpC]\tMR[sample1][CpT]\tMR[sample2][CpT]\tMR[sample3][CpT]\tMR[sample4][CpT]\tMR[sample1][CpN]\tMR[sample2][CpN]\tMR[sample3][CpN]\tMR[sample4][CpN]\tMR[group1][CpG]\tMR[group2][CpG]\tMR[group1][CpA]\tMR[group2][CpA]\tMR[group1][CpC]\tMR[group2][CpC]\tMR[group1][CpT]\tMR[group2][CpT]\tMR[group1][CpN]\tMR[group2][CpN]\tfisherP[group1/group2][CpG]\tfisherP[group1/group2][CpA]\tfisherP[group1/group2][CpC]\tfisherP[group1/group2][CpT]\tfisherP[group1/group2][CpN]\tdeltaMR[group1/group2][CpG]\tdeltaMR[group1/group2][CpA]\tdeltaMR[group1/group2][CpC]\tdeltaMR[group1/group2][CpT]\tdeltaMR[group1/group2][CpN]\n" + "Case4\t5\t9\tannotation7\t\t\t\t\t\t\t\t\t\t\t\t\t66.67\t61.54\t31.25\t31.25\t\t\t\t\t\t\t\t\t\t\t64.00\t31.25\t\t\t1.000\t1.000\t1.000\t0.006227\t1.000\t\t\t\t32.75\t\n" + "Case4\t13\t17\tannotation8\t\t\t\t\t26.09\t70.59\t37.04\t36.00\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t45.00\t36.54\t\t\t\t\t\t\t1.000\t0.5205\t1.000\t1.000\t1.000\t\t8.462\t\t\t\n", stringWriter.getBuffer().toString()); }
From source file:com.twinsoft.convertigo.beans.connectors.HttpConnector.java
@Override public void prepareForTransaction(Context context) throws EngineException { Engine.logBeans.debug("(HttpConnector) Preparing for transaction"); if (Boolean.parseBoolean(EnginePropertiesManager.getProperty(PropertyName.SSL_DEBUG))) { System.setProperty("javax.net.debug", "all"); Engine.logBeans.trace("(HttpConnector) Enabling SSL debug mode"); } else {/*from w w w . ja v a 2s. c om*/ System.setProperty("javax.net.debug", ""); Engine.logBeans.debug("(HttpConnector) Disabling SSL debug mode"); } Engine.logBeans.debug("(HttpConnector) Initializing..."); if (context.isRequestFromVic) { // Check the VIC authorizations only if this is a non trusted // request, i.e. from a request not triggered from VIC (for // instance, from a web service call). if (!context.isTrustedRequest) { try { VicApi vicApi = new VicApi(); if (!vicApi.isServiceAuthorized(context.tasUserName, context.tasVirtualServerName, context.tasServiceCode)) { throw new EngineException("The service '" + context.tasServiceCode + "' is not authorized for the user '" + context.tasUserName + "'"); } } catch (IOException e) { throw new EngineException("Unable to retrieve authorization from the VIC database.", e); } } } AbstractHttpTransaction httpTransaction = null; try { httpTransaction = (AbstractHttpTransaction) context.requestedObject; } catch (ClassCastException e) { throw new EngineException("Requested object is not a transaction", e); } handleCookie = httpTransaction.isHandleCookie(); if (!handleCookie && httpState != null) { httpState.clearCookies(); // remove cookies from previous transaction } httpParameters = httpTransaction.getCurrentHttpParameters(); contentType = MimeType.WwwForm.value(); for (List<String> httpParameter : httpParameters) { String headerName = httpParameter.get(0); String value = httpParameter.get(1); // Content-Type if (HeaderName.ContentType.is(headerName)) { contentType = value; } // oAuth Parameters are passed as standard Headers if (HeaderName.OAuthKey.is(headerName)) { oAuthKey = value; } if (HeaderName.OAuthSecret.is(headerName)) { oAuthSecret = value; } if (HeaderName.OAuthToken.is(headerName)) { oAuthToken = value; } if (HeaderName.OAuthTokenSecret.is(headerName)) { oAuthTokenSecret = value; } } { String overrideContentType = ParameterUtils .toString(httpTransaction.getParameterValue(Parameter.HttpContentType.getName())); if (overrideContentType != null) { contentType = overrideContentType; } } int len = httpTransaction.numberOfVariables(); boolean isFormUrlEncoded = MimeType.WwwForm.is(contentType); doMultipartFormData = false; for (int i = 0; i < len; i++) { RequestableHttpVariable trVariable = (RequestableHttpVariable) httpTransaction.getVariable(i); if (trVariable.getDoFileUploadMode() == DoFileUploadMode.multipartFormData) { doMultipartFormData = true; isFormUrlEncoded = true; } } // Retrieve request template file if necessary File requestTemplateFile = null; if (!isFormUrlEncoded) { String requestTemplateUrl = httpTransaction.getRequestTemplate(); if (!requestTemplateUrl.equals("")) { String projectDirectoryName = context.project.getName(); String absoluteRequestTemplateUrl = Engine.PROJECTS_PATH + "/" + projectDirectoryName + "/" + (context.subPath.length() > 0 ? context.subPath + "/" : "") + requestTemplateUrl; Engine.logBeans.debug("(HttpConnector) Request template Url: " + absoluteRequestTemplateUrl); requestTemplateFile = new File(absoluteRequestTemplateUrl); if (!requestTemplateFile.exists()) { Engine.logBeans.debug( "(HttpConnector) The local request template file (\"" + absoluteRequestTemplateUrl + "\") does not exist. Trying search in Convertigo TEMPLATES directory..."); absoluteRequestTemplateUrl = Engine.TEMPLATES_PATH + "/" + requestTemplateUrl; Engine.logBeans.debug("(HttpConnector) Request template Url: " + absoluteRequestTemplateUrl); requestTemplateFile = new File(absoluteRequestTemplateUrl); if (!requestTemplateFile.exists()) { Engine.logBeans.debug("(HttpConnector) The common request template file (\"" + absoluteRequestTemplateUrl + "\") does not exist. Trying absolute search..."); absoluteRequestTemplateUrl = requestTemplateUrl; Engine.logBeans .debug("(HttpConnector) Request template Url: " + absoluteRequestTemplateUrl); requestTemplateFile = new File(absoluteRequestTemplateUrl); if (!requestTemplateFile.exists()) { throw new EngineException( "Could not find any request template file \"" + requestTemplateUrl + "\" for transaction \"" + httpTransaction.getName() + "\"."); } } } } } // Sets or overwrites server url String httpUrl = httpTransaction.getParameterStringValue(Parameter.ConnectorConnectionString.getName()); if (httpUrl != null) setBaseUrl(httpUrl); else setBaseUrl(); String transactionBaseDir = httpTransaction.getCurrentSubDir(); if (transactionBaseDir.startsWith("http")) { sUrl = transactionBaseDir; /* * if (transactionBaseDir.startsWith("https")) setHttps(true); */ } else sUrl += transactionBaseDir; // Setup the SSL properties if needed if (https) { Engine.logBeans.debug("(HttpConnector) Setting up SSL properties"); certificateManager.collectStoreInformation(context); } String variable, method, httpVariable, queryString = ""; Object httpObjectVariableValue; boolean isMultiValued = false; boolean bIgnoreVariable = false; String urlEncodingCharset = httpTransaction.getComputedUrlEncodingCharset(); // Replace variables in URL List<String> urlPathVariableList = AbstractHttpTransaction.getPathVariableList(sUrl); if (!urlPathVariableList.isEmpty()) { Engine.logBeans.debug("(HttpConnector) Defined URL: " + sUrl); for (String varName : urlPathVariableList) { RequestableHttpVariable rVariable = (RequestableHttpVariable) httpTransaction.getVariable(varName); httpObjectVariableValue = rVariable == null ? "" : httpTransaction.getParameterValue(varName); httpVariable = rVariable == null ? "null" : varName; method = rVariable == null ? "NULL" : rVariable.getHttpMethod(); Engine.logBeans.trace( "(HttpConnector) Path variable: " + varName + " => (" + method + ") " + httpVariable); sUrl = sUrl.replaceAll("\\{" + varName + "\\}", ParameterUtils.toString(httpObjectVariableValue)); } } // Build query string for (int i = 0; i < len; i++) { RequestableHttpVariable rVariable = (RequestableHttpVariable) httpTransaction.getVariable(i); variable = rVariable.getName(); isMultiValued = rVariable.isMultiValued(); method = rVariable.getHttpMethod(); httpVariable = rVariable.getHttpName(); httpObjectVariableValue = httpTransaction.getParameterValue(variable); bIgnoreVariable = urlPathVariableList.contains(variable) || httpObjectVariableValue == null || httpVariable.isEmpty() || !method.equals("GET"); if (!bIgnoreVariable) { Engine.logBeans.trace( "(HttpConnector) Query variable: " + variable + " => (" + method + ") " + httpVariable); try { // handle multivalued variable if (isMultiValued) { if (httpObjectVariableValue instanceof Collection<?>) { for (Object httpVariableValue : (Collection<?>) httpObjectVariableValue) { queryString += ((queryString.length() != 0) ? "&" : ""); queryString += httpVariable + "=" + URLEncoder .encode(ParameterUtils.toString(httpVariableValue), urlEncodingCharset); } } } // standard case else { queryString += ((queryString.length() != 0) ? "&" : ""); queryString += httpVariable + "=" + URLEncoder .encode(ParameterUtils.toString(httpObjectVariableValue), urlEncodingCharset); } } catch (UnsupportedEncodingException e) { throw new EngineException(urlEncodingCharset + " encoding is not supported.", e); } } } // Encodes URL if it contains special characters sUrl = URLUtils.encodeAbsoluteURL(sUrl, urlEncodingCharset); if (queryString.length() != 0) { if (sUrl.indexOf('?') == -1) { sUrl += "?" + queryString; } else { sUrl += "&" + queryString; } } Engine.logBeans.debug("(HttpConnector) URL: " + sUrl); if (Engine.logBeans.isDebugEnabled()) { Engine.logBeans.debug("(HttpConnector) GET query: " + Visibility.Logs.replaceVariables(httpTransaction.getVariablesList(), queryString)); } if (doMultipartFormData) { Engine.logBeans.debug("(HttpConnector) Skip postQuery computing and do a multipart/formData content"); return; } // Build body for POST/PUT postQuery = ""; // Load request template in postQuery if necessary if (!isFormUrlEncoded) { // Ticket #1040 // A request template may be an XML document; in this case, the // "standard" // process apply: tokens are replaced by their respective value. // But a request template may also be an XSL document. In this case, // an XML // document giving all transaction variables should be built and // applied to // the XSL in order to produce a real XML request template. if (requestTemplateFile != null) { try { FileInputStream fis = new FileInputStream(requestTemplateFile); Document requestTemplate = XMLUtils.parseDOM(fis); Element documentElement = requestTemplate.getDocumentElement(); // XSL document if (documentElement.getNodeName().equalsIgnoreCase("xsl:stylesheet")) { // Build the variables XML document Document variablesDocument = XMLUtils.createDom("java"); Element variablesElement = variablesDocument.createElement("variables"); variablesDocument.appendChild(variablesElement); for (RequestableVariable requestableVariable : httpTransaction.getVariablesList()) { RequestableHttpVariable trVariable = (RequestableHttpVariable) requestableVariable; variable = trVariable.getName(); isMultiValued = trVariable.isMultiValued(); httpVariable = trVariable.getHttpName(); Element variableElement = variablesDocument.createElement("variable"); variablesElement.appendChild(variableElement); variableElement.setAttribute("name", variable); httpObjectVariableValue = httpTransaction.getParameterValue(variable); if (httpObjectVariableValue != null) { if (isMultiValued) { variableElement.setAttribute("multi", "true"); if (httpObjectVariableValue instanceof Collection<?>) { for (Object httpVariableValue : (Collection<?>) httpObjectVariableValue) { Element valueElement = variablesDocument.createElement("value"); variableElement.appendChild(valueElement); Text valueText = variablesDocument .createTextNode(getStringValue(trVariable, httpVariableValue)); valueElement.appendChild(valueText); } } } else { Element valueElement = variablesDocument.createElement("value"); variableElement.appendChild(valueElement); Text valueText = variablesDocument .createTextNode(getStringValue(trVariable, httpObjectVariableValue)); valueElement.appendChild(valueText); } } } if (Engine.logBeans.isDebugEnabled()) { String sVariablesDocument = XMLUtils.prettyPrintDOM((Document) Visibility.Logs .replaceVariables(httpTransaction.getVariablesList(), variablesDocument)); Engine.logBeans.debug("Build variables XML document:\n" + sVariablesDocument); } // Apply XSL TransformerFactory tFactory = TransformerFactory.newInstance(); StreamSource streamSource = new StreamSource(new FileInputStream(requestTemplateFile)); Transformer transformer = tFactory.newTransformer(streamSource); StringWriter sw = new StringWriter(); transformer.transform(new DOMSource(variablesElement), new StreamResult(sw)); postQuery = sw.getBuffer().toString(); } // XML document else { // Template has been parsed from file, retrieve its declared encoding char set // If not found use "UTF-8" according to HTTP POST for text/xml (see getData) String xmlEncoding = requestTemplate.getXmlEncoding(); xmlEncoding = (xmlEncoding == null) ? "UTF-8" : xmlEncoding; postQuery = XMLUtils.prettyPrintDOMWithEncoding(requestTemplate, xmlEncoding); } } catch (Exception e) { Engine.logBeans.warn("Unable to parse the request template file as a valid XML/XSL document"); throw new EngineException( "An unexpected error occured while retrieving the request template file for transaction \"" + httpTransaction.getName() + "\".", e); } } } RequestableHttpVariable body = (RequestableHttpVariable) httpTransaction .getVariable(Parameter.HttpBody.getName()); if (body != null) { method = body.getHttpMethod(); httpObjectVariableValue = httpTransaction.getParameterValue(Parameter.HttpBody.getName()); if (method.equals("POST") && httpObjectVariableValue != null) { postQuery = ParameterUtils.toString(httpObjectVariableValue); isFormUrlEncoded = false; } } // Add all input variables marked as POST boolean isLogHidden = false; List<String> logHiddenValues = new ArrayList<String>(); for (int i = 0; i < len; i++) { bIgnoreVariable = false; RequestableHttpVariable trVariable = (RequestableHttpVariable) httpTransaction.getVariable(i); variable = trVariable.getName(); isMultiValued = trVariable.isMultiValued(); method = trVariable.getHttpMethod(); httpVariable = trVariable.getHttpName(); isLogHidden = Visibility.Logs.isMasked(trVariable.getVisibility()); // do not add variable to query if empty name if (httpVariable.equals("")) bIgnoreVariable = true; // Retrieves variable value httpObjectVariableValue = httpTransaction.getParameterValue(variable); if (method.equals("POST")) { // variable must be sent as an HTTP parameter if (!bIgnoreVariable) { Engine.logBeans.trace("(HttpConnector) Parameter variable: " + variable + " => (" + method + ") " + httpVariable); // Content-Type is 'application/x-www-form-urlencoded' if (isFormUrlEncoded) { // Replace variable value in postQuery if (httpObjectVariableValue != null) { // handle multivalued variable if (isMultiValued) { if (httpObjectVariableValue instanceof Collection<?>) for (Object httpVariableValue : (Collection<?>) httpObjectVariableValue) { postQuery += ((postQuery.length() != 0) ? "&" : ""); postQuery += httpVariable + "=" + ParameterUtils.toString(httpVariableValue); } else if (httpObjectVariableValue.getClass().isArray()) for (Object httpVariableValue : (Object[]) httpObjectVariableValue) { postQuery += ((postQuery.length() != 0) ? "&" : ""); postQuery += httpVariable + "=" + ParameterUtils.toString(httpVariableValue); } } // standard case else { postQuery += ((postQuery.length() != 0) ? "&" : ""); postQuery += httpVariable + "=" + ParameterUtils.toString(httpObjectVariableValue); } } } // Content-Type is 'text/xml' else { // Replace variable value in postQuery if (httpObjectVariableValue != null) { // Handle multivalued variable if (isMultiValued) { String varPattern = "$(" + httpVariable + ")"; int varPatternIndex, indexAfterPattern, beginTagIndex, endTagIndex; if (httpObjectVariableValue instanceof Collection<?>) { // while postQuery contains the variable // pattern while (postQuery.indexOf(varPattern) != -1) { varPatternIndex = postQuery.indexOf(varPattern); indexAfterPattern = varPatternIndex + varPattern.length(); if (postQuery.substring(indexAfterPattern).startsWith("concat")) { // concat every value from the // vector // to replace the occurrence in the // template // by the concatenation of the // multiple values String httpVariableValue = ""; for (Object var : (Collection<?>) httpObjectVariableValue) httpVariableValue += getStringValue(trVariable, var); if (isLogHidden) logHiddenValues.add(httpVariableValue); postQuery = postQuery.substring(0, varPatternIndex) + httpVariableValue + postQuery.substring(indexAfterPattern + "concat".length()); } else { // duplicate the tag surrounding the // occurrence in the template // for each value from the vector beginTagIndex = postQuery.substring(0, varPatternIndex) .lastIndexOf('<'); endTagIndex = indexAfterPattern + postQuery.substring(indexAfterPattern).indexOf('>'); String tmpPostQuery = postQuery.substring(0, beginTagIndex); for (Object httpVariableValue : (Collection<?>) httpObjectVariableValue) { String stringValue = getStringValue(trVariable, httpVariableValue); if (isLogHidden) { logHiddenValues.add(stringValue); } tmpPostQuery += (postQuery.substring(beginTagIndex, varPatternIndex) + stringValue + postQuery.substring(indexAfterPattern, endTagIndex + 1)); } tmpPostQuery += postQuery.substring(endTagIndex + 1); postQuery = tmpPostQuery; } } } else { String stringValue = getStringValue(trVariable, httpObjectVariableValue); if (isLogHidden) { logHiddenValues.add(stringValue); } StringEx sx = new StringEx(postQuery); sx.replaceAll("$(" + httpVariable + ")concat", stringValue); postQuery = sx.toString(); } } // Handle single valued variable else { String stringValue = getStringValue(trVariable, httpObjectVariableValue); if (isLogHidden) { logHiddenValues.add(stringValue); } StringEx sx = new StringEx(postQuery); sx.replaceAll("$(" + httpVariable + ")noE", stringValue); sx.replaceAll("$(" + httpVariable + ")", stringValue); postQuery = sx.toString(); } } // Remove variable from postQuery else { String varPattern = "$(" + httpVariable + ")"; int varPatternIndex, beginTagIndex, endTagIndex; // while postQuery contains the variable pattern while (postQuery.indexOf(varPattern) != -1) { varPatternIndex = postQuery.indexOf(varPattern); beginTagIndex = postQuery.substring(0, varPatternIndex).lastIndexOf('<'); endTagIndex = postQuery.indexOf('>', varPatternIndex); postQuery = postQuery.substring(0, beginTagIndex) + postQuery.substring(endTagIndex + 1); } } } } } else if (method.equals("")) { // Replace variable value in postQuery if (httpObjectVariableValue != null) { if (!isFormUrlEncoded && (!(httpVariable.equals("")))) {// used // to // replace // empty // element String stringValue = getStringValue(trVariable, httpObjectVariableValue); if (isLogHidden) { logHiddenValues.add(stringValue); } StringEx sx = new StringEx(postQuery); sx.replaceAll(httpVariable, stringValue); postQuery = sx.toString(); } } } } if (Engine.logBeans.isDebugEnabled()) { Engine.logBeans.debug("(HttpConnector) POST query: " + (isFormUrlEncoded ? "" : "\n") + (isFormUrlEncoded ? Visibility.Logs.replaceVariables(httpTransaction.getVariablesList(), postQuery) : Visibility.Logs.replaceValues(logHiddenValues, postQuery))); } Engine.logBeans.debug("(HttpConnector) Connector successfully prepared for transaction"); }
From source file:edu.cornell.med.icb.goby.stats.TestAnnotationAveragingWriter.java
@Test public void testCase6() { String[] groups = new String[] { "group1", "group2" }; String[] samples = new String[] { "sample1", "sample2", "sample3", "sample4", "sample5", "sample6" }; int[] positions = new int[] { 5, 7, 12, 14, 19, 24, 26, 29 }; int[][] C = { { 5, 3, 4, 8, 5, 2, 8, 7 }, { 5, 3, 9, 8, 9, 8, 4, 9 }, { 5, 3, 9, 8, 7, 9, 8, 0 }, { 5, 3, 9, 8, 9, 9, 8, 0 }, { 5, 3, 9, 8, 2, 9, 8, 0 }, { 0, 3, 5, 8, 8, 7, 8, 0 } }; int[][] Cm = { { 9, 7, 1, 5, 3, 7, 0, 3 }, { 9, 3, 1, 7, 4, 7, 0, 3 }, { 9, 6, 1, 2, 8, 7, 8, 3 }, { 9, 1, 1, 9, 2, 7, 8, 3 }, { 0, 7, 1, 8, 8, 7, 8, 3 }, { 8, 7, 1, 5, 3, 7, 8, 3 } }; testSupport = new MethylCountProviderTestSupport(groups, samples, positions, "Case3", C, Cm); final StringWriter stringWriter = new StringWriter(); AnnotationAveragingWriter testWriter = new AnnotationAveragingWriter(stringWriter, genome, testSupport); testWriter.setWriteNumSites(false);//from w w w. j a va 2 s . c o m testWriter.setContexts(DEFAULT_TEST_CONTEXTS); testWriter.setAnnotationFilename("test-data/vcf-averaging/annotations-1.tsv"); int[] a = { 0, 0, 0, 1, 1, 1 }; testWriter.setSampleIndexToGroupIndex(a); testWriter.writeRecord(); testWriter.writeRecord(); testWriter.writeRecord(); testWriter.writeRecord(); testWriter.writeRecord(); testWriter.writeRecord(); testWriter.writeRecord(); testWriter.writeRecord(); testWriter.close(); assertEquals("Test Case 6 result: ", "Chromosome\tStart\tEnd\tFeature\tMR[sample1][CpG]\tMR[sample2][CpG]\tMR[sample3][CpG]\tMR[sample4][CpG]\tMR[sample5][CpG]\tMR[sample6][CpG]\tMR[sample1][CpA]\tMR[sample2][CpA]\tMR[sample3][CpA]\tMR[sample4][CpA]\tMR[sample5][CpA]\tMR[sample6][CpA]\tMR[sample1][CpC]\tMR[sample2][CpC]\tMR[sample3][CpC]\tMR[sample4][CpC]\tMR[sample5][CpC]\tMR[sample6][CpC]\tMR[sample1][CpT]\tMR[sample2][CpT]\tMR[sample3][CpT]\tMR[sample4][CpT]\tMR[sample5][CpT]\tMR[sample6][CpT]\tMR[sample1][CpN]\tMR[sample2][CpN]\tMR[sample3][CpN]\tMR[sample4][CpN]\tMR[sample5][CpN]\tMR[sample6][CpN]\tMR[group1][CpG]\tMR[group2][CpG]\tMR[group1][CpA]\tMR[group2][CpA]\tMR[group1][CpC]\tMR[group2][CpC]\tMR[group1][CpT]\tMR[group2][CpT]\tMR[group1][CpN]\tMR[group2][CpN]\n" + "Case3\t4\t21\tannotation4\t59.38\t48.48\t60.53\t41.38\t60.00\t62.07\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t56.31\t54.22\t\t\t\t\t\t\t\t\n" + "Case3\t11\t26\tannotation6\t37.21\t33.33\t38.81\t38.57\t47.06\t40.00\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t36.53\t41.92\t\t\t\t\t\t\t\t\n" + "Case3\t4\t30\tannotation3\t45.45\t38.20\t47.31\t43.96\t48.84\t51.85\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t43.63\t48.06\t\t\t\t\t\t\t\t\n" + "Case3\t11\t30\tannotation5\t32.14\t29.73\t26.09\t43.33\t41.38\t40.91\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t29.55\t41.98\t\t\t\t\t\t\t\t\n", stringWriter.getBuffer().toString()); }
From source file:grails.plugin.freemarker.TagLibToDirectiveAndFunction.java
@SuppressWarnings("serial") @Override/*from w w w. j a v a 2 s . c o m*/ public void execute(final Environment env, @SuppressWarnings("rawtypes") Map params, TemplateModel[] loopVars, final TemplateDirectiveBody body) throws TemplateException, IOException { try { Writer wout = env.getOut(); if (wout instanceof GrailsRoutablePrintWriter) { wout = ((GrailsRoutablePrintWriter) wout).getOut(); } tagInstance.invokeMethod("pushOut", wout); params = unwrapParams(params, true); if (log.isDebugEnabled()) { log.debug("wout is " + wout.getClass()); log.debug("execute(): @" + namespace + "." + tagName); log.debug("execute(): params " + params); log.debug("execute(): body " + body); log.debug("hasReturnValue " + hasReturnValue); } Object result = null; if (tagInstance.getMaximumNumberOfParameters() == 1) { result = tagInstance.call(params); } else { Closure bodyClosure = EMPTY_BODY; if (body != null) { bodyClosure = new Closure(this) { @SuppressWarnings({ "unused", "rawtypes", "unchecked" }) public Object doCall(Object it) throws IOException, TemplateException { ObjectWrapper objectWrapper = env.getObjectWrapper(); Map<String, TemplateModel> oldVariables = null; TemplateModel oldIt = null; StringWriter bodyOutput = new StringWriter(); if (log.isDebugEnabled()) { log.debug("doCall it " + it); } boolean itIsAMap = false; if (it != null) { if (it instanceof Map) { itIsAMap = true; oldVariables = new LinkedHashMap<String, TemplateModel>(); Map<String, Object> itMap = (Map) it; for (Map.Entry<String, Object> entry : itMap.entrySet()) { oldVariables.put(entry.getKey(), env.getVariable(entry.getKey())); } } else { oldIt = env.getVariable("it"); } } try { if (it != null) { if (itIsAMap) { Map<String, Object> itMap = (Map) it; for (Map.Entry<String, Object> entry : itMap.entrySet()) { env.setVariable(entry.getKey(), objectWrapper.wrap(entry.getValue())); } } else { env.setVariable("it", objectWrapper.wrap(it)); } } //Writer wout = (Writer) tagInstance.getProperty("out"); body.render(new GrailsPrintWriter(bodyOutput)); } finally { if (oldVariables != null) { for (Map.Entry<String, TemplateModel> entry : oldVariables.entrySet()) { env.setVariable(entry.getKey(), entry.getValue()); } } else if (oldIt != null) { env.setVariable("it", oldIt); } } //return ""; return bodyOutput.getBuffer().toString(); } }; } result = tagInstance.call(new Object[] { params, bodyClosure }); } if (log.isDebugEnabled()) { log.debug("hasReturnValue " + hasReturnValue); //log.debug("result " + result); } //FIXME this used to check for hasReturnValue but since I can't get out passed in right then I always append the result if (result != null && hasReturnValue) { //if (result != null) { env.getOut().append(result.toString()); } } catch (RuntimeException e) { log.error(e.getMessage(), e); throw new TemplateException(e, env); } finally { tagInstance.invokeMethod("popOut", null); } }