Java Code Examples for java.io.PrintStream

The following are top voted examples for showing how to use java.io.PrintStream. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: jentrata-msh   File: ConsoleLogger.java View source code Vote up 6 votes
/**
 * Logs the message to the specified print stream.
 * 
 * @param out the output print stream.
 * @param level the log level.
 * @param description the log description.
 * @param throwable the exception cause.
 */
private void log(PrintStream out, String level, Object description, Throwable throwable) {
    out.println(level+": "+description);
    if (throwable != null) {
        throwable.printStackTrace(out);
    }
}
 
Example 2
Project: aws-toolkit-eclipse   File: FunctionProjectUtil.java View source code Vote up 6 votes
private static File addFileToProject(IPath targetPath, String fileName,
        String fileContent) throws CoreException, FileNotFoundException {

    IFileStore targetFileStore = EFS.getLocalFileSystem().fromLocalFile(
            targetPath.append(fileName).toFile());

    File targetFile = targetFileStore.toLocalFile(EFS.NONE, null);
    targetFile.getParentFile().mkdirs();
    PrintStream ps = new PrintStream(new FileOutputStream(targetFile));
    ps.print(fileContent);
    ps.close();

    return targetFile;
}
 
Example 3
Project: netlib   File: MessageHeader.java View source code Vote up 6 votes
/** Prints the key-value pairs represented by this
    header.  Also prints the RFC required blank line
    at the end. Omits pairs with a null key. */
public synchronized void print(PrintStream p) {
    for (int i = 0; i < nkeys; i++)
        if (keys[i] != null) {
            p.print(keys[i] +
                (values[i] != null ? ": "+values[i]: "") + "\r\n");
        }
    p.print("\r\n");
    p.flush();
}
 
Example 4
Project: jlibs   File: XPathResults.java View source code Vote up 6 votes
private static void print(PrintStream out, Object result, int indent){
    if(result instanceof Collection){
        int i = 0;
        Collection c = (Collection)result;

        String format = "%0"+String.valueOf(c.size()).length()+"d: %s%n";
        for(Object item: c){
            if(item instanceof Collection){
                printIndent(out, indent);
                out.println("[");
                print(out, item, indent+2);
                printIndent(out, indent);
                out.println("]");
            }else{
                printIndent(out, indent);
                out.printf(format, ++i, item);
            }
        }
    }else{
        printIndent(out, indent);
        if(result instanceof NodeItem)
            ((NodeItem)result).printTo(out);
        else
            out.print(result);
        out.println();
    }
}
 
Example 5
Project: erlide   File: RpcMonitor.java View source code Vote up 6 votes
public void dump(final PrintStream out, final boolean full) {
    Collection<OtpErlangObject> myArgs = args.get();
    myArgs = myArgs == null ? new ArrayList<OtpErlangObject>() : myArgs;
    final String argsString = full ? args.toString().replaceAll(
            "\n|\r", " ") : "...";
    OtpErlangObject val = result.get();
    val = val == null ? new OtpErlangAtom("null") : val;
    String resultString = full ? val.toString()
            .replaceAll("\n|\r", " ") : "...";
    if (resultString.length() > 100) {
        resultString = new String(resultString.substring(0, 99) + "...");
    }
    out.format(
            "%30s|%25s:%-20s/%d in=%9d, out=%9d, t=%6d, args=%s -> result=%s%n",
            node.substring(0, Math.min(29, node.length() - 1)), module,
            fun, argsSize, callSize, answerSize, answerTime - callTime,
            argsString, resultString);
}
 
Example 6
Project: netlib   File: JvmGlobalUtilRemoteTest.java View source code Vote up 6 votes
private void checkTorNetAdvanced() throws IOException {
    // test sockets
    {
        // try to use Java standard way of TCP/IP communication
        Socket s = new Socket(SOCKETTEST_HOSTNAME, SOCKETTEST_PORT);
        BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
        OutputStream os = s.getOutputStream();
        PrintStream out = new PrintStream(new DataOutputStream(os));
        
        // send message - without explicit flush! 
        out.print("GET / HTTP/1.");
        out.write('0');
        out.println("\n");
        
        // wait for server response
        String firstLine = in.readLine();
        assertEquals("wrong first line of response", "HTTP/1.1 200 OK", firstLine);
    }
}
 
Example 7
Project: Disco-Build-System   File: CliUtils.java View source code Vote up 5 votes
/**
 * A helper method, called exclusively by printActionSet(). This method calls itself recursively
 * as it traverses the ActionSet's tree structure.
 * 
 * @param outStream The PrintStream on which to display the output.
 * @param buildStore The database containing file, action and package information.
 * @param actionId The ID of the action we're currently displaying (at this level of recursion).
 * @param resultActionSet The full set of actions to be displayed (the result of some previous query).
 * @param filterActionSet The set of actions to actually be displayed (for post-filtering the query results).
 * @param outputFormat The way in which the actions should be formatted.
 * @param showPkgs Set to true if we should display package names.
 * @param indentLevel The number of spaces to indent this action by (at this recursion level).
 */
private static void printActionSetHelper(PrintStream outStream, IBuildStore buildStore, 
		int actionId, ActionSet resultActionSet, ActionSet filterActionSet, 
		DisplayWidth outputFormat, boolean showPkgs, int indentLevel) {

	IActionMgr actionMgr = buildStore.getActionMgr();
	IFileMgr fileMgr = buildStore.getFileMgr();
	IPackageMgr pkgMgr = buildStore.getPackageMgr();
	IPackageMemberMgr pkgMemberMgr = buildStore.getPackageMemberMgr();
	
	/* 
	 * Display the current action, at the appropriate indentation level. The format is:
	 * 
	 * - Action 1 (/home/psmith/t/cvs-1.11.23)
     *     if test ! -f config.h; then rm -f stamp-h1; emake  stamp-h1; else :;
     *     
     * -- Action 2 (/home/psmith/t/cvs-1.11.23)
     *      failcom='exit 1'; for f in x $MAKEFLAGS; do case $f in *=* | --[!k]*);; \
     *
     * Where Action 1 is the parent of Action 2.
     */
	
	/* is this action in the ActionSet to be printed? If not, terminate recursion */
	if (! (((resultActionSet == null) || (resultActionSet.isMember(actionId))) &&
		((filterActionSet == null) || (filterActionSet.isMember(actionId))))) {
		return;
	}	

	/* 
	 * Fetch the action's command string (if there is one). It can either be
	 * in short format (on a single line), or a full string (possibly multiple lines)
	 */
	String command = (String) actionMgr.getSlotValue(actionId, IActionMgr.COMMAND_SLOT_ID);
	if (command == null) {
		command = "<unknown command>";
	}
	else if (outputFormat == DisplayWidth.ONE_LINE) {
		command = ShellCommandUtils.getCommandSummary(command, getColumnWidth() - indentLevel - 3);
	}
	
	/* fetch the name of the directory the action was executed in */
	int actionDirId = (Integer) actionMgr.getSlotValue(actionId, IActionMgr.DIRECTORY_SLOT_ID);
	String actionDirName = fileMgr.getPathName(actionDirId);
	
	/* display the correct number of "-" characters */
	for (int i = 0; i != indentLevel; i++) {
		outStream.append('-');
	}
	outStream.print(" Action " + actionId + " (" + actionDirName);
	
	/* if requested, display the action's package name */
	if (showPkgs) {
		PackageDesc pkg = pkgMemberMgr.getPackageOfMember(IPackageMemberMgr.TYPE_ACTION, actionId);
		if (pkg == null) {
			outStream.print(" - Invalid action");
		} else {
			String pkgName = pkgMgr.getName(pkg.pkgId);
			if (pkgName == null) {
				outStream.print(" - Invalid package");
			} else {
				outStream.print(" - " + pkgName);					
			}
		}
	}
	outStream.println(")");
	
	/* display the action's command string. Each line must be indented appropriately */
	if (outputFormat != DisplayWidth.NOT_WRAPPED) {
		PrintUtils.indentAndWrap(outStream, command, indentLevel + 3, getColumnWidth());
		outStream.println();
	} else {
		outStream.println(command);
	}
	
	/* recursively call ourselves to display each of our children */
	Integer children[] = actionMgr.getChildren(actionId);
	for (int i = 0; i < children.length; i++) {
		printActionSetHelper(outStream, buildStore, children[i], 
				resultActionSet, filterActionSet, outputFormat, showPkgs, indentLevel + 1);
	}
	
}
 
Example 8
Project: netlib   File: HttpURLConnection.java View source code Vote up 5 votes
private void writeRequests() throws IOException {
    /* print all message headers in the MessageHeader
     * onto the wire - all the ones we've set and any
     * others that have been set
     */
     if (!setRequests) {

        /* We're very particular about the order in which we
         * set the request headers here.  The order should not
         * matter, but some careless CGI programs have been
         * written to expect a very particular order of the
         * standard headers.  To name names, the order in which
         * Navigator3.0 sends them.  In particular, we make *sure*
         * to send Content-type: <> and Content-length:<> second
         * to last and last, respectively, in the case of a POST
         * request.
         */
        if (!failedOnce)
            requests.prepend(method + " " + http.getURLFile()+" "  +
                             httpVersion, null);
        if (!getUseCaches()) {
            requests.setIfNotSet ("Cache-Control", "no-cache");
            requests.setIfNotSet ("Pragma", "no-cache");
        }
        requests.setIfNotSet("User-Agent", userAgent);
        int port = url.getPort();
        String host = url.getHost();
        if (port != -1 && port != url.getDefaultPort()) {
            host += ":" + String.valueOf(port);
        }
        requests.setIfNotSet("Host", host);
        requests.setIfNotSet("Accept", acceptString);

        /*
         * For HTTP/1.1 the default behavior is to keep connections alive.
         * However, we may be talking to a 1.0 server so we should set
         * keep-alive just in case, except if we have encountered an error
         * or if keep alive is disabled via a system property
         */

        // Try keep-alive only on first attempt
        if (!failedOnce && http.getHttpKeepAliveSet()) {
            requests.setIfNotSet("Connection", "keep-alive");
        } else {
            /*
             * RFC 2616 HTTP/1.1 section 14.10 says:
             * HTTP/1.1 applications that do not support persistent
             * connections MUST include the "close" connection option
             * in every message
             */
            requests.setIfNotSet("Connection", "close");
        }
        // Set modified since if necessary
        long modTime = getIfModifiedSince();
        if (modTime != 0 ) {
            Date date = new Date(modTime);
            //use the preferred date format according to RFC 2068(HTTP1.1),
            // RFC 822 and RFC 1123
            SimpleDateFormat fo =
              new SimpleDateFormat ("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
            fo.setTimeZone(TimeZone.getTimeZone("GMT"));
            requests.setIfNotSet("If-Modified-Since", fo.format(date));
        }
        // check for preemptive authorization
        AuthenticationInfo sauth = AuthenticationInfo.getServerAuth(url);
        if (sauth != null && sauth.supportsPreemptiveAuthorization() ) {
            // Sets "Authorization"
            requests.setIfNotSet(sauth.getHeaderName(), sauth.getHeaderValue(url,method));
            currentServerCredentials = sauth;
        }

        if (!method.equals("PUT") && (poster != null || streaming())) {
            requests.setIfNotSet ("Content-type",
                    "application/x-www-form-urlencoded");
        }

        if (streaming()) {
            if (chunkLength != -1) {
                requests.set ("Transfer-Encoding", "chunked");
            } else { /* fixed content length */
                if (fixedContentLengthLong != -1) {
                    requests.set ("Content-Length",
                                  String.valueOf(fixedContentLengthLong));
                } else if (fixedContentLength != -1) {
                    requests.set ("Content-Length",
                                  String.valueOf(fixedContentLength));
                }
            }
        } else if (poster != null) {
            /* add Content-Length & POST/PUT data */
            synchronized (poster) {
                /* close it, so no more data can be added */
                poster.close();
                requests.set("Content-Length",
                             String.valueOf(poster.size()));
            }
        }

        // get applicable cookies based on the uri and request headers
        // add them to the existing request headers
        setCookieHeader();

        setRequests=true;
    }
    if(logger.isLoggable(Level.FINEST)) {
        logger.fine(requests.toString());
    }
    http.writeRequests(requests, poster);
    if (ps.checkError()) {
        String proxyHost = http.getProxyHostUsed();
        int proxyPort = http.getProxyPortUsed();
        disconnectInternal();
        if (failedOnce) {
            throw new IOException("Error writing to server");
        } else { // try once more
            failedOnce=true;
            if (proxyHost != null) {
                setProxiedClient(url, proxyHost, proxyPort);
            } else {
                setNewClient (url);
            }
            ps = (PrintStream) http.getOutputStream();
            connected=true;
            responses = new MessageHeader();
            setRequests=false;
            writeRequests();
        }
    }
}