Java Code Examples for java.io.PrintWriter.write()

The following are Jave code examples for showing how to use write() of the java.io.PrintWriter class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: AEM   File: AbstractExtJSONServlet.java   View Source Code Vote up 7 votes
protected final void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {

    PrintWriter out = response.getWriter();
    try {
        threadLocal = new ThreadLocal<JSONArray>() {
            @Override
            protected JSONArray initialValue() {
                return new JSONArray();
            }
        };
        loadElements(request);
        out.write(threadLocal.get().toString());
    } catch (Exception e) {
        throw new ServletException(e);
    } finally {
        out.flush();
        threadLocal.remove();
    }
}
 
Example 2
Project: uavstack   File: AbsJEEGlobalFilterHandler.java   View Source Code Vote up 7 votes
protected void writeResponseBody(HttpServletResponse response, String data, int returnCode, String encoding) {

        response.setCharacterEncoding(encoding);
        response.setStatus(returnCode);

        try {
            PrintWriter pw = response.getWriter();
            pw.write(data);
            pw.flush();
            pw.close();
        }
        catch (IOException e) {
            logger.error("BaseGlobalFilterHandler[" + getContext() + "] writes response FAIL.", e);
        }

    }
 
Example 3
Project: jboot   File: JbootTextRender.java   View Source Code Vote up 7 votes
public void render() {
    PrintWriter writer = null;
    try {

        RenderHelpler.actionCacheExec(text, contentType);

        response.setHeader("Pragma", "no-cache");    // HTTP/1.0 caches might not implement Cache-Control and might only implement Pragma: no-cache
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        response.setContentType(contentType);
        response.setCharacterEncoding(getEncoding());    // 与 contentType 分开设置

        writer = response.getWriter();
        writer.write(text);
        writer.flush();
    } catch (IOException e) {
        throw new RenderException(e);
    }
}
 
Example 4
Project: Tarski   File: StaticThemeReaderWriter.java   View Source Code Vote up 7 votes
/** Returns the String representation of an AlloyRelation's settings. */
private static String writeEdgeViz(VizState view, VizState defaultView, AlloyRelation x) throws IOException {
   StringWriter sw=new StringWriter();
   PrintWriter out=new PrintWriter(sw);
   writeDotColor(out, view.edgeColor.get(x), defaultView.edgeColor.get(x));
   writeDotStyle(out, view.edgeStyle.get(x), defaultView.edgeStyle.get(x));
   writeBool(out, "visible",   view.edgeVisible.get(x),  defaultView.edgeVisible.get(x));
   writeBool(out, "merge",     view.mergeArrows.get(x),  defaultView.mergeArrows.get(x));
   writeBool(out, "layout",    view.layoutBack.get(x),   defaultView.layoutBack.get(x));
   writeBool(out, "attribute", view.attribute.get(x),    defaultView.attribute.get(x));
   writeBool(out, "constraint",view.constraint.get(x),   defaultView.constraint.get(x));
   if (view.weight.get(x) != defaultView.weight.get(x))  out.write(" weight=\"" + view.weight.get(x) + "\"");
   if (x!=null && !view.label.get(x).equals(defaultView.label.get(x)))
      Util.encodeXMLs(out, " label=\"", view.label.get(x), "\"");
   if (out.checkError()) throw new IOException("PrintWriter IO Exception!");
   return sw.toString();
}
 
Example 5
Project: lams   File: MonitoringAction.java   View Source Code Vote up 7 votes
/**
    * Release mark
    *
    * @param mapping
    * @param form
    * @param request
    * @param response
    * @return
    */
   public ActionForward releaseMarks(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) {

// get service then update report table
submitFilesService = getSubmitFilesService();
Long sessionID = new Long(WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_SESSION_ID));
submitFilesService.releaseMarksForSession(sessionID);

try {
    response.setContentType("text/html;charset=utf-8");
    PrintWriter out = response.getWriter();
    SubmitFilesSession session = submitFilesService.getSessionById(sessionID);
    String sessionName = "";
    if (session != null) {
	sessionName = session.getSessionName();
    }
    out.write(getMessageService().getMessage("msg.mark.released", new String[] { sessionName }));
    out.flush();
} catch (IOException e) {
}
return null;
   }
 
Example 6
Project: neoscada   File: JsonServlet.java   View Source Code Vote up 6 votes
@Override
protected void doPost ( final HttpServletRequest request, final HttpServletResponse response ) throws ServletException, IOException
{
    if ( request.getPathInfo () == null )
    {
        send404Error ( request, response );
        return;
    }
    if ( request.getPathInfo ().equals ( "/publish" ) || request.getPathInfo ().equals ( "/publish/" ) )
    {
        // read input
        final BufferedReader reader = request.getReader ();
        final char[] buffer = new char[4 * 1024];
        int len;
        final StringBuilder sb = new StringBuilder ();
        while ( ( len = reader.read ( buffer, 0, buffer.length ) ) != -1 )
        {
            sb.append ( buffer, 0, len );
        }
        final Event event = EventSerializer.deserializeEvent ( sb.toString () );

        this.injector.injectEvent ( event, new InjectionContext.Builder ().sourceModule ( "org.eclipse.scada.ae.server.http" ).build () );

        // return output
        response.setContentType ( "text/plain" );
        final PrintWriter pw = new PrintWriter ( response.getOutputStream () );
        pw.write ( "OK" );
        pw.close ();
    }
    else
    {
        send404Error ( request, response );
    }
}
 
Example 7
Project: jerrydog   File: SSIFlastmod.java   View Source Code Vote up 6 votes
/**
    * @see SSICommand
    */
   public void process(SSIMediator ssiMediator,
		String[] paramNames,
		String[] paramValues,
		PrintWriter writer) {

String configErrMsg = ssiMediator.getConfigErrMsg();
StringBuffer buf = new StringBuffer();

       for(int i=0;i<paramNames.length;i++) {
    String paramName = paramNames[i];
    String paramValue = paramValues[i];

    try {
	if ( paramName.equalsIgnoreCase("file") ||
	     paramName.equalsIgnoreCase("virtual") ) {
	    boolean virtual = paramName.equalsIgnoreCase("virtual");
	    long lastModified = ssiMediator.getFileLastModified( paramValue,  virtual );
	    Date date = new Date( lastModified );
	    String configTimeFmt = ssiMediator.getConfigTimeFmt();
	    writer.write( formatDate(date, configTimeFmt ) );
	} else {
	    ssiMediator.log("#flastmod--Invalid attribute: " + paramName );
	    writer.write( configErrMsg );
	}	    
    } catch ( IOException e ) {
	ssiMediator.log("#flastmod--Couldn't get last modified for file: " + paramValue, e );
	writer.write( configErrMsg );
    }
}
   }
 
Example 8
Project: IPPR2016   File: ExceptionUtils.java   View Source Code Vote up 6 votes
public static void createUnauthorizedException(final String msg, final ServletResponse res)
    throws IOException {
  ((HttpServletResponse) res).setStatus(401);
  ((HttpServletResponse) res).setHeader("ContentType", "plain/text");
  final PrintWriter writer = ((HttpServletResponse) res).getWriter();
  writer.write(msg);
  writer.close();
}
 
Example 9
Project: apache-tomcat-7.0.73-with-comment   File: SSIFlastmod.java   View Source Code Vote up 6 votes
/**
 * @see SSICommand
 */
@Override
public long process(SSIMediator ssiMediator, String commandName,
        String[] paramNames, String[] paramValues, PrintWriter writer) {
    long lastModified = 0;
    String configErrMsg = ssiMediator.getConfigErrMsg();
    for (int i = 0; i < paramNames.length; i++) {
        String paramName = paramNames[i];
        String paramValue = paramValues[i];
        String substitutedValue = ssiMediator
                .substituteVariables(paramValue);
        try {
            if (paramName.equalsIgnoreCase("file")
                    || paramName.equalsIgnoreCase("virtual")) {
                boolean virtual = paramName.equalsIgnoreCase("virtual");
                lastModified = ssiMediator.getFileLastModified(
                        substitutedValue, virtual);
                Date date = new Date(lastModified);
                String configTimeFmt = ssiMediator.getConfigTimeFmt();
                writer.write(formatDate(date, configTimeFmt));
            } else {
                ssiMediator.log("#flastmod--Invalid attribute: "
                        + paramName);
                writer.write(configErrMsg);
            }
        } catch (IOException e) {
            ssiMediator.log(
                    "#flastmod--Couldn't get last modified for file: "
                            + substitutedValue, e);
            writer.write(configErrMsg);
        }
    }
    return lastModified;
}
 
Example 10
Project: apache-tomcat-7.0.73-with-comment   File: SSIFsize.java   View Source Code Vote up 6 votes
/**
 * @see SSICommand
 */
@Override
public long process(SSIMediator ssiMediator, String commandName,
        String[] paramNames, String[] paramValues, PrintWriter writer) {
    long lastModified = 0;
    String configErrMsg = ssiMediator.getConfigErrMsg();
    for (int i = 0; i < paramNames.length; i++) {
        String paramName = paramNames[i];
        String paramValue = paramValues[i];
        String substitutedValue = ssiMediator
                .substituteVariables(paramValue);
        try {
            if (paramName.equalsIgnoreCase("file")
                    || paramName.equalsIgnoreCase("virtual")) {
                boolean virtual = paramName.equalsIgnoreCase("virtual");
                lastModified = ssiMediator.getFileLastModified(
                        substitutedValue, virtual);
                long size = ssiMediator.getFileSize(substitutedValue,
                        virtual);
                String configSizeFmt = ssiMediator.getConfigSizeFmt();
                writer.write(formatSize(size, configSizeFmt));
            } else {
                ssiMediator.log("#fsize--Invalid attribute: " + paramName);
                writer.write(configErrMsg);
            }
        } catch (IOException e) {
            ssiMediator.log("#fsize--Couldn't get size for file: "
                    + substitutedValue, e);
            writer.write(configErrMsg);
        }
    }
    return lastModified;
}
 
Example 11
Project: ditb   File: MemoryBoundedLogMessageBuffer.java   View Source Code Vote up 6 votes
/**
 * Dump the contents of the buffer to the given stream.
 */
public synchronized void dumpTo(PrintWriter out) {
  SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

  for (LogMessage msg : messages) {
    out.write(df.format(new Date(msg.timestamp)));
    out.write(" ");
    out.println(new String(msg.message, Charsets.UTF_8));
  }
}
 
Example 12
Project: orgzly-android   File: MiscUtils.java   View Source Code Vote up 6 votes
public static void writeStringToFile(String str, File file) throws FileNotFoundException {
    PrintWriter out = new PrintWriter(file);
    try {
        out.write(str);
    } finally {
        out.close();
    }
}
 
Example 13
Project: imputedb   File: QueryPlanDotter.java   View Source Code Vote up 6 votes
public static void print(DbIterator plan, String fileName) throws IOException {
    File f = new File(fileName);
    PrintWriter writer = new PrintWriter(f);
    String graph = QueryPlanDotter.draw(plan);
    writer.write(graph);
    writer.close();
}
 
Example 14
Project: Tarski   File: StaticThemeReaderWriter.java   View Source Code Vote up 6 votes
/** Writes nothing if the value is equal to the default value. */
private static void writeBool(PrintWriter out, String key, Boolean value, Boolean defaultValue) throws IOException {
   if (value==null && defaultValue==null) return;
   if (value!=null && defaultValue!=null && value.booleanValue()==defaultValue.booleanValue()) return;
   out.write(' ');
   out.write(key);
   if (value==null) out.write("=\"inherit\""); else out.write(value ? "=\"yes\"":"=\"no\"");
}
 
Example 15
Project: lazycat   File: StatusTransformer.java   View Source Code Vote up 6 votes
/**
 * 
 */
public static void writeFooter(PrintWriter writer, int mode) {
	if (mode == 0) {
		// HTML Tail Section
		writer.print(Constants.HTML_TAIL_SECTION);
	} else if (mode == 1) {
		writer.write("</status>");
	}
}
 
Example 16
Project: lams   File: SSIInclude.java   View Source Code Vote up 6 votes
/**
 * @see SSICommand
 */
public long process(SSIMediator ssiMediator, String commandName,
        String[] paramNames, String[] paramValues, PrintWriter writer) {
    long lastModified = 0;
    String configErrMsg = ssiMediator.getConfigErrMsg();
    for (int i = 0; i < paramNames.length; i++) {
        String paramName = paramNames[i];
        String paramValue = paramValues[i];
        String substitutedValue = ssiMediator
                .substituteVariables(paramValue);
        try {
            if (paramName.equalsIgnoreCase("file")
                    || paramName.equalsIgnoreCase("virtual")) {
                boolean virtual = paramName.equalsIgnoreCase("virtual");
                lastModified = ssiMediator.getFileLastModified(
                		 substitutedValue, virtual);
                String text = ssiMediator.getFileText(substitutedValue,
                        virtual);
                writer.write(text);
            } else {
                ssiMediator.log("#include--Invalid attribute: "
                        + paramName);
                writer.write(configErrMsg);
            }
        } catch (IOException e) {
            ssiMediator.log("#include--Couldn't include file: "
                    + substitutedValue, e);
            writer.write(configErrMsg);
        }
    }
    return lastModified;
}
 
Example 17
Project: urule   File: URuleServlet.java   View Source Code Vote up 6 votes
private void outContent(HttpServletResponse resp,String msg) throws IOException {
	resp.setContentType("text/html");
	PrintWriter pw=resp.getWriter();
	pw.write("<html>");
	pw.write("<header><title>URule Console</title></header>");
	pw.write("<body>");
	pw.write(msg);
	pw.write("</body>");
	pw.write("</html>");
	pw.flush();
	pw.close();
}
 
Example 18
Project: lams   File: SSIFlastmod.java   View Source Code Vote up 6 votes
/**
 * @see SSICommand
 */
public long process(SSIMediator ssiMediator, String commandName,
        String[] paramNames, String[] paramValues, PrintWriter writer) {
	long lastModified = 0;
    String configErrMsg = ssiMediator.getConfigErrMsg();
    for (int i = 0; i < paramNames.length; i++) {
        String paramName = paramNames[i];
        String paramValue = paramValues[i];
        String substitutedValue = ssiMediator
                .substituteVariables(paramValue);
        try {
            if (paramName.equalsIgnoreCase("file")
                    || paramName.equalsIgnoreCase("virtual")) {
                boolean virtual = paramName.equalsIgnoreCase("virtual");
                lastModified = ssiMediator.getFileLastModified(
                        substitutedValue, virtual);
                Date date = new Date(lastModified);
                String configTimeFmt = ssiMediator.getConfigTimeFmt();
                writer.write(formatDate(date, configTimeFmt));
            } else {
                ssiMediator.log("#flastmod--Invalid attribute: "
                        + paramName);
                writer.write(configErrMsg);
            }
        } catch (IOException e) {
            ssiMediator.log(
                    "#flastmod--Couldn't get last modified for file: "
                            + substitutedValue, e);
            writer.write(configErrMsg);
        }
    }
    return lastModified;
}
 
Example 19
Project: playswith   File: ManifestServlet.java   View Source Code Vote up 5 votes
public void doGet(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException
{
	ServletContext context = getServletContext();
	String[] path = request.getRequestURI().split("/");
	if(path.length < 3)
	{	response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; }
	String action = path[2];
	String file = path[3];
	switch(action)
	{
		case "update":
			switch(file)
			{
				case "catalog":
					updateManifestCatalog(context);
					response.setStatus(HttpServletResponse.SC_NO_CONTENT);
					return;
				case "mobileAssetContent":
					updateManifestCatalog(context);
					updateManifestCacheFile("catalog", _mobileAssetContentCacheFile, "https://www.bungie.net" + mobileAssetContentPathURL, context);
					response.setStatus(HttpServletResponse.SC_NO_CONTENT);
					return;
				case "mobileWorldContent":
					updateManifestCatalog(context);
					updateManifestCacheFile("catalog", _mobileWorldContentCacheFile, "https://www.bungie.net" + mobileWorldContentPathsURL, context);
					response.setStatus(HttpServletResponse.SC_NO_CONTENT);
					return;
			}
			break;
		case "fetch":
			if(path.length < 4)
			{	response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; }
			String type = path[4];
			String databasePath;
			switch(file)
			{
				case "mobileAssetContent": databasePath = Paths.get(_filesCacheDir,_mobileAssetContentCacheFile).toString(); break;
				case "mobileWorldContent": databasePath = Paths.get(_filesCacheDir,_mobileWorldContentCacheFile).toString(); break;
				default:
					response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
					return;
			}
			String val = null;
			if(path.length > 5)
			{
				String id = path[5];
				if(id != null && id.matches("-?\\d+"))
				{
					val = ManifestCache.getValue(databasePath, type, Long.parseLong(id));
				} else {
					val = ManifestCache.getValue(databasePath, type, id);
				}
			} else {
				val = ManifestCache.getValue(databasePath, type);
			}
			if(val == null)
			{
				response.setStatus(HttpServletResponse.SC_NOT_FOUND);
			} else {
				response.setStatus(HttpServletResponse.SC_OK);
				response.setContentType("application/json");
				response.setCharacterEncoding("utf-8");
				PrintWriter out = response.getWriter();
				out.write(val);
				out.close();
			}
			return;
	}
	response.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
 
Example 20
Project: logistimo-web-service   File: LocationConfigServlet.java   View Source Code Vote up 5 votes
private void writeResponse(PrintWriter pw, String responseText) {
  pw.write(responseText);
  pw.close();
}