List of usage examples for java.io PrintWriter write
public void write(String s)
From source file:com.globalsight.everest.webapp.pagehandler.administration.users.UserImportHandler.java
/** * Import the user info into system/*from w ww. jav a2 s .c om*/ * * @param request * @param response * @param sessionId */ private void refreshProgress(HttpServletRequest request, HttpServletResponse response, String sessionId) { try { int percentage; if (user_percentage_map.get(sessionId) == null) { percentage = 0; } else { percentage = user_percentage_map.get(sessionId); } String msg; if (user_error_map.get(sessionId) == null) { msg = ""; } else { msg = user_error_map.get(sessionId); } response.setContentType("text/html;charset=UTF-8"); PrintWriter writer = response.getWriter(); writer.write(String.valueOf(percentage + "|" + msg)); writer.close(); } catch (Exception e) { logger.error("Refresh failed.", e); } }
From source file:com.globalsight.everest.projecthandler.MachineTranslateAdapter.java
private boolean testDoMT(MachineTranslationProfile mtProfile, PrintWriter writer) throws JSONException { String url = mtProfile.getUrl(); String engineName = mtProfile.getCategory(); try {/* w w w . j a va 2 s . c o m*/ DoMTUtil.testDoMtHost(url, engineName); } catch (Exception e) { String errString = e.getMessage(); JSONObject jso = new JSONObject(); jso.put("ExceptionInfo", errString); writer.write(jso.toString()); return false; } return true; }
From source file:com.imagelake.android.privilages.Servlet_privilages.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { PrintWriter out = response.getWriter(); try {/*from www .ja v a 2 s. c o m*/ String user_type = request.getParameter("user_type"); if (user_type != null) { if (Integer.parseInt(user_type) != 4) { privilageArray = new JSONArray(); li = pdi.listAll(Integer.parseInt(user_type)); if (!li.isEmpty()) { for (Privilages privilages : li) { if (privilages.getState() == 1) { inf = infs.getInterfaceName(privilages.getInterface_interface_id()); JSONObject jo = new JSONObject(); jo.put("interface", inf.getDisplay_name()); jo.put("imgId", inf.getImg_id()); System.out.println(inf.getImg_id()); privilageArray.add(jo); } } out.write("json=" + privilageArray.toJSONString()); } else { out.write("msg=No privilages."); } } else { out.write("msg=Incorrect user type."); } } else { out.write("msg=User type error."); } } catch (Exception e) { e.printStackTrace(); out.write("msg=Internal server error,Please try again later."); } }
From source file:com.patrolpro.servlet.UploadJasperReportServlet.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*ww w. jav a2 s . c om*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); String companyId = request.getParameter("companyId"); FileItem fileData = null; Integer mobileFormId = null; List<FileItem> fields = upload.parseRequest(request); for (int f = 0; f < fields.size(); f++) { if (fields.get(f).getFieldName().equals("file_data")) { fileData = fields.get(f); } else if (fields.get(f).getFieldName().equals("mobileFormId")) { mobileFormId = Integer.parseInt(fields.get(f).getString()); } } if (fileData == null || !fileData.getName().endsWith(".jrxml")) { out.write("{\"error\": \"Invalid file type! Please select a jrxml (Jasper Report) file!\"}"); out.flush(); } else { InputStream iStream = fileData.getInputStream(); MobileFormService mobileService = new MobileFormService(companyId); ByteArrayOutputStream bOutput = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int bufCount = 0; while ((bufCount = iStream.read(buffer)) > -1) { bOutput.write(buffer, 0, bufCount); } bOutput.flush(); byte[] rawData = bOutput.toByteArray(); JasperReport jasperReport = JasperCompileManager.compileReport(new ByteArrayInputStream(rawData)); JRParameter[] params = jasperReport.getParameters(); HashMap<String, Class> reportParams = new HashMap<String, Class>(); for (int p = 0; p < params.length; p++) { JRParameter param = params[p]; int searchPos = -1; for (int a = 0; a < MobileForms.getReservedIdentifiers().length; a++) { if (MobileForms.getReservedIdentifiers()[a].equals(param.getName())) { searchPos = a; } } if (!param.isSystemDefined() && searchPos < 0 && !param.getName().startsWith("nfc_l_") && !param.getName().endsWith("_loc")) { reportParams.put(param.getName(), param.getValueClass()); } } ByteArrayOutputStream oStream = new ByteArrayOutputStream(); JasperCompileManager.writeReportToXmlStream(jasperReport, oStream); //JasperCompileManager.compileReportToStream(new ByteArrayInputStream(rawData), oStream); MobileForms selectedForm = mobileService.getForm(mobileFormId); selectedForm.setReportData(oStream.toByteArray()); mobileService.saveForm(selectedForm); Iterator<String> keyIterator = reportParams.keySet().iterator(); ArrayList<MobileFormData> currData = mobileService.getFormData(selectedForm.getMobileFormsId()); int numberInserted = 1; while (keyIterator.hasNext()) { String key = keyIterator.next(); boolean hasData = false; for (int d = 0; d < currData.size(); d++) { if (currData.get(d).getDataLabel().equals(key) && currData.get(d).getActive()) { hasData = true; } } if (!hasData) { MobileFormData formData = new MobileFormData(); formData.setActive(true); formData.setMobileFormsId(selectedForm.getMobileFormsId()); formData.setDataLabel(key); if (reportParams.get(key) == Date.class) { formData.setDateType(5); } else if (reportParams.get(key) == InputStream.class) { formData.setDateType(8); } else if (reportParams.get(key) == Boolean.class) { formData.setDateType(3); } else { formData.setDateType(1); } formData.setOrdering(currData.size() + numberInserted); mobileService.saveFormData(formData); numberInserted++; } } out.write("{}"); out.flush(); } } catch (JRException jr) { out.write("{\"error\": \"" + jr.getMessage().replaceAll("\n", "").replaceAll(":", "").replaceAll("\t", "") + "\"}"); out.flush(); } catch (Exception e) { out.write("{\"error\": \"Exception uploading report, " + e + "\"}"); out.flush(); } finally { out.close(); } }
From source file:be.iminds.aiolos.ui.DemoServlet.java
private void getNodeDetails(PrintWriter writer, String nodeId) { JSONObject nodeInfo = new JSONObject(); PlatformManager platform = platformTracker.getService(); if (platform != null) { NodeInfo ni = platform.getNode(nodeId); NodeMonitorInfo nmi = platform.getNodeMonitorInfo(nodeId); if (ni != null) { nodeInfo.put("nodeId", ni.getNodeId()); nodeInfo.put("name", ni.getName()); nodeInfo.put("ip", ni.getIP()); nodeInfo.put("cores", nmi.getNoCpuCores()); nodeInfo.put("cpu", floatFormat.format(nmi.getCpuUsage())); nodeInfo.put("os", ni.getOS()); nodeInfo.put("arch", ni.getArch()); }//from ww w . j a va 2 s .c o m } writer.write(nodeInfo.toJSONString()); }
From source file:net.morphbank.webclient.ProcessFiles.java
public InputStream post(String strURL, String strXMLFilename, PrintWriter out) throws Exception { InputStream response = null;//w w w .j a v a 2 s . c o m File input = new File(strXMLFilename); // Prepare HTTP post PostMethod post = new PostMethod(strURL); // Request content will be retrieved directly // from the input stream Part[] parts = { Part[] parts = { new FilePart("uploadFile", strXMLFilename, input) }; RequestEntity entity = new MultipartRequestEntity(parts, post.getParams()); // RequestEntity entity = new FileRequestEntity(input, // "text/xml;charset=utf-8"); post.setRequestEntity(entity); // Get HTTP client HttpClient httpclient = new HttpClient(); // Execute request try { int result = httpclient.executeMethod(post); // Display status code System.out.println("Response status code: " + result); // Display response response = post.getResponseBodyAsStream(); for (int i = response.read(); i != -1; i = response.read()) { out.write(i); } } finally { // Release current connection to the connection pool once you are // done post.releaseConnection(); } return response; }
From source file:edu.ku.kuali.kra.award.web.struts.action.AwardActionsAction.java
/** * BU KC/SAP Integration: RDFD print functionality. * * @param mapping//ww w . j av a 2 s . c om * - The ActionMapping used to select this instance * @param form * - The optional ActionForm bean for this request (if any) * @param request * - The HTTP request we are processing * @param response * - The HTTP response we are creating * @return an ActionForward instance describing where and how control should be forwarded, or null if the response has already been completed. * @throws Exception * - if an exception occurs */ public ActionForward printAward(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { SapIntegrationService integrationService = KcServiceLocator.getService(SapIntegrationService.class); // call the transmit() method on SAPIntegrationService AwardForm awardForm = (AwardForm) form; Award primaryAward = awardForm.getAwardHierarchyBean().getRootNode().getAward(); // cycle through the award list and only pass on those that have been // marked as approved for transmission ArrayList<Award> awardsList = new ArrayList<Award>(); checkAwardChildren(awardForm.getAwardHierarchyBean().getRootNode(), awardsList, request); SapTransmission transmission = new SapTransmission(primaryAward, awardsList); String transmissionXml = integrationService.getTransmitXml(transmission); transmissionXml = StringUtils.replace(transmissionXml, "ns2:", ""); StringReader xmlReader = new StringReader(transmissionXml); StreamSource xmlSource = new StreamSource(xmlReader); InputStream xslStream = this.getClass() .getResourceAsStream("/edu/bu/kuali/kra/printing/stylesheet/sapPrint.xslt"); StreamSource xslSource = new StreamSource(xslStream); StringWriter resultWriter = new StringWriter(); StreamResult result = new StreamResult(resultWriter); TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(xslSource); transformer.transform(xmlSource, result); PrintWriter out = response.getWriter(); out.write(resultWriter.getBuffer().toString()); return null; }
From source file:com.ephesoft.gxt.admin.server.UploadClassifyExtractFile.java
/** * This API is used to process attach file. * // ww w .j a v a2s . c om * @param req {@link HttpServletRequest}. * @param resp {@link HttpServletResponse}. * @param bSService {@link BatchSchemaService}. * @return */ private void attachFile(final HttpServletRequest req, final HttpServletResponse resp, final BatchSchemaService bSService) throws IOException { final String batchClassIdentifier = req.getParameter(DocumentTypeConstants.BATCH_CLASS_ID_REQ_PARAMETER); final PrintWriter printWriter = resp.getWriter(); String tempFile = null; if (ServletFileUpload.isMultipartContent(req)) { String testTableDirPath = null; if (req.getParameter(DocumentTypeConstants.IS_TEST_CLASSIFICATIONFILE).equalsIgnoreCase("true")) { testTableDirPath = EphesoftStringUtil.concatenate(bSService.getBaseFolderLocation(), File.separator, batchClassIdentifier, File.separator, "test-classification"); } else { testTableDirPath = EphesoftStringUtil.concatenate(bSService.getBaseFolderLocation(), File.separator, batchClassIdentifier, File.separator, "test-extraction"); } final ServletFileUpload upload = getUploadedFile(testTableDirPath); tempFile = processUploadedFile(upload, req, printWriter, testTableDirPath); printWriter.write(tempFile); } else { log.error("Request contents type is not supported."); printWriter.write("Request contents type is not supported."); } printWriter.flush(); }
From source file:com.jayway.maven.plugins.android.AbstractEmulatorMojo.java
/** * Sends a user command to the running emulator via its telnet interface. * * @param port The emulator's telnet port. * @param command The command to execute on the emulator's telnet interface. * @return Whether sending the command succeeded. */// ww w.java 2 s .c om private boolean sendEmulatorCommand( //final Launcher launcher, //final PrintStream logger, final int port, final String command) { Callable<Boolean> task = new Callable<Boolean>() { public Boolean call() throws IOException { Socket socket = null; BufferedReader in = null; PrintWriter out = null; try { socket = new Socket("127.0.0.1", port); out = new PrintWriter(socket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); if (in.readLine() == null) { return false; } out.write(command); out.write("\r\n"); } finally { try { out.close(); in.close(); socket.close(); } catch (Exception e) { // Do nothing } } return true; } private static final long serialVersionUID = 1L; }; boolean result = false; try { ExecutorService executor = Executors.newSingleThreadExecutor(); Future<Boolean> future = executor.submit(task); result = future.get(); } catch (Exception e) { getLog().error(String.format("Failed to execute emulator command '%s': %s", command, e)); } return result; }
From source file:com.googlecode.jmxtrans.model.output.GraphiteWriter.java
@Override public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception { Socket socket = null;//from ww w . ja v a2 s. c o m PrintWriter writer = null; try { socket = pool.borrowObject(address); writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), UTF_8), true); List<String> typeNames = this.getTypeNames(); for (Result result : results) { log.debug("Query result: {}", result); Map<String, Object> resultValues = result.getValues(); for (Entry<String, Object> values : resultValues.entrySet()) { Object value = values.getValue(); if (isValidNumber(value)) { String line = KeyUtils.getKeyString(server, query, result, values, typeNames, rootPrefix) .replaceAll("[()]", "_") + " " + value.toString() + " " + result.getEpoch() / 1000 + "\n"; log.debug("Graphite Message: {}", line); writer.write(line); } else { onlyOnceLogger.infoOnce( "Unable to submit non-numeric value to Graphite: [{}] from result [{}]", value, result); } } } } finally { if (writer != null && writer.checkError()) { log.error("Error writing to Graphite, clearing Graphite socket pool"); pool.invalidateObject(address, socket); } else { pool.returnObject(address, socket); } } }