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

The following are Jave code examples for showing how to use print() 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: apache-tomcat-7.0.73-with-comment   File: TestAbstractHttp11Processor.java   View Source Code Vote up 9 votes
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    resp.setContentType("text/plain");
    resp.setCharacterEncoding("UTF-8");
    if (!useChunks) {
        // Longer than it needs to be because response will fail before
        // it is complete
        resp.setContentLength(100);
    }
    PrintWriter pw = resp.getWriter();
    pw.print("line01");
    pw.flush();
    resp.flushBuffer();
    pw.print("line02");
    pw.flush();
    resp.flushBuffer();
    pw.print("line03");

    // Now throw a RuntimeException to end this request
    throw new ServletException("Deliberate failure");
}
 
Example 2
Project: hadoop   File: TimedOutTestsListener.java   View Source Code Vote up 7 votes
private static void printThread(ThreadInfo ti, PrintWriter out) {
  out.print("\"" + ti.getThreadName() + "\"" + " Id="
      + ti.getThreadId() + " in " + ti.getThreadState());
  if (ti.getLockName() != null) {
    out.print(" on lock=" + ti.getLockName());
  }
  if (ti.isSuspended()) {
    out.print(" (suspended)");
  }
  if (ti.isInNative()) {
    out.print(" (running in native)");
  }
  out.println();
  if (ti.getLockOwnerName() != null) {
    out.println(INDENT + " owned by " + ti.getLockOwnerName() + " Id="
        + ti.getLockOwnerId());
  }
}
 
Example 3
Project: openjdk-jdk10   File: UnionGen.java   View Source Code Vote up 7 votes
private int readBranch (int index, String indent, String name, String disName, TypedefEntry entry, PrintWriter stream)
{
    SymtabEntry type = entry.type ();
    Util.writeInitializer (indent, '_' + name, "", entry, stream);

    if (!entry.arrayInfo ().isEmpty () ||
        type instanceof SequenceEntry ||
        type instanceof PrimitiveEntry ||
        type instanceof StringEntry) {
        index = ((JavaGenerator)entry.generator ()).read (index, indent, '_' + name, entry, stream);
    } else {
        stream.println (indent + '_' + name + " = " + Util.helperName (type, true) + ".read (istream);");
    }

    stream.print (indent + "value." + name + " (");
    if( disName == "" )
        stream.println("_" + name + ");");
    else
        stream.println(disName + ", " + "_" + name + ");");

    return index;
}
 
Example 4
Project: tomcat7   File: TestNamingContext.java   View Source Code Vote up 7 votes
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    resp.setContentType("text/plain;UTF-8");
    PrintWriter out = resp.getWriter();

    try {
        Context ctx = new InitialContext();
        Object obj = ctx.lookup("java:comp/env/bug50351");
        TesterObject to = (TesterObject) obj;
        out.print(to.getFoo());
    } catch (NamingException ne) {
        ne.printStackTrace(out);
    }
}
 
Example 5
Project: hadoop   File: TestClusterCLI.java   View Source Code Vote up 7 votes
@Test
public void testGetClusterNodeLabelsWithLocalAccess() throws Exception {
  YarnClient client = mock(YarnClient.class);
  when(client.getClusterNodeLabels()).thenReturn(
      ImmutableSet.of("remote1", "remote2"));
  ClusterCLI cli = new ClusterCLI();
  cli.setClient(client);
  cli.setSysOutPrintStream(sysOut);
  cli.setSysErrPrintStream(sysErr);
  ClusterCLI.localNodeLabelsManager = mock(CommonNodeLabelsManager.class);
  when(ClusterCLI.localNodeLabelsManager.getClusterNodeLabels())
      .thenReturn(ImmutableSet.of("local1", "local2"));

  int rc =
      cli.run(new String[] { ClusterCLI.CMD,
          "-" + ClusterCLI.LIST_LABELS_CMD,
          "-" + ClusterCLI.DIRECTLY_ACCESS_NODE_LABEL_STORE });
  assertEquals(0, rc);

  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  PrintWriter pw = new PrintWriter(baos);
  // it should return local* instead of remote*
  pw.print("Node Labels: local1,local2");
  pw.close();
  verify(sysOut).println(baos.toString("UTF-8"));
}
 
Example 6
Project: https-github.com-apache-zookeeper   File: ReadOnlyZooKeeperServer.java   View Source Code Vote up 7 votes
@Override
public void dumpConf(PrintWriter pwriter) {
    super.dumpConf(pwriter);

    pwriter.print("initLimit=");
    pwriter.println(self.getInitLimit());
    pwriter.print("syncLimit=");
    pwriter.println(self.getSyncLimit());
    pwriter.print("electionAlg=");
    pwriter.println(self.getElectionType());
    pwriter.print("electionPort=");
    pwriter.println(self.getElectionAddress().getPort());
    pwriter.print("quorumPort=");
    pwriter.println(self.getQuorumAddress().getPort());
    pwriter.print("peerType=");
    pwriter.println(self.getLearnerType().ordinal());
}
 
Example 7
Project: boohee_v5.6   File: FragmentActivity.java   View Source Code Vote up 7 votes
private void dumpViewHierarchy(String prefix, PrintWriter writer, View view) {
    writer.print(prefix);
    if (view == null) {
        writer.println("null");
        return;
    }
    writer.println(viewToString(view));
    if (view instanceof ViewGroup) {
        ViewGroup grp = (ViewGroup) view;
        int N = grp.getChildCount();
        if (N > 0) {
            prefix = prefix + "  ";
            for (int i = 0; i < N; i++) {
                dumpViewHierarchy(prefix, writer, grp.getChildAt(i));
            }
        }
    }
}
 
Example 8
Project: incubator-netbeans   File: ClassIndexTest.java   View Source Code Vote up 7 votes
private FileObject createJavaFile (
        final FileObject root,
        final String pkg,
        final String name,
        final String content) throws IOException {
        final FileObject file = FileUtil.createData(
            root,
            String.format("%s/%s.java",
                FileObjects.convertPackage2Folder(pkg),
                name));
        final FileLock lck = file.lock();
        try {
            final PrintWriter out = new PrintWriter (new OutputStreamWriter(file.getOutputStream(lck)));
            try {
                out.print(content);
            } finally {
                out.close();
            }
        } finally {
            lck.releaseLock();
        }
        return file;
}
 
Example 9
Project: neoscada   File: ListServlet.java   View Source Code Vote up 6 votes
private void showConfigurations ( final HttpServletResponse resp, final ConfigurationAdministrator admin, final String factoryId, final Configuration[] configurations ) throws IOException
{
    final PrintWriter stream = resp.getWriter ();
    stream.print ( "<table class='configuration' width='100%'>" );
    stream.print ( "<tr><th>ID</th><th>State</th><th>Error</th><th>Data</th></tr>" );

    Arrays.sort ( configurations, new Comparator<Configuration> () {

        @Override
        public int compare ( final Configuration o1, final Configuration o2 )
        {
            return o1.getId ().compareTo ( o2.getId () );
        }
    } );

    for ( final Configuration cfg : configurations )
    {
        stream.print ( "<tr>" );
        stream.print ( String.format ( "<td>%s</td>", cfg.getId () ) );
        stream.print ( String.format ( "<td>%s</td>", cfg.getState () ) );
        if ( cfg.getErrorInformation () != null )
        {
            stream.print ( String.format ( "<td>%s</td>", cfg.getErrorInformation ().getMessage () ) );
        }
        else
        {
            stream.print ( String.format ( "<td></td>" ) );
        }
        stream.print ( "<td><div style='float:right;'>" );

        showData ( stream, cfg.getData (), factoryId, cfg.getId () );

        stream.print ( "<form method='post'><input type='Submit' value='Delete' name='cmd_delete' /><input type='hidden' name='factoryId' value='" + factoryId + "' /><input type='hidden' name='configurationId' value=" + cfg.getId () + " /></form>" );
        stream.print ( "</div></td>" );

        stream.print ( "</tr>" );
    }

    stream.print ( "</table>" );
}
 
Example 10
Project: tomcat7   File: DuplicateMappingParamServlet.java   View Source Code Vote up 6 votes
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res)
        throws IOException, ServletException {
    PrintWriter out = res.getWriter();
    out.print("<p>" + getInitParameter("foo") + " "
            + getInitParameter("bar") + "</p>");
}
 
Example 11
Project: monarch   File: StatArchiveReader.java   View Source Code Vote up 6 votes
void dump(PrintWriter stream) {
  stream.print("[size=" + count);
  for (int i = 0; i < count; i++) {
    if (i != 0) {
      stream.print(", ");
      stream.print(timeStamps[i] - timeStamps[i - 1]);
    } else {
      stream.print(" " + timeStamps[i]);
    }
  }
  stream.println("]");
}
 
Example 12
Project: hotelbook-JavaWeb   File: UpdatePwdServlet.java   View Source Code Vote up 6 votes
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    request.setCharacterEncoding("utf-8");
    response.setContentType("text/html;charset=utf-8");
    PrintWriter out = response.getWriter();

    // 调用service
    LoginService service = new LoginServiceImpl();
    MD5 md5 = new MD5();

    // 获得姓名
    String loginName = request.getParameter("loginName");
    String loginPwd = request.getParameter("loginPwd");  //转成MD5存储

    Login login;
    int check = -1;

    try {
        login = service.queryLogin(loginName);
        System.out.println(login);
        login.setLoginPwd(loginPwd);
        System.out.println(login);
        check = service.updateLogin(login);
        System.out.println(check);
        System.out.println(service.queryLogin(loginName));
    } catch (SQLException e) {
        e.printStackTrace();
    }
    Gson gson = new Gson();
    out.print(gson.toJson(check));
}
 
Example 13
Project: parabuild-ci   File: TestHandler.java   View Source Code Vote up 6 votes
public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException
{
    String scriptName = request.getPathInfo();
    scriptName = LocalUtil.replace(scriptName, testHandlerUrl, "");
    scriptName = LocalUtil.replace(scriptName, "/", "");

    String page = debugPageGenerator.generateTestPage(request.getContextPath() + request.getServletPath(), scriptName);

    response.setContentType(MimeConstants.MIME_HTML);
    PrintWriter out = response.getWriter();
    out.print(page);
}
 
Example 14
Project: openjdk-jdk10   File: SimpleSerialization.java   View Source Code Vote up 6 votes
private static String getFailureText(final Object orig, final Object copy) {
    final StringWriter sw = new StringWriter();
    final PrintWriter pw = new PrintWriter(sw);

    pw.println("Test FAILED: Deserialized object is not equal to the original object");
    pw.print("\tOriginal: ");
    printObject(pw, orig).println();
    pw.print("\tCopy:     ");
    printObject(pw, copy).println();

    pw.close();
    return sw.toString();
}
 
Example 15
Project: AppleCommander   File: PascalTextFileFilter.java   View Source Code Vote up 6 votes
/**
 * Process the given FileEntry and return a byte array 
 * with filtered data; use PrintWriter to get platform 
 * agnostic line endings.
 */
public byte[] filter(FileEntry fileEntry) {
	byte[] fileData = fileEntry.getFileData();
	int offset = HEADER_SIZE;
	ByteArrayOutputStream byteArray = new
		ByteArrayOutputStream(fileData.length);
	PrintWriter printWriter = new PrintWriter(byteArray, true);
	while (offset < fileData.length) {
		char c = (char)(fileData[offset] & 0x7f);	// Will the bitwise AND be a problem??
		switch (c) {
			case NUL:	break;		// ignore
			case CR:	printWriter.println();
						break;
			case DLE:	if (offset+1 < fileData.length) {
							offset++;
							int indent = fileData[offset] - INDENT_BASE_VALUE;
							while (indent-- > 0) {
								printWriter.print(' ');
							}
						}
						break;
			default:	printWriter.print(c);
						break;
		}
		offset++;
	}
	return byteArray.toByteArray();
}
 
Example 16
Project: AnyMall   File: GoodsCtrl.java   View Source Code Vote up 6 votes
@Override
protected void doPost(HttpServletRequest request,
		HttpServletResponse response) throws ServletException, IOException {
	response.setContentType("application/json");
	response.setCharacterEncoding("utf-8");

	PrintWriter out = response.getWriter();

	String rawContent = IOUtils.toString(request.getReader());
	log.debug(String.format("request content: %s", rawContent));

	out.print(goodsDAO.findById(1));
}
 
Example 17
Project: jerrydog   File: StandardServer.java   View Source Code Vote up 5 votes
/**
 * Store the specified Server properties.
 *
 * @param writer PrintWriter to which we are storing
 * @param indent Number of spaces to indent this element
 * @param server Object to be stored
 *
 * @exception Exception if an exception occurs while storing
 */
private void storeServer(PrintWriter writer, int indent,
                         Server server) throws Exception {

    // Store the beginning of this element
    writer.println("<?xml version='1.0' encoding='utf-8'?>");
    for (int i = 0; i < indent; i++) {
        writer.print(' ');
    }
    writer.print("<Server");
    storeAttributes(writer, server);
    writer.println(">");

    // Store nested <Listener> elements
    if (server instanceof Lifecycle) {
        LifecycleListener listeners[] =
            ((Lifecycle) server).findLifecycleListeners();
        for (int i = 0; i < listeners.length; i++) {
            storeListener(writer, indent + 2, listeners[i]);
        }
    }

    // Store nested <GlobalNamingResources> element
    NamingResources globalNamingResources =
        server.getGlobalNamingResources();
    if (globalNamingResources != null) {
        for (int i = 0; i < indent + 2; i++) {
            writer.print(' ');
        }
        writer.println("<GlobalNamingResources>");
        storeNamingResources(writer, indent + 4, globalNamingResources);
        for (int i = 0; i < indent + 2; i++) {
            writer.print(' ');
        }
        writer.println("</GlobalNamingResources>");
    }

    // Store nested <Service> elements
    Service services[] = server.findServices();
    for (int i = 0; i < services.length; i++) {
        storeService(writer, indent + 2, services[i]);
    }

    // Store the ending of this element
    for (int i = 0; i < indent; i++) {
        writer.print(' ');
    }
    writer.println("</Server>");

}
 
Example 18
Project: GitHub   File: NanoHTTPD.java   View Source Code Vote up 5 votes
/**
 * Sends given response to the socket.
 */
private void send(OutputStream outputStream) {
    String mime = mimeType;
    SimpleDateFormat gmtFrmt = new SimpleDateFormat(
            "E, d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
    gmtFrmt.setTimeZone(TimeZone.getTimeZone("GMT"));

    try {
        if (status == null) {
            throw new Error("sendResponse(): Status can't be null.");
        }
        PrintWriter pw = new PrintWriter(outputStream);
        pw.print("HTTP/1.0 " + status.getDescription() + " \r\n");

        if (mime != null) {
            pw.print("Content-Type: " + mime + "\r\n");
        }

        if (header == null || header.get("Date") == null) {
            pw.print("Date: " + gmtFrmt.format(new Date()) + "\r\n");
        }

        if (header != null) {
            for (String key : header.keySet()) {
                String value = header.get(key);
                pw.print(key + ": " + value + "\r\n");
            }
        }

        pw.print("\r\n");
        pw.flush();

        if (data != null) {
            int pending = data.available(); // This is to support
            // partial sends, see
            // serveFile()
            int BUFFER_SIZE = 16 * 1024;
            byte[] buff = new byte[BUFFER_SIZE];
            while (pending > 0) {
                int read = data.read(buff, 0,
                        ((pending > BUFFER_SIZE) ? BUFFER_SIZE
                                : pending));
                if (read <= 0) {
                    break;
                }
                outputStream.write(buff, 0, read);
                pending -= read;
            }
        }
        outputStream.flush();
        outputStream.close();
        if (data != null)
            data.close();
    } catch (IOException ioe) {
        // Couldn't write? No can do.
    }
}
 
Example 19
Project: L2jBrasil   File: GameStatusThread.java   View Source Code Vote up 5 votes
public GameStatusThread(Socket client, int uptime, String StatusPW) throws IOException
{
    _cSocket = client;
    _uptime = uptime;

    _print = new PrintWriter(_cSocket.getOutputStream());
    _read  = new BufferedReader(new InputStreamReader(_cSocket.getInputStream()));

    if ( isValidIP(client) ) {
        telnetOutput(1, client.getInetAddress().getHostAddress()+" accepted.");
        _print.println("Welcome To The L2J Telnet Session.");
        _print.println("Please Insert Your Password!");
        _print.print("Password: ");
        _print.flush();
        String tmpLine = _read.readLine();
        if ( tmpLine == null )  {
            _print.println("Error.");
            _print.println("Disconnected...");
            _print.flush();
            _cSocket.close();
        }
        else {
            if (tmpLine.compareTo(StatusPW) != 0)
            {
                _print.println("Incorrect Password!");
                _print.println("Disconnected...");
                _print.flush();
                _cSocket.close();
            }
            else
            {
                _print.println("Password Correct!");
                _print.println("[L2J]");
                _print.print("");
                _print.flush();
                start();
            }
        }
    }
    else {
        telnetOutput(5, "Connection attempt from "+ client.getInetAddress().getHostAddress() +" rejected.");
        _cSocket.close();
    }
}
 
Example 20
Project: unitimes   File: BuildingCoordsAjax.java   View Source Code Vote up 4 votes
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
    
    response.addHeader("Content-Type", "text/xml; charset=UTF-8");
    request.setCharacterEncoding("UTF-8");
    
    PrintWriter out = response.getWriter();
    
    out.print("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n");
    out.print("<results>");
    computeResponse(request, out);
    out.print("</results>");
    
    return null;        

}