List of usage examples for java.io PrintWriter print
public void print(Object obj)
From source file:org.nuxeo.client.internals.spi.NuxeoClientException.java
@Override public void printStackTrace(PrintWriter s) { if (status == INTERNAL_ERROR_STATUS) { super.printStackTrace(s); }/*w ww . java 2 s. c o m*/ s.println("Exception:"); s.print(getRemoteStackTrace()); }
From source file:org.clothocad.phagebook.controllers.AutoCompleteController.java
@RequestMapping(value = "/autoComplete", method = RequestMethod.GET) protected void autoComplete(@RequestParam Map<String, String> params, HttpServletResponse response) throws ServletException, IOException { //I WILL RETURN THE MAP AS A JSON OBJECT.. it is client side's issue to parse all data for what they need! //they could check over there if the schema matches what they are querying for and so i can do this generically! //user should be logged in so I will log in as that user. String query = params.get("query") != null ? params.get("query") : ""; boolean isValid = false; System.out.println("Query is: " + query); if (!query.equals("")) { isValid = true;/*ww w .j ava 2 s.c om*/ } if (isValid) { ClothoConnection conn = new ClothoConnection(Args.clothoLocation); Clotho clothoObject = new Clotho(conn); //TODO: we need to have an authentication token at some point String username = this.backendPhagebookUser; String password = this.backendPhagebookPassword; Map loginMap = new HashMap(); loginMap.put("username", username); loginMap.put("credentials", password); clothoObject.login(loginMap); JSONArray replies = (JSONArray) clothoObject.autocomplete(query); conn.closeConnection(); response.setStatus(HttpServletResponse.SC_ACCEPTED); response.setContentType("application/json"); PrintWriter out = response.getWriter(); out.print(replies); out.flush(); out.close(); clothoObject.logout(); } response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.setContentType("application/json"); JSONObject reply = new JSONObject(); reply.put("message", "Auto Complete requires a query parameter"); PrintWriter out = response.getWriter(); out.print(reply); out.flush(); out.close(); }
From source file:com.ict.nasc.tasc.app.module.screen.simple.Download.java
/** * /*w w w . j a v a2s . c om*/ * * @param filename * @throws Exception */ public void execute(@Param("filename") String filename) throws Exception { // buffering? ??? brc.setBuffering(false); // headers?????us-ascii???? filename = defaultIfNull(trimToNull(filename), "image") + ".txt"; filename = "\"" + escapeURL(filename) + "\""; response.setHeader("Content-disposition", "attachment; filename=" + filename); // ??content type? // HTML?JSON?JavaScript?JPG?PDF?EXCEL response.setContentType("text/plain"); PrintWriter out = response.getWriter(); for (int i = 0; i < 100; i++) { out.flush(); // ??? for (int j = 0; j < 100000; j++) { out.print(i); } out.println(); Thread.sleep(100); // ?? } }
From source file:com.aptechfpt.controller.InsertSalePerson.java
protected void Register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {/*from w w w . java 2 s.co m*/ boolean isMultipartContext = ServletFileUpload.isMultipartContent(request); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> fields = upload.parseRequest(request); AccountDTO.Builder builder = new AccountDTO.Builder(); for (Iterator<FileItem> it = fields.iterator(); it.hasNext();) { FileItem fileItem = it.next(); switch (fileItem.getFieldName()) { case "email": System.out.println("email: " + fileItem.getString()); builder.Email(fileItem.getString()); continue; case "password": System.out.println("password: " + fileItem.getString()); builder.Password(fileItem.getString()); continue; case "image": System.out.println("image: " + fileItem.getName()); builder.ImageLink(writeFile(fileItem)); continue; case "firstName": System.out.println("firstName: " + fileItem.getString()); builder.FirstName(fileItem.getString()); continue; case "lastName": System.out.println("lastName: " + fileItem.getString()); builder.LastName(fileItem.getString()); continue; case "phone": System.out.println("phone: " + fileItem.getString()); builder.Phone(fileItem.getString()); continue; case "address": System.out.println("address: " + fileItem.getString()); builder.Address(fileItem.getString()); continue; case "gender": System.out.println("gender: " + fileItem.getString()); builder.Gender(AccountGender.valueOf(fileItem.getString())); continue; // case "role": // System.out.println("role: " + fileItem.getString()); // builder.Role(Role.valueOf(fileItem.getString())); case "dateOfBirth": System.out.println("dateOfBirth: " + fileItem.getString()); builder.DateOfBirth(new DateTime(fileItem.getString())); } } builder.Role(Role.SALEPERSON); AccountDTO dto = builder.build(); System.out.println("Email: " + dto.getEmail()); System.out.println("Password: " + dto.getPassword()); System.out.println("Image Link: " + dto.getImageLink()); System.out.println("First Name: " + dto.getFirstName()); System.out.println("Last Name: " + dto.getLastName()); System.out.println("Gender: " + dto.getGender()); System.out.println("Phone: " + dto.getPhone()); System.out.println("Address: " + dto.getAddress()); System.out.println("Date Of Birth: " + dto.getDateOfBirth()); accountFacade.create(dto.toAccount()); StringBuilder jsonRes = new StringBuilder(); jsonRes.append("{\"message\":").append("\"Account ").append(dto.getEmail()) .append(" create successfull.").append("\"}"); response.setContentType("application/json"); PrintWriter out = response.getWriter(); out.print(jsonRes.toString()); out.close(); } catch (FileUploadException ex) { ex.printStackTrace(); Logger.getLogger(InsertSalePerson.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:$.Download.java
public void execute(@Param("filename") String filename) throws Exception { // buffering???? brc.setBuffering(false);/*w w w . j a v a 2s . c om*/ // headers?????us-ascii???? filename = defaultIfNull(trimToNull(filename), "image") + ".txt"; filename = "\"" + escapeURL(filename) + "\""; response.setHeader("Content-disposition", "attachment; filename=" + filename); // ??content type? // HTML?JSON?JavaScript?JPG?PDF?EXCEL response.setContentType("text/plain"); PrintWriter out = response.getWriter(); for (int i = 0; i < 100; i++) { out.flush(); // ??? for (int j = 0; j < 100000; j++) { out.print(i); } out.println(); Thread.sleep(100); // ?? } }
From source file:com.sdapp.server.LoginServlet.java
private void printParamRow(PrintWriter out, String name, String value) { out.println("<TR><TD>" + name + "\n<TD>"); if (value.length() == 0) out.print("<I>No Value</I>"); else// www . j a v a 2 s . c o m out.print(value); }
From source file:org.loklak.api.server.AccountServlet.java
@SuppressWarnings("unchecked") protected void process(HttpServletRequest request, HttpServletResponse response, RemoteAccess.Post post) throws ServletException, IOException { // parameters String callback = post.get("callback", ""); boolean jsonp = callback != null && callback.length() > 0; boolean minified = post.get("minified", false); boolean update = "update".equals(post.get("action", "")); String screen_name = post.get("screen_name", ""); String data = post.get("data", ""); if (update) { if (data == null || data.length() == 0) { response.sendError(400, "your request does not contain a data object."); return; }/*from ww w. ja v a2s . co m*/ // parse the json data try { Map<String, Object> map = DAO.jsonMapper.readValue(data, DAO.jsonTypeRef); Object accounts_obj = map.get("accounts"); List<Map<String, Object>> accounts; if (accounts_obj instanceof List<?>) { accounts = (List<Map<String, Object>>) accounts_obj; } else { accounts = new ArrayList<Map<String, Object>>(1); accounts.add(map); } for (Map<String, Object> account : accounts) { if (account == null) continue; try { AccountEntry a = new AccountEntry(account); DAO.writeAccount(a, true); } catch (IOException e) { response.sendError(400, "submitted data is not well-formed: " + e.getMessage()); e.printStackTrace(); return; } } if (accounts.size() == 1) { screen_name = (String) accounts.iterator().next().get("screen_name"); } } catch (IOException e) { e.printStackTrace(); } } UserEntry userEntry = DAO.searchLocalUserByScreenName(screen_name); AccountEntry accountEntry = DAO.searchLocalAccount(screen_name); post.setResponse(response, "application/javascript"); // generate json Map<String, Object> m = new LinkedHashMap<>(); Map<String, Object> metadata = new LinkedHashMap<>(); metadata.put("count", userEntry == null ? "0" : "1"); metadata.put("client", post.getClientHost()); m.put("search_metadata", metadata); // create a list of accounts. Why a list? Because the same user may have accounts for several services. List<Object> accounts = new ArrayList<>(); if (accountEntry == null) { if (userEntry != null) accounts.add(AccountEntry.toEmptyAccount(userEntry)); } else { accounts.add(accountEntry.toMap(userEntry)); } m.put("accounts", accounts); // write json PrintWriter sos = response.getWriter(); if (jsonp) sos.print(callback + "("); sos.print((minified ? new ObjectMapper().writer() : new ObjectMapper().writerWithDefaultPrettyPrinter()) .writeValueAsString(m)); if (jsonp) sos.println(");"); sos.println(); post.finalize(); }
From source file:ch.unifr.pai.twice.widgets.mpProxyScreenShot.server.ReadOnlyPresentation.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter w = resp.getWriter(); for (String uuid : uuidToScreenshot.keySet()) { Screenshot s = uuidToScreenshot.get(uuid); w.print("<div style=\"width:"); w.print((int) Math.ceil((double) s.width * scaleFactor)); w.print("px; height:"); w.print((int) Math.ceil((double) s.height * scaleFactor)); w.print("px; overflow:hidden; display:inline-block;\">"); w.print("<iframe "); w.print("name=\""); w.print(uuid);//from w ww .j a va2 s . c o m w.print("\" style=\"width:100%; height:100%;\" src=\""); w.print(SimpleHttpUrlConnectionServletFilter.getServletPath(req)); w.print("/" + s.url + "/"); w.print("miceScreenShot?uuid=" + uuid); w.print("\"></iframe></div>"); } w.flush(); w.close(); return; }
From source file:main.java.vasolsim.common.file.ExamBuilder.java
/** * Writes an exam to an XML file/* ww w . j av a 2 s . c om*/ * * @param exam the exam to be written * @param examFile the target file * @param password the passphrase locking the restricted content * @param overwrite if an existing file can be overwritten * * @return if the write was successful * * @throws VaSolSimException */ public static boolean writeExam(@Nonnull Exam exam, @Nonnull File examFile, @Nonnull String password, boolean overwrite) throws VaSolSimException { logger.info("beginning exam export -> " + exam.getTestName()); logger.debug("checking export destination..."); /* * check the file creation status and handle it */ //if it exists if (examFile.isFile()) { logger.trace("exam file exists, checking overwrite..."); //can't overwrite if (!overwrite) { logger.error("file already present and cannot overwrite"); throw new VaSolSimException(ERROR_MESSAGE_FILE_ALREADY_EXISTS); } //can overwrite, clear the existing file else { logger.trace("overwriting..."); PrintWriter printWriter; try { printWriter = new PrintWriter(examFile); } catch (FileNotFoundException e) { logger.error("internal file presence check failed", e); throw new VaSolSimException(ERROR_MESSAGE_FILE_NOT_FOUND_AFTER_INTERNAL_CHECK); } printWriter.print(""); printWriter.close(); } } //no file, create one else { logger.trace("exam file does not exist, creating..."); if (!examFile.getParentFile().isDirectory() && !examFile.getParentFile().mkdirs()) { logger.error("could not create empty directories for export"); throw new VaSolSimException(ERROR_MESSAGE_COULD_NOT_CREATE_DIRS); } try { logger.trace("creating files..."); if (!examFile.createNewFile()) { logger.error("could not create empty file for export"); throw new VaSolSimException(ERROR_MESSAGE_COULD_NOT_CREATE_FILE); } } catch (IOException e) { logger.error("io error on empty file creation", e); throw new VaSolSimException(ERROR_MESSAGE_CREATE_FILE_EXCEPTION); } } logger.debug("initializing weak cryptography scheme..."); /* * initialize the cryptography system */ String encryptedHash; Cipher encryptionCipher; try { logger.trace("hashing password into key..."); //hash the password byte[] hash; MessageDigest msgDigest = MessageDigest.getInstance("SHA-512"); msgDigest.update(password.getBytes()); hash = GenericUtils.validate512HashTo128Hash(msgDigest.digest()); logger.trace("initializing cipher"); encryptionCipher = GenericUtils.initCrypto(hash, Cipher.ENCRYPT_MODE); encryptedHash = GenericUtils .convertBytesToHexString(GenericUtils.applyCryptographicCipher(hash, encryptionCipher)); } catch (NoSuchAlgorithmException e) { logger.error("FAILED. could not initialize crypto", e); throw new VaSolSimException(ERROR_MESSAGE_GENERIC_CRYPTO + "\n\nBAD ALGORITHM\n" + e.toString() + "\n" + e.getCause() + "\n" + ExceptionUtils.getStackTrace(e), e); } logger.debug("initializing the document builder..."); /* * initialize the document */ Document examDoc; Transformer examTransformer; try { logger.trace("create document builder factory instance -> create new doc"); examDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); logger.trace("set document properties"); examTransformer = TransformerFactory.newInstance().newTransformer(); examTransformer.setOutputProperty(OutputKeys.INDENT, "yes"); examTransformer.setOutputProperty(OutputKeys.METHOD, "xml"); examTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); examTransformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "roles.dtd"); examTransformer.setOutputProperty(INDENTATION_KEY, "4"); } catch (ParserConfigurationException e) { logger.error("parser was not configured correctly", e); throw new VaSolSimException(ERROR_MESSAGE_INTERNAL_XML_PARSER_INITIALIZATION_EXCEPTION, e); } catch (TransformerConfigurationException e) { logger.error("transformer was not configured properly"); throw new VaSolSimException(ERROR_MESSAGE_INTERNAL_TRANSFORMER_CONFIGURATION, e); } logger.debug("building document..."); /* * build exam info */ logger.trace("attaching root..."); Element root = examDoc.createElement(XML_ROOT_ELEMENT_NAME); examDoc.appendChild(root); logger.trace("attaching info..."); Element info = examDoc.createElement(XML_INFO_ELEMENT_NAME); root.appendChild(info); //exam info logger.trace("attaching exam info..."); GenericUtils.appendSubNode(XML_TEST_NAME_ELEMENT_NAME, exam.getTestName(), info, examDoc); GenericUtils.appendSubNode(XML_AUTHOR_NAME_ELEMENT_NAME, exam.getAuthorName(), info, examDoc); GenericUtils.appendSubNode(XML_SCHOOL_NAME_ELEMENT_NAME, exam.getSchoolName(), info, examDoc); GenericUtils.appendSubNode(XML_PERIOD_NAME_ELEMENT_NAME, exam.getPeriodName(), info, examDoc); GenericUtils.appendSubNode(XML_DATE_ELEMENT_NAME, exam.getDate(), info, examDoc); //start security xml section logger.trace("attaching security..."); Element security = examDoc.createElement(XML_SECURITY_ELEMENT_NAME); root.appendChild(security); GenericUtils.appendSubNode(XML_ENCRYPTED_VALIDATION_HASH_ELEMENT_NAME, encryptedHash, security, examDoc); GenericUtils.appendSubNode(XML_PARAMETRIC_INITIALIZATION_VECTOR_ELEMENT_NAME, GenericUtils.convertBytesToHexString(encryptionCipher.getIV()), security, examDoc); GenericUtils.appendSubNode(XML_IS_REPORTING_STATISTICS_ELEMENT_NAME, Boolean.toString(exam.isReportingStats()), security, examDoc); GenericUtils.appendSubNode(XML_IS_REPORTING_STATISTICS_STANDALONE_ELEMENT_NAME, Boolean.toString(exam.isReportingStatsStandalone()), security, examDoc); GenericUtils.appendSubNode(XML_STATISTICS_DESTINATION_EMAIL_ADDRESS_ELEMENT_NAME, GenericUtils.convertBytesToHexString(GenericUtils.applyCryptographicCipher( exam.getStatsDestinationEmail() == null ? GenericUtils.NO_EMAIL.getBytes() : exam.getStatsDestinationEmail().getBytes(), encryptionCipher)), security, examDoc); GenericUtils.appendSubNode(XML_STATISTICS_SENDER_EMAIL_ADDRESS_ELEMENT_NAME, GenericUtils.convertBytesToHexString(GenericUtils.applyCryptographicCipher( exam.getStatsSenderEmail() == null ? GenericUtils.NO_EMAIL.getBytes() : exam.getStatsSenderEmail().getBytes(), encryptionCipher)), security, examDoc); GenericUtils.appendSubNode(XML_STATISTICS_SENDER_EMAIL_PASSWORD_ELEMENT_NAME, GenericUtils.convertBytesToHexString(GenericUtils.applyCryptographicCipher( exam.getStatsSenderPassword() == null ? GenericUtils.NO_DATA.getBytes() : exam.getStatsSenderPassword().getBytes(), encryptionCipher)), security, examDoc); GenericUtils.appendSubNode(XML_STATISTICS_SENDER_SMTP_ADDRESS_ELEMENT_NAME, GenericUtils.convertBytesToHexString(GenericUtils.applyCryptographicCipher( exam.getStatsSenderSMTPAddress() == null ? GenericUtils.NO_SMTP.getBytes() : exam.getStatsSenderSMTPAddress().getBytes(), encryptionCipher)), security, examDoc); GenericUtils.appendSubNode(XML_STATISTICS_SENDER_SMTP_PORT_ELEMENT_NAME, GenericUtils.convertBytesToHexString(GenericUtils.applyCryptographicCipher( Integer.toString(exam.getStatsSenderSMTPPort()).getBytes(), encryptionCipher)), security, examDoc); logger.debug("checking exam content integrity..."); ArrayList<QuestionSet> questionSets = exam.getQuestionSets(); if (GenericUtils.checkExamIntegrity(exam).size() == 0) { logger.debug("exporting exam content..."); for (int setsIndex = 0; setsIndex < questionSets.size(); setsIndex++) { QuestionSet qSet = questionSets.get(setsIndex); logger.trace("exporting question set -> " + qSet.getName()); Element qSetElement = examDoc.createElement(XML_QUESTION_SET_ELEMENT_NAME); root.appendChild(qSetElement); GenericUtils.appendSubNode(XML_QUESTION_SET_ID_ELEMENT_NAME, Integer.toString(setsIndex + 1), qSetElement, examDoc); GenericUtils.appendSubNode(XML_QUESTION_SET_NAME_ELEMENT_NAME, (qSet.getName().equals("")) ? "Question Set " + (setsIndex + 1) : qSet.getName(), qSetElement, examDoc); GenericUtils.appendSubNode(XML_QUESTION_SET_RESOURCE_TYPE_ELEMENT_NAME, qSet.getResourceType().toString(), qSetElement, examDoc); if (qSet.getResourceType() != GenericUtils.ResourceType.NONE && qSet.getResources() != null) { logger.debug("exporting question set resources..."); for (BufferedImage img : qSet.getResources()) { if (img != null) { try { logger.trace("writing image..."); ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIO.write(img, "png", out); out.flush(); GenericUtils.appendCDATASubNode(XML_QUESTION_SET_RESOURCE_DATA_ELEMENT_NAME, new String(Base64.encodeBase64(out.toByteArray())), qSetElement, examDoc); } catch (IOException e) { throw new VaSolSimException( "Error: cannot write images to byte array for transport"); } } } } //TODO export problem in this subroutine for (int setIndex = 0; setIndex < qSet.getQuestions().size(); setIndex++) { Question question = qSet.getQuestions().get(setIndex); logger.trace("exporting question -> " + question.getName()); Element qElement = examDoc.createElement(XML_QUESTION_ELEMENT_NAME); qSetElement.appendChild(qElement); logger.trace("question id -> " + setIndex); GenericUtils.appendSubNode(XML_QUESTION_ID_ELEMENT_NAME, Integer.toString(setIndex + 1), qElement, examDoc); logger.trace("question name -> " + question.getName()); GenericUtils.appendSubNode(XML_QUESTION_NAME_ELEMENT_NAME, (question.getName().equals("")) ? "Question " + (setIndex + 1) : question.getName(), qElement, examDoc); logger.trace("question test -> " + question.getQuestion()); GenericUtils.appendSubNode(XML_QUESTION_TEXT_ELEMENT_NAME, question.getQuestion(), qElement, examDoc); logger.trace("question answer scramble -> " + Boolean.toString(question.getScrambleAnswers())); GenericUtils.appendSubNode(XML_QUESTION_SCRAMBLE_ANSWERS_ELEMENT_NAME, Boolean.toString(question.getScrambleAnswers()), qElement, examDoc); logger.trace("question answer order matters -> " + Boolean.toString(question.getAnswerOrderMatters())); GenericUtils.appendSubNode(XML_QUESTION_REATIAN_ANSWER_ORDER_ELEMENT_NAME, Boolean.toString(question.getAnswerOrderMatters()), qElement, examDoc); logger.debug("exporting correct answer choices..."); for (AnswerChoice answer : question.getCorrectAnswerChoices()) { logger.trace("exporting correct answer choice(s) -> " + answer.getAnswerText()); GenericUtils .appendSubNode(XML_QUESTION_ENCRYPTED_ANSWER_HASH, GenericUtils.convertBytesToHexString(GenericUtils.applyCryptographicCipher( answer.getAnswerText().getBytes(), encryptionCipher)), qElement, examDoc); } logger.debug("exporting answer choices..."); for (int questionIndex = 0; questionIndex < question.getAnswerChoices() .size(); questionIndex++) { if (question.getAnswerChoices().get(questionIndex).isActive()) { AnswerChoice ac = question.getAnswerChoices().get(questionIndex); logger.trace("exporting answer choice -> " + ac.getAnswerText()); Element acElement = examDoc.createElement(XML_ANSWER_CHOICE_ELEMENT_NAME); qElement.appendChild(acElement); logger.trace("answer choice id -> " + questionIndex); GenericUtils.appendSubNode(XML_ANSWER_CHOICE_ID_ELEMENT_NAME, Integer.toString(questionIndex + 1), acElement, examDoc); logger.trace("answer choice visible id -> " + ac.getVisibleChoiceID()); GenericUtils.appendSubNode(XML_ANSWER_CHOICE_VISIBLE_ID_ELEMENT_NAME, ac.getVisibleChoiceID(), acElement, examDoc); logger.trace("answer text -> " + ac.getAnswerText()); GenericUtils.appendSubNode(XML_ANSWER_TEXT_ELEMENT_NAME, ac.getAnswerText(), acElement, examDoc); } } } } } else { logger.error("integrity check failed"); PopupManager.showMessage(errorsToOutput(GenericUtils.checkExamIntegrity(exam))); return false; } logger.debug("transforming exam..."); try { examTransformer.transform(new DOMSource(examDoc), new StreamResult(examFile)); } catch (TransformerException e) { logger.error("exam export failed (transformer error)", e); return false; } logger.debug("transformation done"); logger.info("exam export successful"); return true; }
From source file:net.mohatu.bloocoin.miner.Register.java
private void saveBloostamp() { File bloocoinFolder = new File(System.getProperty("user.home") + "/.bloocoin"); if (!bloocoinFolder.exists()) { System.out.println("Creating " + System.getProperty("user.home") + "/.bloocoin" + " directory"); boolean result = bloocoinFolder.mkdir(); if (result) { System.out.println("bloocoin folder created"); }//from w w w.ja v a 2s . c o m } try { PrintWriter out = new PrintWriter( new BufferedWriter(new FileWriter(System.getProperty("user.home") + "/.bloocoin/bloostamp"))); out.print(addr + ":" + key); out.close(); Main.loadDataPub(); } catch (IOException e) { System.out.println("Saving failed:"); e.printStackTrace(); } }