List of usage examples for java.io PrintWriter write
public void write(String s)
From source file:org.openremote.controller.servlet.LoginServlet.java
/** * Load the login page template and insert a possible error message * @param response Response that will be sent to the client * @param error Error message to be shown in login panel * @throws IOException//w w w . j a va 2s . c o m */ private void returnLoginPage(HttpServletResponse response, String error) throws IOException { PrintWriter out = response.getWriter(); Map<String, String> data = new HashMap<String, String>(); data.put("errorMessage", error); try { out.write(FreemarkerUtil.freemarkerDo(data, "login.ftl")); } catch (TemplateException e) { logger.error(e.getMessage()); } }
From source file:de.undercouch.gradle.tasks.download.AuthenticationTest.java
@Override protected Handler[] makeHandlers() throws IOException { ContextHandler authenticationHandler = new ContextHandler("/" + AUTHENTICATE) { @Override/*from ww w. j a v a 2 s . c o m*/ public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException { String ahdr = request.getHeader("Authorization"); if (ahdr == null) { if (!basic) { response.setHeader("WWW-Authenticate", "Digest realm=\"" + REALM + "\"," + "nonce=\"" + NONCE + "\""); } response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "No authorization header given"); return; } if (basic) { checkBasic(ahdr, response); } else { checkDigest(ahdr, response); } } private void checkBasic(String ahdr, HttpServletResponse response) throws IOException { if (!ahdr.startsWith("Basic ")) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization header does not start with 'Basic '"); return; } ahdr = ahdr.substring(6); ahdr = new String(Base64.decodeBase64(ahdr)); String[] userAndPass = ahdr.split(":"); if (!USERNAME.equals(userAndPass[0]) || !PASSWORD.equals(userAndPass[1])) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Wrong credentials"); return; } response.setStatus(200); PrintWriter rw = response.getWriter(); rw.write("auth: " + ahdr); rw.close(); } private void checkDigest(String ahdr, HttpServletResponse response) throws IOException { if (!ahdr.startsWith("Digest ")) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization header does not start with 'Digest '"); return; } String expectedResponse = USERNAME + ":" + REALM + ":" + PASSWORD; expectedResponse = DigestUtils.md5Hex(expectedResponse); ahdr = ahdr.substring(7); String[] parts = ahdr.split(","); for (String p : parts) { if (p.startsWith("username") && !p.equals("username=\"" + USERNAME + "\"")) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Wrong username"); return; } else if (p.startsWith("nonce") && !p.equals("nonce=\"" + NONCE + "\"")) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Wrong nonce"); return; } else if (p.startsWith("realm") && !p.equals("realm=\"" + REALM + "\"")) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Wrong realm"); return; } else if (p.startsWith("response") && !p.equals("response=\"" + expectedResponse + "\"")) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Wrong response"); return; } } response.setStatus(200); PrintWriter rw = response.getWriter(); rw.close(); } }; return new Handler[] { authenticationHandler }; }
From source file:org.apache.cxf.fediz.service.idp.MetadataServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/xml; charset=utf-8"); PrintWriter out = response.getWriter(); try {//from ww w . j a va2s .c o m ConfigService cs = (ConfigService) getApplicationContext().getBean("config"); Idp idpConfig = cs.getIDP(realm); LOG.debug(idpConfig.toString()); MetadataWriter mw = new MetadataWriter(); Document metadata = mw.getMetaData(idpConfig); out.write(DOM2Writer.nodeToString(metadata)); } catch (Exception ex) { LOG.error("Failed to get metadata document: ", ex); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
From source file:com.microsoft.tfs.client.common.ui.protocolhandler.ProtocolHandlerWindowsRegistrationCommand.java
private void writeHexValue(PrintWriter writer, final String s) throws IOException { final byte[] b = s.getBytes("UTF_16LE"); //$NON-NLS-1$ for (final byte x : b) { writer.write(String.format("%02x", x)); //$NON-NLS-1$ writer.write(','); }//w w w .j a va 2 s . co m // The value in the RegEdit script should be zero-terminated writer.write("00,00"); //$NON-NLS-1$ }
From source file:biz.taoconsulting.dominodav.methods.LOCK.java
/** * Writes out the XML response to a lock request * /* ww w .j a v a 2s . c om*/ * @param res * @param li */ private void writeLockResponseXML(HttpServletResponse resp, LockInfo li) { IDAVXMLResponse xr = DavXMLResponsefactory.getXMLResponse(null, false); /* * Response looks like this: <D:prop xmlns:D="DAV:"> <D:lockdiscovery> * <D:activelock> <D:locktype> <D:write/> </D:locktype> <D:lockscope> * <D:exclusive/> </D:lockscope> <D:depth>0</D:depth> * <D:owner>Administrator</D:owner> <D:timeout>Second-179</D:timeout> * <D:locktoken> * <D:href>opaquelocktoken:45b028e368da5f3e1d9652b2a8f1e1dc</D:href> * </D:locktoken> </D:activelock> </D:lockdiscovery></D:prop> */ xr.openTag("prop"); xr.auxTag("username", li.getUsername()); xr.openTag("lockdiscovery"); xr.openTag("activelock"); xr.openTag("locktype"); xr.emptyTag("write"); xr.closeTag(1); xr.openTag("lockscope"); xr.emptyTag("exclusive"); xr.closeTag(1); xr.simpleTag("depth", "0"); xr.simpleTag("owner", li.getLocalUsername()); xr.simpleTag("timeout", "Second-" + li.getTimeout()); xr.openTag("locktoken"); xr.simpleTag("href", li.getToken()); xr.closeDocument(); // Close all pending tags and the document resp.setContentType(DAVProperties.TYPE_XML); // resp.setHeader("content-encoding", "utf-8"); // resp.setContentLength(xr.getXMLBytes().length); try { String result = xr.toString(); resp.setContentLength(result.length()); PrintWriter out = resp.getWriter(); out.write(result); out.close(); // ServletOutputStream out = this.getOutputStream(); // out.write(xr.getXMLBytes()); // out.close(); } catch (IOException e) { LOGGER.error(e); } }
From source file:edu.cornell.med.icb.goby.modes.CountsArchiveToBedGraphMode.java
/** * Run the map2text mode.//from w w w. ja va2 s. co m * * @throws java.io.IOException error reading / writing */ @Override public void execute() throws IOException { PrintWriter writer = null; try { writer = new PrintWriter( new GZIPOutputStream(new FastBufferedOutputStream(new FileOutputStream(outputFile + ".gz")))); writer.write("track type=bedGraph name=" + label + " visibility=full viewLimits=1:200\n"); final AlignmentReaderImpl alignment = new AlignmentReaderImpl(inputBasename); alignment.readHeader(); alignment.close(); final IndexedIdentifier referenceIds = alignment.getTargetIdentifiers(); final DoubleIndexedIdentifier backwards = new DoubleIndexedIdentifier(referenceIds); final CountsArchiveReader reader = new CountsArchiveReader(inputBasename, alternativeCountArchiveExtension); for (int referenceIndex = 0; referenceIndex < reader.getNumberOfIndices(); referenceIndex++) { String referenceId = backwards.getId(referenceIndex).toString(); boolean processThisSequence = true; // prepare reference ID for UCSC genome browser. if ("MT".equalsIgnoreCase(referenceId)) { // patch chromosome name for UCSC genome browser: referenceId = "M"; } // ignore c22_H2, c5_H2, and other contigs but not things like chr1 (mm9) if (referenceId.startsWith("c") && !referenceId.startsWith("chr")) { processThisSequence = false; } // ignore NT_* if (referenceId.startsWith("NT_")) { processThisSequence = false; } if (filterByReferenceNames && !includeReferenceNames.contains(referenceId)) { processThisSequence = false; } if (processThisSequence) { // prepend the reference id with "chr" if it doesn't use that already final String chromosome; if (referenceId.startsWith("chr")) { chromosome = referenceId; } else { chromosome = "chr" + referenceId; } long sumCount = 0; int numCounts = 0; final CountsReader counts = reader.getCountReader(referenceIndex); int writePosition; while (counts.hasNextTransition()) { counts.nextTransition(); final int length = counts.getLength(); final int count = counts.getCount(); final int position = counts.getPosition(); writePosition = position + 1; if (count != 0) { writer.printf("%s %d %d %d\n", chromosome, writePosition, writePosition + length, count); } sumCount += count; numCounts++; } final double averageCount = sumCount / (double) numCounts; System.out.println("average count for sequence " + referenceId + " " + averageCount); } } } finally { IOUtils.closeQuietly(writer); } }
From source file:cn.leancloud.diamond.client.processor.SnapshotConfigInfoProcessor.java
/** * ?snapshot/*from w w w . j a v a2 s .c om*/ * * @param dataId * @param group * @param config * @throws IOException */ public void saveSnaptshot(String dataId, String group, String config) throws IOException { if (StringUtils.isBlank(dataId)) { throw new IllegalArgumentException("blank dataId"); } if (StringUtils.isBlank(group)) { throw new IllegalArgumentException("blank group"); } if (config == null) { config = ""; } File file = getTargetFile(dataId, group); FileOutputStream out = null; PrintWriter writer = null; try { out = new FileOutputStream(file); BufferedOutputStream stream = new BufferedOutputStream(out); writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream, Constants.ENCODE))); writer.write(config); writer.flush(); } finally { if (writer != null) writer.close(); if (out != null) { out.close(); } } }
From source file:com.android.get.AndroidJSONMethod.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try {/* w w w . ja v a 2 s .co m*/ String fn = request.getParameter("un"); String pw = request.getParameter("pw"); JSONObject jo = new JSONObject(); if (fn.equals("abc") && pw.equals("123")) { jo.put("fname", "Lakmal"); jo.put("lname", "navarathne"); } out.write(jo.toJSONString()); } finally { out.close(); } }
From source file:com.google.appengine.tools.mapreduce.MapReduceServletTest.java
public void testCommandError() throws Exception { HttpServletRequest request = createMockRequest( MapReduceServlet.COMMAND_PATH + "/" + MapReduceServlet.GET_JOB_DETAIL_PATH, false, true); expect(request.getMethod()).andReturn("GET").anyTimes(); HttpServletResponse response = createMock(HttpServletResponse.class); PrintWriter responseWriter = createMock(PrintWriter.class); responseWriter.write('{'); responseWriter.write("\"error_class\""); responseWriter.write(':'); responseWriter.write("\"java.lang.RuntimeException\""); responseWriter.write(','); responseWriter.write("\"error_message\""); responseWriter.write(':'); responseWriter.write("\"Full stack trace is available in the server logs. " + "Message: blargh\""); responseWriter.write('}'); responseWriter.flush();/*ww w . j a v a2s. com*/ // This method can't actually throw this exception, but that's not // important to the test. expect(request.getParameter("mapreduce_id")).andThrow(new RuntimeException("blargh")); response.setContentType("application/json"); expect(response.getWriter()).andReturn(responseWriter).anyTimes(); replay(request, response, responseWriter); servlet.doPost(request, response); verify(request, response, responseWriter); }
From source file:de.tudarmstadt.lt.lm.web.servlet.LanguageModelProviderServlet.java
private void show_available(PrintWriter w) throws RemoteException, NotBoundException, UnsupportedEncodingException { scanForLanguageModels();//from w w w . j ava2 s . c om w.write(_html_header); w.format("<h3>%s</h3>%n", "Available Language Model Provider:"); for (Entry<String, Integer> lmkey2index : _lm_keys.entrySet()) w.format("<p><strong><a href='?lm=%s'>%s</a></strong></p>%n", URLEncoder.encode(lmkey2index.getKey(), "UTF-8"), lmkey2index.getKey()); w.write(_html_footer); }