List of usage examples for java.io PrintWriter print
public void print(Object obj)
From source file:com.thinkgem.jeesite.modules.retrieval.web.SearchController.java
License:asdf
/** * jsonxml/*w w w .j a v a2 s.c o m*/ * @param request * @param response * @param simpleQuery * @param type */ @RequestMapping(value = "/list/{type}", method = RequestMethod.POST) @ResponseBody public void search(HttpServletRequest request, HttpServletResponse response, @RequestBody SimpleQuery simpleQuery, @PathVariable String type) { RetrievalPages pages = null; long startTime = System.currentTimeMillis(); pages = search(simpleQuery); long endTime = System.currentTimeMillis(); String time = String.format("%.2f", (double) (endTime - startTime) / 1000); pages.setTime(time); if ("json".equals(type)) { try { String json = new MapperUtil().toJson(pages); response.setContentType("application/json"); PrintWriter out = response.getWriter(); out.print(json); } catch (IOException e) { e.printStackTrace(); } } else if ("xml".equals(type)) { try { Map<String, Class> map = new HashMap<String, Class>(); map.put("RetrievalPages", RetrievalPages.class); map.put("RetrievalPage", RetrievalPage.class); String xml = new MapperUtil(map).toXml(pages); response.setContentType("text/xml"); PrintWriter out = response.getWriter(); out.print(xml); } catch (IOException e) { e.printStackTrace(); } } else { } }
From source file:com.redhat.red.build.koji.model.xmlrpc.messages.AbstractKojiMessageTest.java
protected String getFormalizeXMLStringFromFile(final String filename) throws IOException, XMLStreamException { final BufferedReader reader = new BufferedReader(new InputStreamReader(getXMLStream(filename))); final StringWriter writer = new StringWriter(); final PrintWriter pWriter = new PrintWriter(writer); String line = null;//from w ww .j av a 2 s. co m while ((line = reader.readLine()) != null) { pWriter.print(line.trim()); } return formalizeXMLString(writer.toString().trim()); }
From source file:com.test.servlet.LoginController.java
@Override public void setResponse(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter writer = response.getWriter(); String email = getParam(RequestParam.email.toString()); String password = getParam(RequestParam.password.toString()); if (Utility.isStringEmpty(email)) { writer.print( Utility.generalErrorMessage(ResponseCode.email_not_provided.toString(), "Email is required!")); return;//from w w w .java 2s. co m } if (Utility.isStringEmpty(password)) { writer.print(Utility.generalErrorMessage(ResponseCode.password_not_provided.toString(), "Password is required!")); return; } DBUtility dbUtil = new DBUtility(servlet); User user = dbUtil.getUser(email, password); if (user != null) { HttpSession session = request.getSession(); session.setAttribute("user_id", user.getId()); String sessionKey = SessionGenerator.getInstance().nextSessionId(); Cookie cookie = new Cookie("auth_key", sessionKey); cookie.setMaxAge(Constants.COOKIE_AGE); response.addCookie(cookie); dbUtil.insertSession(sessionKey, user.getId()); JSONObject jResponse = new JSONObject(); jResponse.put(JSONKey.status.toString(), 0); //jResponse.put(JSONKey.auth_key.toString(), sessionKey); jResponse.put(JSONKey.user_info.toString(), user.toJSONObject()); writer.print(jResponse.toString()); } else { writer.print(Utility.generalErrorMessage(ResponseCode.email_doesnt_exist.toString(), "Email address not found")); } }
From source file:net.duckling.ddl.web.controller.team.CreateTeamController.java
@RequestMapping(params = "func=validateTeamId") public void validateTeamId(HttpServletRequest request, HttpServletResponse response) throws IOException { String teamId = request.getParameter("teamId"); boolean flag = teamService.isValidateNewTeamName(teamId); PrintWriter writer = response.getWriter(); writer.print(flag); writer.flush();/*from ww w . j a va 2 s . c om*/ writer.close(); }
From source file:com.roncoo.controller.BaseController.java
public void write(HttpServletResponse response, String s) { PrintWriter out = null; try {/*from w w w .j a va 2 s. com*/ out = response.getWriter(); out.print(s); } catch (IOException e) { log.error("?", e); } finally { out.close(); } }
From source file:de.nbi.ontology.test.TextEnhancerTest.java
/** * Test, if texts are enhances properly. * //from w w w .j ava2 s . c o m * @param inFile * a text * @throws IOException */ @Test(dataProviderClass = TestFileProvider.class, dataProvider = "enhanceTestFiles", groups = { "functest" }) public void exactMatch(File inFile) throws IOException { log.info("Processing " + inFile.getName()); String basename = FilenameUtils.removeExtension(inFile.getAbsolutePath()); File outFile = new File(basename + ".out"); File resFile = new File(basename + ".res"); PrintWriter w = new PrintWriter(new FileWriter(outFile)); XWikiTextEnhancer enhancer = new XWikiTextEnhancer(); String text = FileUtils.readFileToString(inFile); String newText = enhancer.enhance(text); w.print(newText); w.flush(); w.close(); Assert.assertTrue(FileUtils.contentEquals(outFile, resFile)); }
From source file:ac.ucy.cs.spdx.service.SpdxViolationAnalysis.java
@POST @Path("/correct/") @Consumes(MediaType.TEXT_PLAIN)//from www . jav a 2 s . c om @Produces(MediaType.TEXT_XML) public Response correctSpdx(String jsonString) throws Exception { ObjectMapper mapper = new ObjectMapper(); JsonNode fileNode = null; try { fileNode = mapper.readTree(jsonString); } catch (JsonProcessingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } String fileName = fileNode.get("filename").toString(); fileName = fileName.substring(1, fileName.length() - 1); final String LICENSE_HTML = "http://spdx.org/licenses/"; String contentXML = fileNode.get("content").toString(); contentXML = StringEscapeUtils.unescapeXml(contentXML); contentXML = contentXML.substring(1, contentXML.length() - 1); String newDeclared = fileNode.get("declared").toString(); newDeclared = newDeclared.substring(1, newDeclared.length() - 1); String fullpath = ParseRdf.parseToRdf(fileName, contentXML); setLastCorrected(fullpath); File xmlFile = new File(fullpath); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(xmlFile); if (doc.getElementsByTagName("licenseDeclared").item(0).getAttributes() .getNamedItem("rdf:resource") == null) { Element e = (Element) doc.getElementsByTagName("licenseDeclared").item(0); e.setAttribute("rdf:resource", LICENSE_HTML + newDeclared); } else { doc.getElementsByTagName("licenseDeclared").item(0).getAttributes().getNamedItem("rdf:resource") .setNodeValue(LICENSE_HTML + newDeclared); } TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); PrintWriter writer = new PrintWriter(xmlFile); writer.print(""); writer.close(); StreamResult result = new StreamResult(xmlFile); transformer.transform(source, result); ResponseBuilder response = Response.ok((Object) xmlFile); response.header("Content-Disposition", "attachment; filename=" + fileName); return response.build();// {"filename":"anomos","declared":"Apache-2.0","content":""} }
From source file:com.library.essay.tinymce.spellchecker.GoogleSpellChekerServlet.java
private void sendData(String xml) throws IOException { uc.setDoOutput(true);//from w ww . j av a 2 s. c om PrintWriter pw = new PrintWriter(uc.getOutputStream()); System.out.println("-------------------" + xml); pw.print(xml); pw.flush(); }
From source file:com.mycompany.rproject.runnableClass.java
public static void write() { try {// w w w .j av a 2s . co m System.out.println("Loading models..."); Configuration configuration = new Configuration(); // Load model from the jar configuration.setAcousticModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us"); //diccionario que usamos configuration.setDictionaryPath("resource:/edu/cmu/sphinx/models/en-us/cmudict-en-us.dict"); //languagemodel configuration.setLanguageModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us.lm.dmp"); // //creo un reconozcedor StreamSpeechRecognizer recognizer = new StreamSpeechRecognizer(configuration); System.out.println("wuhu"); InputStream stream = TranscriberDemo.class .getResourceAsStream("/edu/cmu/sphinx/demo/aligner/outpone.wav"); System.out.println("holotuhu"); // stream.skip(44); System.out.println("wuhuluhutuhu"); // Simple recognition with generic model recognizer.startRecognition(stream); SpeechResult result; String outputFilePath = "/Users/paulamontojo/Downloads/rproject/src/main/resources/edu/cmu/sphinx/demo/aligner/prueba.txt"; PrintWriter pw = null; try { pw = new PrintWriter(new BufferedWriter(new FileWriter(outputFilePath, false))); // Loop until last utterance in the audio file has been decoded, in which case the recognizer will return null. while ((result = recognizer.getResult()) != null) { //get hypothesis System.out.format("Hypothesis: %s\n", result.getHypothesis()); for (WordResult res : result.getWords()) { if (res.toString().contains("<sil>")) { System.out.println(" "); pw.println(" "); } else { System.out.print(res); pw.print(res); } } System.out.println("Best hypothesis:"); for (String s : result.getNbest(1)) { System.out.println(s); System.out.println("holi"); } } } catch (IOException ex) { } finally { if (pw != null) { pw.close(); pw.flush(); } } recognizer.stopRecognition(); try { File archivo = new File( "/Users/paulamontojo/Downloads/rproject/src/main/resources/edu/cmu/sphinx/demo/aligner/prueba.txt"); fr = new FileReader(archivo); br = new BufferedReader(fr); sbu = new StringBuilder(); // Lectura del fichero String linea; while ((linea = br.readLine()) != null) { System.out.println(linea); sbu.append(linea); sbu.append("\n"); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != fr) { fr.close(); } } catch (Exception e2) { e2.printStackTrace(); } } System.out.println(sbu.toString()); } catch (IOException ex) { Logger.getLogger(runnableClass.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:feedme.controller.OrderCompleteServlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request// w ww . j a v a 2 s . c o m * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); String fullName = request.getParameter("fname"); String email = request.getParameter("email"); String phone = request.getParameter("phone"); String address = request.getParameter("address"); Order cart = (Order) request.getSession().getAttribute("shoppingCart"); cart.setCustomerFullName(fullName); cart.setCustomerPhonenum(phone); cart.setCustomerAdress(address); int userId = 0; AuthenticatUser customer = (AuthenticatUser) request.getSession().getAttribute("AuthenticatUser"); try { if (customer != null && PasswordEncryptionService.authenticate(Integer.toString(0), customer.getEncrypRole(), "Customer".getBytes())) { userId = ((AuthenticatUser) request.getSession().getAttribute("AuthenticatUser")).getUserId(); } } catch (NoSuchAlgorithmException ex) { Logger.getLogger(OrderCompleteServlet.class.getName()).log(Level.SEVERE, null, ex); } catch (InvalidKeySpecException ex) { Logger.getLogger(OrderCompleteServlet.class.getName()).log(Level.SEVERE, null, ex); } cart.setOrderCustomerId(userId); DbOrderManagement dbom = new DbOrderManagement(); int result = dbom.addNewOrder(cart); JSONObject orderStatus = new JSONObject(); try { if (result == 1) { request.getSession().setAttribute("shoppingCart", new Order()); orderStatus.put("status", 1); sendEmail(email, cart); } else { orderStatus.put("shoppingCartError", " ? ?? "); orderStatus.put("status", 0); } orderStatus.put("order", cart.toJson()); response.setContentType("application/json"); PrintWriter writer = response.getWriter(); writer.print(orderStatus); response.getWriter().flush(); } catch (JSONException ex) { Logger.getLogger(OrderCompleteServlet.class.getName()).log(Level.SEVERE, null, ex); } }