List of usage examples for java.io PrintWriter write
public void write(String s)
From source file:controllers.IndexServlet.java
private static void Upload(HttpServletRequest request, HttpServletResponse response, PrintWriter writer) { response.setContentType("text/plain"); try {/*from w ww. j a va2 s . c o m*/ Part httpPostedFile = request.getPart("file"); String fileName = ""; for (String content : httpPostedFile.getHeader("content-disposition").split(";")) { if (content.trim().startsWith("filename")) { fileName = content.substring(content.indexOf('=') + 1).trim().replace("\"", ""); } } long curSize = httpPostedFile.getSize(); if (DocumentManager.GetMaxFileSize() < curSize || curSize <= 0) { writer.write("{ \"error\": \"File size is incorrect\"}"); return; } String curExt = FileUtility.GetFileExtension(fileName); if (!DocumentManager.GetFileExts().contains(curExt)) { writer.write("{ \"error\": \"File type is not supported\"}"); return; } InputStream fileStream = httpPostedFile.getInputStream(); fileName = DocumentManager.GetCorrectName(fileName); String fileStoragePath = DocumentManager.StoragePath(fileName, null); File file = new File(fileStoragePath); try (FileOutputStream out = new FileOutputStream(file)) { int read; final byte[] bytes = new byte[1024]; while ((read = fileStream.read(bytes)) != -1) { out.write(bytes, 0, read); } out.flush(); } writer.write("{ \"filename\": \"" + fileName + "\"}"); } catch (IOException | ServletException e) { writer.write("{ \"error\": \"" + e.getMessage() + "\"}"); } }
From source file:com.dien.upload.server.UploadServlet.java
protected static void renderJSONResponse(HttpServletRequest request, HttpServletResponse response, String message) throws IOException { //json????/*from w w w . j a v a 2 s. c o m*/ response.setContentType("text/html;charset=utf-8"); PrintWriter out; try { out = response.getWriter(); out.write(message); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.dien.upload.server.UploadServlet.java
/** * Writes a XML response to the client. * The message must be a text which will be wrapped in an XML structure. * /*from w w w .jav a 2 s .c o m*/ * Note: if the request is a POST, the response should set the content type * to text/html or text/plain in order to be able in the client side to * read the iframe body (submitCompletEvent.getResults()), otherwise the * method returns null * * @param request * @param response * @param message * @param post * specify whether the request is post or not. * @throws IOException */ protected static void renderXmlResponse(HttpServletRequest request, HttpServletResponse response, String message, boolean post) throws IOException { //json???? response.setContentType("text/html;charset=utf-8"); PrintWriter out; try { out = response.getWriter(); out.write("<html><body><textarea>" + message + "</textarea></body></html>"); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.jsmartframework.web.manager.WebContext.java
/** * Write response directly as String. Note that by using this method the response * as HTML will not be generated and the response will be what you have defined. * * @param response String to write in the response. * @throws IOException//from w ww .j a va2s. c o m */ public static void writeResponseAsString(String response) throws IOException { WebContext context = getCurrentInstance(); if (context != null) { context.responseWritten = true; PrintWriter writer = context.response.getWriter(); writer.write(response); writer.flush(); } }
From source file:com.jsmartframework.web.manager.WebContext.java
/** * Write response directly as JSON from Object. Note that by using this method the response * as HTML will not be generated and the response will be what you have defined. * * @param object Object to convert into JSON to write in the response. * @param gson Gson instance to be used to convert object into JSON. * @throws IOException/* ww w. ja va 2 s.com*/ */ public static void writeResponseAsJson(Object object, Gson gson) throws IOException { WebContext context = getCurrentInstance(); if (context != null) { context.responseWritten = true; context.response.setContentType("application/json"); PrintWriter writer = context.response.getWriter(); writer.write(gson.toJson(object)); writer.flush(); } }
From source file:com.iitb.cse.Utils.java
public static boolean startExperiment(int expId, String timeout, String logBgTraffic) { File file = null;/*www . j a v a2 s .c o m*/ File file1 = null; if (Constants.experimentDetailsDirectory.endsWith("/")) { file = new File(Constants.experimentDetailsDirectory + Constants.currentSession.getCurrentExperimentId() + "/" + Constants.configFile); file1 = new File( Constants.experimentDetailsDirectory + Constants.currentSession.getCurrentExperimentId()); } else { file = new File(Constants.experimentDetailsDirectory + "/" + Constants.currentSession.getCurrentExperimentId() + "/" + Constants.configFile); file1 = new File( Constants.experimentDetailsDirectory + "/" + Constants.currentSession.getCurrentExperimentId()); } if (file.exists()) { Charset charset = Charset.forName("UTF-8"); String line = null; String[] data = new String[1000];// int index = 0; data[index] = ""; try { BufferedReader reader = Files.newBufferedReader(file.toPath(), charset); Calendar cal = Calendar.getInstance(); while ((line = reader.readLine()) != null) { System.out.println("\nLENGTH : " + line.length()); if (line.isEmpty() || line.trim().equals("")) { System.out.println("\nCASE1"); continue; } else if (line.trim().equals("*****\n")) { System.out.println("\nCASE2"); data[index] = expId + "\n" + data[index]; index++; data[index] = ""; continue; } else if (line.trim().equals("*****")) { System.out.println("\nCASE3"); data[index] = expId + "\n" + data[index]; index++; data[index] = ""; continue; } String[] lineVariables = line.split(" "); // int offset = Integer.parseInt(lineVariables[1]); // cal.add(Calendar.SECOND, offset); //**************************************************** double time = Double.parseDouble(lineVariables[1]); int sec = (int) time; double rem = time % 1; int remainder = (int) (rem * 1000); // Calendar cal = Calendar.getInstance(); // System.out.println("\nSec : " + sec + "\nMiSec : " + remainder + "\nTime : " + cal.getTime()); int flag = 0; if (remainder < 100) { flag = 1; remainder = remainder + 100; cal.add(Calendar.SECOND, sec); cal.add(Calendar.MILLISECOND, remainder); cal.add(Calendar.MILLISECOND, -100); } else { cal.add(Calendar.SECOND, sec); cal.add(Calendar.MILLISECOND, remainder); } //**************************************************** if (lineVariables.length == 5) { // System.out.println("\nINSIDE"); data[index] += generateLine(cal, lineVariables[2], lineVariables[0], lineVariables[3], lineVariables[4]); } else { // System.out.println("\nOUTSIDE"); data[index] += generateLine(cal, lineVariables[2], lineVariables[0], lineVariables[3]); } if (flag == 1) { cal.add(Calendar.SECOND, -1 * sec); cal.add(Calendar.MILLISECOND, -1 * remainder); cal.add(Calendar.MILLISECOND, 100); } else { cal.add(Calendar.SECOND, -1 * sec); cal.add(Calendar.MILLISECOND, -1 * remainder); } } data[index] = expId + "\n" + data[index]; } catch (IOException ex) { System.out.println(ex.toString()); return false; } int controlFileIndex = 0; for (DeviceInfo d : Constants.currentSession.getFilteredClients()) { if (controlFileIndex >= Constants.currentSession.getFilteredClients().size()) { break; } else if (data[controlFileIndex] != null) { String jsonString = Utils.getControlFileJson(data[controlFileIndex], timeout, logBgTraffic); System.out.println("\njsonString : " + jsonString); System.out.println("\nControl FIle : " + data[controlFileIndex]); /* Locally keep the corresponding control file to each client*/ PrintWriter writer; try { writer = new PrintWriter(file1 + "/" + d.macAddress + "_confFile"); writer.write(data[controlFileIndex]); writer.flush(); writer.close(); } catch (FileNotFoundException ex) { System.out.println("\nException : " + ex.toString()); } //writer.close(); System.out.println("\nDevice Info : IP " + d.ip + " Port " + d.port + " Mac " + d.macAddress); Thread sendData = new Thread(new SendData(expId, d, 0, jsonString, data[controlFileIndex])); sendData.start(); } else { break; } controlFileIndex++; } } else { System.out.println("\nConfig FIle not found in location : " + Constants.experimentDetailsDirectory + Constants.currentSession.getCurrentExperimentId()); } return true; }
From source file:com.jsmartframework.web.manager.WebContext.java
/** * Write response directly as Event-Stream for Server Sent Events. * * @param asyncContext - Asynchronous Context. * @param event - Name of event to be written on response. * @param data - Content of event ot be written on response. * @param retry - Time in (milliseconds) for client retry opening connection. * after asynchronous context is closed. * @throws IOException//from w ww.j av a2s .co m */ public static void writeResponseAsEventStream(AsyncContext asyncContext, String event, Object data, Long retry) throws IOException { if (asyncContext != null && event != null && data != null) { HttpServletResponse response = (HttpServletResponse) asyncContext.getResponse(); response.setContentType("text/event-stream"); PrintWriter printWriter = response.getWriter(); if (retry != null) { printWriter.write("retry:" + retry + "\n"); } printWriter.write("event:" + event + "\n"); printWriter.write("data:" + data + "\n\n"); printWriter.flush(); } }
From source file:io.selendroid.android.impl.DefaultAndroidEmulator.java
private static Map<String, Integer> mapDeviceNamesToSerial() { Map<String, Integer> mapping = new HashMap<String, Integer>(); CommandLine command = new CommandLine(AndroidSdk.adb()); command.addArgument("devices"); Scanner scanner;//from w w w.ja v a 2s.c om try { scanner = new Scanner(ShellCommand.exec(command)); } catch (ShellCommandException e) { return mapping; } while (scanner.hasNextLine()) { String line = scanner.nextLine(); Pattern pattern = Pattern.compile("emulator-\\d\\d\\d\\d"); Matcher matcher = pattern.matcher(line); if (matcher.find()) { String serial = matcher.group(0); Integer port = Integer.valueOf(serial.replaceAll("emulator-", "")); TelnetClient client = null; try { client = new TelnetClient(port); String avdName = client.sendCommand("avd name"); mapping.put(avdName, port); } catch (AndroidDeviceException e) { // ignore } finally { if (client != null) { client.close(); } } Socket socket = null; PrintWriter out = null; BufferedReader in = 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) { throw new AndroidDeviceException("error"); } out.write("avd name\r\n"); out.flush(); in.readLine();// OK String avdName = in.readLine(); mapping.put(avdName, port); } catch (Exception e) { // ignore } finally { try { out.close(); in.close(); socket.close(); } catch (Exception e) { // do nothing } } } } scanner.close(); return mapping; }
From source file:fi.helsinki.opintoni.security.AuthFailureHandler.java
@Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); PrintWriter writer = response.getWriter(); writer.write(exception.getMessage()); writer.flush();// ww w.j av a 2 s . c om }
From source file:sct.ApplicationContextNamespaceTestServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { XmlWebApplicationContext ctx = new XmlWebApplicationContext(); ClassLoader loader = Thread.currentThread().getContextClassLoader(); ctx.setClassLoader(loader);//from www.j a v a2 s . com ctx.setConfigLocation("classpath:sct/namespace.xml"); ctx.refresh(); Object bean = ctx.getBean("someBean"); if (bean != null) { PrintWriter writer = resp.getWriter(); writer.write("OK"); writer.flush(); } }