use of java.io.Writer in project tomcat by apache.
the class WsRemoteEndpointImplBase method sendObjectByCompletion.
@SuppressWarnings({ "unchecked", "rawtypes" })
public void sendObjectByCompletion(Object obj, SendHandler completion) {
if (obj == null) {
throw new IllegalArgumentException(sm.getString("wsRemoteEndpoint.nullData"));
}
if (completion == null) {
throw new IllegalArgumentException(sm.getString("wsRemoteEndpoint.nullHandler"));
}
/*
* Note that the implementation will convert primitives and their object
* equivalents by default but that users are free to specify their own
* encoders and decoders for this if they wish.
*/
Encoder encoder = findEncoder(obj);
if (encoder == null && Util.isPrimitive(obj.getClass())) {
String msg = obj.toString();
sendStringByCompletion(msg, completion);
return;
}
if (encoder == null && byte[].class.isAssignableFrom(obj.getClass())) {
ByteBuffer msg = ByteBuffer.wrap((byte[]) obj);
sendBytesByCompletion(msg, completion);
return;
}
try {
if (encoder instanceof Encoder.Text) {
String msg = ((Encoder.Text) encoder).encode(obj);
sendStringByCompletion(msg, completion);
} else if (encoder instanceof Encoder.TextStream) {
try (Writer w = getSendWriter()) {
((Encoder.TextStream) encoder).encode(obj, w);
}
completion.onResult(new SendResult());
} else if (encoder instanceof Encoder.Binary) {
ByteBuffer msg = ((Encoder.Binary) encoder).encode(obj);
sendBytesByCompletion(msg, completion);
} else if (encoder instanceof Encoder.BinaryStream) {
try (OutputStream os = getSendStream()) {
((Encoder.BinaryStream) encoder).encode(obj, os);
}
completion.onResult(new SendResult());
} else {
throw new EncodeException(obj, sm.getString("wsRemoteEndpoint.noEncoder", obj.getClass()));
}
} catch (Exception e) {
SendResult sr = new SendResult(e);
completion.onResult(sr);
}
}
use of java.io.Writer in project tomcat by apache.
the class WsRemoteEndpointImplBase method sendObject.
@SuppressWarnings({ "unchecked", "rawtypes" })
public void sendObject(Object obj) throws IOException, EncodeException {
if (obj == null) {
throw new IllegalArgumentException(sm.getString("wsRemoteEndpoint.nullData"));
}
/*
* Note that the implementation will convert primitives and their object
* equivalents by default but that users are free to specify their own
* encoders and decoders for this if they wish.
*/
Encoder encoder = findEncoder(obj);
if (encoder == null && Util.isPrimitive(obj.getClass())) {
String msg = obj.toString();
sendString(msg);
return;
}
if (encoder == null && byte[].class.isAssignableFrom(obj.getClass())) {
ByteBuffer msg = ByteBuffer.wrap((byte[]) obj);
sendBytes(msg);
return;
}
if (encoder instanceof Encoder.Text) {
String msg = ((Encoder.Text) encoder).encode(obj);
sendString(msg);
} else if (encoder instanceof Encoder.TextStream) {
try (Writer w = getSendWriter()) {
((Encoder.TextStream) encoder).encode(obj, w);
}
} else if (encoder instanceof Encoder.Binary) {
ByteBuffer msg = ((Encoder.Binary) encoder).encode(obj);
sendBytes(msg);
} else if (encoder instanceof Encoder.BinaryStream) {
try (OutputStream os = getSendStream()) {
((Encoder.BinaryStream) encoder).encode(obj, os);
}
} else {
throw new EncodeException(obj, sm.getString("wsRemoteEndpoint.noEncoder", obj.getClass()));
}
}
use of java.io.Writer in project tomcat by apache.
the class TestHttp11Processor method testRequestBodySwallowing.
/*
* Tests what happens if a request is completed during a dispatch but the
* request body has not been fully read.
*/
@Test
public void testRequestBodySwallowing() throws Exception {
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
Context ctx = tomcat.addContext("", null);
DispatchingServlet servlet = new DispatchingServlet();
Wrapper w = Tomcat.addServlet(ctx, "Test", servlet);
w.setAsyncSupported(true);
ctx.addServletMappingDecoded("/test", "Test");
tomcat.start();
// Hand-craft the client so we have complete control over the timing
SocketAddress addr = new InetSocketAddress("localhost", getPort());
Socket socket = new Socket();
socket.setSoTimeout(300000);
socket.connect(addr, 300000);
OutputStream os = socket.getOutputStream();
Writer writer = new OutputStreamWriter(os, "ISO-8859-1");
InputStream is = socket.getInputStream();
Reader r = new InputStreamReader(is, "ISO-8859-1");
BufferedReader reader = new BufferedReader(r);
// Write the headers
writer.write("POST /test HTTP/1.1\r\n");
writer.write("Host: localhost:8080\r\n");
writer.write("Transfer-Encoding: chunked\r\n");
writer.write("\r\n");
writer.flush();
validateResponse(reader);
// Write the request body
writer.write("2\r\n");
writer.write("AB\r\n");
writer.write("0\r\n");
writer.write("\r\n");
writer.flush();
// Write the 2nd request
writer.write("POST /test HTTP/1.1\r\n");
writer.write("Host: localhost:8080\r\n");
writer.write("Transfer-Encoding: chunked\r\n");
writer.write("\r\n");
writer.flush();
// Read the 2nd response
validateResponse(reader);
// Write the 2nd request body
writer.write("2\r\n");
writer.write("AB\r\n");
writer.write("0\r\n");
writer.write("\r\n");
writer.flush();
// Done
socket.close();
}
use of java.io.Writer in project whirr by apache.
the class HadoopServiceTest method test.
@Test
public void test() throws Exception {
Configuration conf = getConfiguration();
JobConf job = new JobConf(conf, HadoopServiceTest.class);
JobClient client = new JobClient(job);
waitForTaskTrackers(client);
FileSystem fs = FileSystem.get(conf);
OutputStream os = fs.create(new Path("input"));
Writer wr = new OutputStreamWriter(os);
wr.write("b a\n");
wr.close();
job.setMapperClass(TokenCountMapper.class);
job.setReducerClass(LongSumReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(LongWritable.class);
FileInputFormat.setInputPaths(job, new Path("input"));
FileOutputFormat.setOutputPath(job, new Path("output"));
JobClient.runJob(job);
FSDataInputStream in = fs.open(new Path("output/part-00000"));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
assertEquals("a\t1", reader.readLine());
assertEquals("b\t1", reader.readLine());
assertNull(reader.readLine());
reader.close();
}
use of java.io.Writer in project tomcat by apache.
the class ErrorReportValve method report.
// ------------------------------------------------------ Protected Methods
/**
* Prints out an error report.
*
* @param request The request being processed
* @param response The response being generated
* @param throwable The exception that occurred (which possibly wraps
* a root cause exception
*/
protected void report(Request request, Response response, Throwable throwable) {
int statusCode = response.getStatus();
// and that error has not been reported.
if (statusCode < 400 || response.getContentWritten() > 0 || !response.setErrorReported()) {
return;
}
String message = RequestUtil.filter(response.getMessage());
if (message == null) {
if (throwable != null) {
String exceptionMessage = throwable.getMessage();
if (exceptionMessage != null && exceptionMessage.length() > 0) {
message = RequestUtil.filter((new Scanner(exceptionMessage)).nextLine());
}
}
if (message == null) {
message = "";
}
}
// Do nothing if there is no reason phrase for the specified status code and
// no error message provided
String reason = null;
String description = null;
StringManager smClient = StringManager.getManager(Constants.Package, request.getLocales());
response.setLocale(smClient.getLocale());
try {
reason = smClient.getString("http." + statusCode + ".reason");
description = smClient.getString("http." + statusCode + ".desc");
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
}
if (reason == null || description == null) {
if (message.isEmpty()) {
return;
} else {
reason = smClient.getString("errorReportValve.unknownReason");
description = smClient.getString("errorReportValve.noDescription");
}
}
StringBuilder sb = new StringBuilder();
sb.append("<!doctype html><html lang=\"");
sb.append(smClient.getLocale().getLanguage()).append("\">");
sb.append("<head>");
sb.append("<title>");
sb.append(smClient.getString("errorReportValve.statusHeader", String.valueOf(statusCode), reason));
sb.append("</title>");
sb.append("<style type=\"text/css\">");
sb.append(TomcatCSS.TOMCAT_CSS);
sb.append("</style>");
sb.append("</head><body>");
sb.append("<h1>");
sb.append(smClient.getString("errorReportValve.statusHeader", String.valueOf(statusCode), reason)).append("</h1>");
if (isShowReport()) {
sb.append("<hr class=\"line\" />");
sb.append("<p><b>");
sb.append(smClient.getString("errorReportValve.type"));
sb.append("</b> ");
if (throwable != null) {
sb.append(smClient.getString("errorReportValve.exceptionReport"));
} else {
sb.append(smClient.getString("errorReportValve.statusReport"));
}
sb.append("</p>");
if (!message.isEmpty()) {
sb.append("<p><b>");
sb.append(smClient.getString("errorReportValve.message"));
sb.append("</b> ");
sb.append(message).append("</p>");
}
sb.append("<p><b>");
sb.append(smClient.getString("errorReportValve.description"));
sb.append("</b> ");
sb.append(description);
sb.append("</p>");
if (throwable != null) {
String stackTrace = getPartialServletStackTrace(throwable);
sb.append("<p><b>");
sb.append(smClient.getString("errorReportValve.exception"));
sb.append("</b></p><pre>");
sb.append(RequestUtil.filter(stackTrace));
sb.append("</pre>");
int loops = 0;
Throwable rootCause = throwable.getCause();
while (rootCause != null && (loops < 10)) {
stackTrace = getPartialServletStackTrace(rootCause);
sb.append("<p><b>");
sb.append(smClient.getString("errorReportValve.rootCause"));
sb.append("</b></p><pre>");
sb.append(RequestUtil.filter(stackTrace));
sb.append("</pre>");
// In case root cause is somehow heavily nested
rootCause = rootCause.getCause();
loops++;
}
sb.append("<p><b>");
sb.append(smClient.getString("errorReportValve.note"));
sb.append("</b> ");
sb.append(smClient.getString("errorReportValve.rootCauseInLogs"));
sb.append("</p>");
}
sb.append("<hr class=\"line\" />");
}
if (isShowServerInfo()) {
sb.append("<h3>").append(ServerInfo.getServerInfo()).append("</h3>");
}
sb.append("</body></html>");
try {
try {
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
if (container.getLogger().isDebugEnabled()) {
container.getLogger().debug("status.setContentType", t);
}
}
Writer writer = response.getReporter();
if (writer != null) {
// If writer is null, it's an indication that the response has
// been hard committed already, which should never happen
writer.write(sb.toString());
response.finishResponse();
}
} catch (IOException e) {
// Ignore
} catch (IllegalStateException e) {
// Ignore
}
}
Aggregations