Java Code Examples for java.io.PrintWriter#write()
The following examples show how to use
java.io.PrintWriter#write() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ResponseUtil.java From DrivingAgency with MIT License | 6 votes |
public static void errorAuthentication(HttpServletResponse response, String errorMsg) { PrintWriter out=null; try { Map<String,Object> data= Maps.newConcurrentMap(); data.put("error",errorMsg); response.setCharacterEncoding("UTF-8"); response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value()); response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE); ResponseResult responseResult= ResponseResult.createByError(ResponseCode.AUTHENTICATION_FAILURE.getCode() ,ResponseCode.AUTHENTICATION_FAILURE.getDesc(),data); out=response.getWriter() ; out.write(JsonSerializerUtil.obj2String(responseResult)); } catch (IOException e) { e.printStackTrace(); }finally { out.close(); } }
Example 2
Source File: UDDI_040_PerformanceIntegrationTest.java From juddi with Apache License 2.0 | 6 votes |
@AfterClass public static void stopManager() throws Exception { if (!TckPublisher.isEnabled()) { return; } tckTModelSam.deleteCreatedTModels(authInfoSam); manager.stop(); Iterator<Map.Entry<String, Double>> iterator = data.entrySet().iterator(); File f = new File("pref-rpt-" + System.currentTimeMillis() + ".txt"); PrintWriter writer = new PrintWriter(f, "UTF-8"); while (iterator.hasNext()) { Map.Entry<String, Double> next = iterator.next(); logger.info(next.getKey() + " = " + next.getValue() + " tx/ms"); writer.write(next.getKey() + " = " + next.getValue() + " tx/ms" + System.getProperty("line.separator")); } writer.close(); f = null; TckCommon.PrintMarker(); }
Example 3
Source File: DispatcherReqRespTests5S_SPEC2_19_ForwardJSPResourceRequest.java From portals-pluto with Apache License 2.0 | 6 votes |
@Override public void render(RenderRequest portletReq, RenderResponse portletResp) throws PortletException, IOException { long tid = Thread.currentThread().getId(); portletReq.setAttribute(THREADID_ATTR, tid); PrintWriter writer = portletResp.getWriter(); writer.write("<div id=\"DispatcherReqRespTests5S_SPEC2_19_ForwardJSPResourceRequest\">no resource output.</div>\n"); ResourceURL resurl = portletResp.createResourceURL(); resurl.setCacheability(PAGE); writer.write("<script>\n"); writer.write("(function () {\n"); writer.write(" var xhr = new XMLHttpRequest();\n"); writer.write(" xhr.onreadystatechange=function() {\n"); writer.write(" if (xhr.readyState==4 && xhr.status==200) {\n"); writer.write(" document.getElementById(\"DispatcherReqRespTests5S_SPEC2_19_ForwardJSPResourceRequest\").innerHTML=xhr.responseText;\n"); writer.write(" }\n"); writer.write(" };\n"); writer.write(" xhr.open(\"GET\",\"" + resurl.toString() + "\",true);\n"); writer.write(" xhr.send();\n"); writer.write("})();\n"); writer.write("</script>\n"); }
Example 4
Source File: Main.java From netbeans with Apache License 2.0 | 6 votes |
public static void main(String[] args) throws IOException { final File file = new File("D:/temp/nbi-build/build.sh"); final String newline = "\n"; final List<String> lines = new LinkedList<String>(); BufferedReader reader = new BufferedReader(new FileReader(file)); String line2read = null; while ((line2read = reader.readLine()) != null) { lines.add(line2read); } reader.close(); PrintWriter writer = new PrintWriter(new FileWriter(file)); for (String line2write: lines) { writer.write(line2write + newline); } writer.close(); }
Example 5
Source File: CharsetServlet.java From quarkus-http with Apache License 2.0 | 5 votes |
@Override protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { String charset = req.getParameter("charset"); resp.setCharacterEncoding(charset); PrintWriter writer = resp.getWriter(); writer.write("\u0041\u00A9\u00E9\u0301\u0941\uD835\uDD0A"); writer.close(); }
Example 6
Source File: FilterTests_PortletFilter_ApiEventFilter_event.java From portals-pluto with Apache License 2.0 | 5 votes |
@Override public void render(RenderRequest portletReq, RenderResponse portletResp) throws PortletException, IOException { portletResp.setContentType("text/html"); PrintWriter writer = portletResp.getWriter(); writer.write("<h3>Event Companion Portlet </h3>\n"); writer.write("<p>FilterTests_PortletFilter_ApiEventFilter_event</p>\n"); String msg = (String) portletReq.getPortletSession().getAttribute( RESULT_ATTR_PREFIX + "FilterTests_PortletFilter_ApiEventFilter", APPLICATION_SCOPE); msg = (msg == null) ? "Not ready. click test case link." : msg; writer.write("<p>" + msg + "</p>\n"); }
Example 7
Source File: LogoutSuccessHandlerImpl.java From Eagle with Apache License 2.0 | 5 votes |
@Override public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { PrintWriter writer = response.getWriter(); ObjectMapper mapper = new ObjectMapper(); if(authentication!=null && authentication.isAuthenticated()) { response.setStatus(HttpServletResponse.SC_OK); writer.write(mapper.writeValueAsString(new AuthenticationResult(true, "Successfully logout session for user \"" + authentication.getName()+"\""))); }else{ response.setStatus(HttpServletResponse.SC_OK); writer.write(mapper.writeValueAsString(new AuthenticationResult(true, "Session is not authenticated"))); } writer.flush(); writer.close(); }
Example 8
Source File: SSIEcho.java From tomcatsrc with Apache License 2.0 | 5 votes |
/** * @see SSICommand */ @Override public long process(SSIMediator ssiMediator, String commandName, String[] paramNames, String[] paramValues, PrintWriter writer) { String encoding = DEFAULT_ENCODING; String originalValue = null; String errorMessage = ssiMediator.getConfigErrMsg(); for (int i = 0; i < paramNames.length; i++) { String paramName = paramNames[i]; String paramValue = paramValues[i]; if (paramName.equalsIgnoreCase("var")) { originalValue = paramValue; } else if (paramName.equalsIgnoreCase("encoding")) { if (isValidEncoding(paramValue)) { encoding = paramValue; } else { ssiMediator.log("#echo--Invalid encoding: " + paramValue); writer.write(errorMessage); } } else { ssiMediator.log("#echo--Invalid attribute: " + paramName); writer.write(errorMessage); } } String variableValue = ssiMediator.getVariableValue( originalValue, encoding); if (variableValue == null) { variableValue = MISSING_VARIABLE_VALUE; } writer.write(variableValue); return System.currentTimeMillis(); }
Example 9
Source File: SSIFlastmod.java From Tomcat7.0.67 with Apache License 2.0 | 5 votes |
/** * @see SSICommand */ @Override public long process(SSIMediator ssiMediator, String commandName, String[] paramNames, String[] paramValues, PrintWriter writer) { long lastModified = 0; String configErrMsg = ssiMediator.getConfigErrMsg(); for (int i = 0; i < paramNames.length; i++) { String paramName = paramNames[i]; String paramValue = paramValues[i]; String substitutedValue = ssiMediator .substituteVariables(paramValue); try { if (paramName.equalsIgnoreCase("file") || paramName.equalsIgnoreCase("virtual")) { boolean virtual = paramName.equalsIgnoreCase("virtual"); lastModified = ssiMediator.getFileLastModified( substitutedValue, virtual); Date date = new Date(lastModified); String configTimeFmt = ssiMediator.getConfigTimeFmt(); writer.write(formatDate(date, configTimeFmt)); } else { ssiMediator.log("#flastmod--Invalid attribute: " + paramName); writer.write(configErrMsg); } } catch (IOException e) { ssiMediator.log( "#flastmod--Couldn't get last modified for file: " + substitutedValue, e); writer.write(configErrMsg); } } return lastModified; }
Example 10
Source File: HeaderPortletTests_SPEC3_6_4_HeaderPortlet.java From portals-pluto with Apache License 2.0 | 5 votes |
@Override public void render(RenderRequest renderRequest, RenderResponse renderResponse) throws PortletException, IOException { PrintWriter writer = renderResponse.getWriter(); ModuleTestCaseDetails tcd = new ModuleTestCaseDetails(); /* TestCase: V3HeaderPortletTests_SPEC3_6_4_HeaderPortlet_renderHeaders */ /* * Details: "renderHeaders() method is called before render() method if * the portlet implements HeaderPortlet interface." */ { TestResult result = tcd.getTestResultFailed( V3HEADERPORTLETTESTS_SPEC3_6_4_HEADERPORTLET_RENDERHEADERS); result.setTcSuccess(tr0_success); result.writeTo(writer); tr0_success = false; } String msg = (String) renderRequest.getAttribute( RESULT_ATTR_PREFIX + "HeaderPortletTests_SPEC3_6_4_HeaderPortlet"); writer.write("<p>" + msg + "</p>\n"); renderRequest.removeAttribute( RESULT_ATTR_PREFIX + "HeaderPortletTests_SPEC3_6_4_HeaderPortlet"); }
Example 11
Source File: UserInfoServlet.java From openid4java with Apache License 2.0 | 5 votes |
protected void onService(HttpServletRequest req, HttpServletResponse resp) throws Exception { String serverUrl = "http://" + req.getServerName() + ":" + req.getServerPort() + "/provider"; String back; if ("html".equals(req.getParameter("format"))) { resp.setContentType("text/html"); back = "<html><head>\n" + "<link rel='openid.server' href='" + serverUrl + "'/>\n" + "</head><body>in html</body></html>" ; } else { resp.setContentType("application/xrds+xml"); back = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<xrds:XRDS\n" + " xmlns:xrds=\"xri://$xrds\"\n" + " xmlns:openid=\"http://openid.net/xmlns/1.0\"\n" + " xmlns=\"xri://$xrd*($v*2.0)\">\n" + " <XRD>\n" + " <Service priority=\"0\">\n" + " <Type>http://openid.net/signon/1.0</Type>\n" + " <URI>http://" + req.getServerName() + ":" + req.getServerPort() + "/provider</URI>\n" + " </Service>\n" + " </XRD>\n" + "</xrds:XRDS>" ; } PrintWriter out = resp.getWriter(); out.write(back); }
Example 12
Source File: AddlEnvironmentTests_SPEC2_10_ContextOptions_event.java From portals-pluto with Apache License 2.0 | 5 votes |
@Override public void render(RenderRequest portletReq, RenderResponse portletResp) throws PortletException, IOException { PrintWriter writer = portletResp.getWriter(); writer.write("<h3>Event Companion Portlet </h3>\n"); writer.write("<p>AddlEnvironmentTests_SPEC2_10_ContextOptions_event</p>\n"); PortletURL aurl = portletResp.createActionURL(); TestButton tb = new TestButton(V2ADDLENVIRONMENTTESTS_SPEC2_10_CONTEXTOPTIONS_ACTIONSCOPEDREQUESTATTRIBUTES9, aurl); tb.writeTo(writer); }
Example 13
Source File: TopologySSEServlet.java From thorntail with Apache License 2.0 | 5 votes |
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/event-stream"); resp.setCharacterEncoding("UTF-8"); AsyncContext asyncContext = req.startAsync(); PrintWriter writer = resp.getWriter(); TopologyListener topologyListener = new SSETopologyListener(writer, req.isSecure()); ScheduledFuture keepAlive = this.keepAliveExecutor.scheduleAtFixedRate( new KeepAliveRunnable(writer, topologyListener), 10, 15, TimeUnit.SECONDS); asyncContext.setTimeout(0); asyncContext.addListener(new TopologyAsyncListener(topology, topologyListener, keepAlive)); this.topology.addListener(topologyListener); String json = topologyToJson(req.isSecure()); writer.write("event: topologyChange\n"); writer.write("data: " + json); writer.flush(); }
Example 14
Source File: ConfigurationManager.java From ciscorouter with MIT License | 5 votes |
/** * Saves the updated configuration to the specified file. */ public static void saveConfiguration(File save, ArrayList<Host> saveHosts) { Element root = new Element("Hosts"); for(Host h : saveHosts) { Element host = new Element("Host"); Element ip = new Element("IP"); ip.appendChild(h.getAddress().toString()); host.appendChild(ip); Element username = new Element("Username"); username.appendChild(h.getUser()); host.appendChild(username); Element password = new Element("Password"); password.appendChild(h.getPass()); host.appendChild(password); if(h.usesEnable()) { Element superuser = new Element("ElevatePassword"); superuser.appendChild(h.getEnablePass()); host.appendChild(superuser); } root.appendChild(host); } Document doc = new Document(root); FileWriter f = null; try { f = new FileWriter(save); } catch (IOException e) { e.printStackTrace(); } PrintWriter p = new PrintWriter(f); p.write(doc.toXML()); p.flush(); p.close(); }
Example 15
Source File: SigTestsURL_PortletURL_SIGResourceRenurl.java From portals-pluto with Apache License 2.0 | 5 votes |
@Override public void render(RenderRequest portletReq, RenderResponse portletResp) throws PortletException, IOException { long tid = Thread.currentThread().getId(); portletReq.setAttribute(THREADID_ATTR, tid); PrintWriter writer = portletResp.getWriter(); writer .write("<div id=\"SigTestsURL_PortletURL_SIGResourceRenurl\">no resource output.</div>\n"); ResourceURL resurl = portletResp.createResourceURL(); resurl.setCacheability(PAGE); writer.write("<script>\n"); writer.write("(function () {\n"); writer.write(" var xhr = new XMLHttpRequest();\n"); writer.write(" xhr.onreadystatechange=function() {\n"); writer.write(" if (xhr.readyState==4 && xhr.status==200) {\n"); writer.write( " document.getElementById(\"SigTestsURL_PortletURL_SIGResourceRenurl\").innerHTML=xhr.responseText;\n"); writer.write(" }\n"); writer.write(" };\n"); writer.write(" xhr.open(\"GET\",\"" + resurl.toString() + "\",true);\n"); writer.write(" xhr.send();\n"); writer.write("})();\n"); writer.write("</script>\n"); }
Example 16
Source File: MavenHandler.java From packagedrone with Eclipse Public License 1.0 | 5 votes |
private void renderDirAsHtml ( final HttpServletResponse response, final DirectoryNode dir, final String path ) throws IOException { response.setContentType ( "text/html; charset=utf-8" ); @SuppressWarnings ( "resource" ) final PrintWriter w = response.getWriter (); final Map<String, Object> model = new HashMap<> (); model.put ( "path", path ); model.put ( "dir", new HtmlDirRenderer ( dir ) ); model.put ( "version", VersionInformation.VERSION ); w.write ( StringReplacer.replace ( loadResource ( "content/index.html" ), new ExtendedPropertiesReplacer ( model ), StringReplacer.DEFAULT_PATTERN, true ) ); }
Example 17
Source File: TestChunkedInputFilter.java From tomcatsrc with Apache License 2.0 | 5 votes |
private void dumpHeader(String headerName, HttpServletRequest req, PrintWriter pw) { String value = req.getHeader(headerName); if (value == null) { value = "null"; } pw.write(value); }
Example 18
Source File: ServletTest.java From raml-tester with Apache License 2.0 | 5 votes |
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("application/json"); final PrintWriter out = resp.getWriter(); out.write(req.getParameter("param") == null ? "\"json string\"" : "illegal json"); out.flush(); }
Example 19
Source File: ScriptServlet.java From BotLibre with Eclipse Public License 1.0 | 4 votes |
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); LoginBean loginBean = getEmbeddedLoginBean(request, response); SessionProxyBean proxy = (SessionProxyBean)request.getSession().getAttribute("proxy"); ScriptBean bean = loginBean.getBean(ScriptBean.class); loginBean.setActiveBean(bean); if (!loginBean.checkDomain(request, response)) { return; } String domain = (String)request.getParameter("domain"); if (domain != null) { DomainBean domainBean = loginBean.getBean(DomainBean.class); if (domainBean.getInstance() == null || !String.valueOf(domainBean.getInstanceId()).equals(domain)) { domainBean.validateInstance(domain); } } String browse = (String)request.getParameter("id"); String source = (String)request.getParameter("source"); String versions = (String)request.getParameter("versions"); String file = (String)request.getParameter("file"); if (browse != null) { if (proxy != null) { proxy.setInstanceId(browse); } if (bean.validateInstance(browse)) { if ((versions != null)) { request.getRequestDispatcher("script-versions.jsp").forward(request, response); return; } if (file != null) { bean.incrementConnects(ClientType.WEB); if (Site.LOCK && !loginBean.isSandbox()) { throw new BotException("Must use sandbox domain"); } if (bean.getInstance().getLanguage().equals("HTML")) { response.setContentType("text/html; charset=utf-8"); } //response.setHeader("Content-disposition","attachment; filename=" + encodeURI(state.getName()) + ".log"); PrintWriter writer = response.getWriter(); writer.write(bean.getInstance().getSourceCode()); writer.flush(); return; } if (source != null) { bean.incrementConnects(ClientType.WEB); if (bean.getInstance().isExternal()) { response.sendRedirect(bean.getInstance().getWebsiteURL()); } else { request.getRequestDispatcher("script-source.jsp").forward(request, response); } return; } } else if (file != null) { request.getRequestDispatcher("error.jsp").forward(request, response); return; } request.getRequestDispatcher("script.jsp").forward(request, response); return; } doPost(request, response); }
Example 20
Source File: TestContainerManager.java From big-c with Apache License 2.0 | 4 votes |
@Test public void testContainerSetup() throws Exception { containerManager.start(); // ////// Create the resources for the container File dir = new File(tmpDir, "dir"); dir.mkdirs(); File file = new File(dir, "file"); PrintWriter fileWriter = new PrintWriter(file); fileWriter.write("Hello World!"); fileWriter.close(); // ////// Construct the Container-id ContainerId cId = createContainerId(0); // ////// Construct the container-spec. ContainerLaunchContext containerLaunchContext = recordFactory.newRecordInstance(ContainerLaunchContext.class); URL resource_alpha = ConverterUtils.getYarnUrlFromPath(localFS .makeQualified(new Path(file.getAbsolutePath()))); LocalResource rsrc_alpha = recordFactory.newRecordInstance(LocalResource.class); rsrc_alpha.setResource(resource_alpha); rsrc_alpha.setSize(-1); rsrc_alpha.setVisibility(LocalResourceVisibility.APPLICATION); rsrc_alpha.setType(LocalResourceType.FILE); rsrc_alpha.setTimestamp(file.lastModified()); String destinationFile = "dest_file"; Map<String, LocalResource> localResources = new HashMap<String, LocalResource>(); localResources.put(destinationFile, rsrc_alpha); containerLaunchContext.setLocalResources(localResources); StartContainerRequest scRequest = StartContainerRequest.newInstance( containerLaunchContext, createContainerToken(cId, DUMMY_RM_IDENTIFIER, context.getNodeId(), user, context.getContainerTokenSecretManager())); List<StartContainerRequest> list = new ArrayList<StartContainerRequest>(); list.add(scRequest); StartContainersRequest allRequests = StartContainersRequest.newInstance(list); containerManager.startContainers(allRequests); BaseContainerManagerTest.waitForContainerState(containerManager, cId, ContainerState.COMPLETE); // Now ascertain that the resources are localised correctly. ApplicationId appId = cId.getApplicationAttemptId().getApplicationId(); String appIDStr = ConverterUtils.toString(appId); String containerIDStr = ConverterUtils.toString(cId); File userCacheDir = new File(localDir, ContainerLocalizer.USERCACHE); File userDir = new File(userCacheDir, user); File appCache = new File(userDir, ContainerLocalizer.APPCACHE); File appDir = new File(appCache, appIDStr); File containerDir = new File(appDir, containerIDStr); File targetFile = new File(containerDir, destinationFile); File sysDir = new File(localDir, ResourceLocalizationService.NM_PRIVATE_DIR); File appSysDir = new File(sysDir, appIDStr); File containerSysDir = new File(appSysDir, containerIDStr); for (File f : new File[] { localDir, sysDir, userCacheDir, appDir, appSysDir, containerDir, containerSysDir }) { Assert.assertTrue(f.getAbsolutePath() + " doesn't exist!!", f.exists()); Assert.assertTrue(f.getAbsolutePath() + " is not a directory!!", f.isDirectory()); } Assert.assertTrue(targetFile.getAbsolutePath() + " doesn't exist!!", targetFile.exists()); // Now verify the contents of the file BufferedReader reader = new BufferedReader(new FileReader(targetFile)); Assert.assertEquals("Hello World!", reader.readLine()); Assert.assertEquals(null, reader.readLine()); }