Example usage for java.io PrintStream PrintStream

List of usage examples for java.io PrintStream PrintStream

Introduction

In this page you can find the example usage for java.io PrintStream PrintStream.

Prototype

public PrintStream(File file, Charset charset) throws IOException 

Source Link

Document

Creates a new print stream, without automatic line flushing, with the specified file and charset.

Usage

From source file:com.jayway.restassured.module.mockmvc.PutTest.java

@Test
public void doesnt_automatically_adds_x_www_form_urlencoded_as_content_type_when_putting_params() {
    StringWriter writer = new StringWriter();
    PrintStream captor = new PrintStream(new WriterOutputStream(writer), true);

    given().config(newConfig().logConfig(new LogConfig(captor, true))).param("name", "Johan").when()
            .put("/greetingPut").then().log().all().statusCode(415);

    assertThat(writer.toString(),/*from  w  w  w . j  a v  a2 s .c  om*/
            equalTo("415 Content type 'null' not supported\nAccept: application/x-www-form-urlencoded\n"));
}

From source file:ServiceDaemon.java

/**
 * init and destroy were added in jakarta-tomcat-daemon.
 *//*from  w  w  w.  j a v  a  2 s. c  o m*/
public void init(DaemonContext context) throws Exception {
    /* Set the err */
    System.setErr(new PrintStream(new FileOutputStream(new File("ServiceDaemon.err")), true));
    System.err.println("ServiceDaemon: instance " + this.hashCode() + " init");

    /* read the properties file */
    prop = new Properties();
    try {
        prop.load(new FileInputStream("startfile"));
    } catch (Exception e) {
        // Cannot find startfile.properties.
        // XXX: Should we print something?
    }
    /* create an array to store the processes */
    int i = 0;
    for (Enumeration e = prop.keys(); e.hasMoreElements();) {
        e.nextElement();
        i++;
    }
    System.err.println("ServiceDaemon: init for " + i + " processes");
    proc = new Process[i];
    readout = new ServiceDaemonReadThread[i];
    readerr = new ServiceDaemonReadThread[i];
    for (i = 0; i < proc.length; i++) {
        proc[i] = null;
        readout[i] = null;
        readerr[i] = null;
    }

    System.err.println("ServiceDaemon: init done ");

}

From source file:fr.gael.dhus.DHuS.java

/** Starts the DHuS (starts Tomcat, creates the Spring application context. */
public static void start() {
    // Transfer System.err in logger
    System.setErr(new PrintStream(new LoggingOutputStream(LOGGER), true));

    String version = DHuS.class.getPackage().getImplementationVersion();

    // Force ehcache not to call home
    System.setProperty("net.sf.ehcache.skipUpdateCheck", "true");
    System.setProperty("org.terracotta.quartz.skipUpdateCheck", "true");
    System.setProperty("user.timezone", "UTC");
    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
    System.setProperty("fr.gael.dhus.version", version == null ? "dev" : version);

    if (!SystemService.restore()) {
        LOGGER.error("Cannot run system restoration.");
        LOGGER.error("Check the restoration file \"" + SystemService.RESTORATION_PROPERTIES
                + "\" from the current directory.");
        System.exit(1);/*from   www.j av a2  s .  c o  m*/
    }

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            if ((server != null) && server.isRunning()) {
                try {
                    server.stop();
                } catch (TomcatException e) {
                    e.printStackTrace();
                }
            }
        }
    }));

    // Always add JMSAppender
    //Logger rootLogger = LogManager.getRootLogger ();
    //org.apache.logging.log4j.core.Logger coreLogger =
    //(org.apache.logging.log4j.core.Logger)rootLogger;
    //JMSAppender jmsAppender = JMSAppender.createAppender ();
    //coreLogger.addAppender (jmsAppender);
    try {
        // Activates the resolver for Drb
        DrbFactoryResolver.setMetadataResolver(new DrbCortexMetadataResolver(DrbCortexModel.getDefaultModel()));
    } catch (IOException e) {
        LOGGER.error("Resolver cannot be handled.");
        //logger.error (new Message(MessageType.SYSTEM,
        //"Resolver cannot be handled."));
    }

    LOGGER.info("Launching Data Hub Service...");
    //logger.info (new Message(MessageType.SYSTEM,
    //"Loading Data Hub Service..."));

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "classpath:fr/gael/dhus/spring/dhus-core-context.xml");
    context.registerShutdownHook();

    // Registers ContextClosedEvent listeners to properly save states before
    // the Spring context is destroyed.
    ApplicationListener sync_sv = context.getBean(ISynchronizerService.class);
    context.addApplicationListener(sync_sv);

    // Initialize Database Incoming folder
    IncomingManager incoming_manager = (IncomingManager) context.getBean("incomingManager");
    incoming_manager.initIncoming();

    // Initialize DHuS loggers
    //jmsAppender.cleanWaitingLogs ();
    //logger.info (new Message(MessageType.SYSTEM, "DHuS Started"));
    try {
        //ftp = xml.getBean (FtpServer.class);
        //ftp.start ();

        server = ApplicationContextProvider.getBean(TomcatServer.class);
        server.init();

        LOGGER.info("Starting server " + server.getClass() + "...");
        //logger.info (new Message(MessageType.SYSTEM, "Starting server..."));
        server.start();
        //logger.info (new Message(MessageType.SYSTEM, "Server started."));

        LOGGER.info("Server started.");

        // Initialises SolrDAO
        SolrDao solr_dao = (SolrDao) context.getBean("solrDao");
        solr_dao.initServerStarted();

        Map<String, WebApplication> webapps = context.getBeansOfType(WebApplication.class);
        for (String beanName : webapps.keySet()) {
            server.install(webapps.get(beanName));
        }

        fr.gael.dhus.server.http.web.WebApplication.installAll(server);
        WebServlet.installAll(server);
        WebPostProcess.launchAll();

        LOGGER.info("Server is ready...");
        started = true;

        //InitializableComponent.initializeAll ();
        //logger.info (new Message(MessageType.SYSTEM, "Server is ready..."));
        server.await();
    } catch (Exception e) {
        LOGGER.error("Cannot start system.", e);
        //logger.error (new Message(MessageType.SYSTEM, "Cannot start DHuS."), e);
        //ftp.stop ();
        System.exit(1);
    }
}

From source file:com.marketplace.Utils.java

/**
 * Converts a list of Android permissions to a corresponding int value in
 * database. If a new permission is found, then that permission gets added
 * to an external file 'permission' found in the directory config.
 * // w  ww  .  ja v  a2  s.  co m
 * @param permissions
 *            a list of permissions that needs to be converted.
 * 
 * @return a list of corresponding int value.
 */
synchronized public static List<Integer> permissionToInt(List<String> permissions) {
    List<Integer> pListArr = new ArrayList<Integer>(permissions.size());

    for (String permission : permissions) {
        if (pMap.containsKey(permission)) {
            pListArr.add(pMap.get(permission));
        } else {
            try {
                log.info("New permission found. Adding to the database");

                PrintStream printStream = new PrintStream(new FileOutputStream(Utils.fileName, true), true);
                printStream.print(permission + "\t" + (pMap.size() + 1) + "\n");
                printStream.close();

                pMap.put(permission, pMap.size() + 1);
                new Sender().doBasicHttpPost("{\"permission\":\"" + permission + "\"}",
                        Constants.newPermissionUrlJson);

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (ConnectivityException e) {
                log.info("There was a problem connecting to the database");
            }
        }
    }

    return pListArr;
}

From source file:com.lfv.yada.net.server.ServerLogger.java

public ServerLogger(int groupId, String logpath) {
    // Create a logger for this class
    if (logpath == null) {
        logpath = "data/logs/";
    }/*from  w  w w  . j  a  v a2  s.c  o m*/
    mylogpath = logpath;
    log = LogFactory.getLog(getClass());
    log.info("ServerLogger: logpath=" + logpath);

    // Create a calendar
    startTime = System.currentTimeMillis();
    calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    calendar.setTimeInMillis(startTime);
    String filename = "Grp" + groupId + "-" + calendar.get(Calendar.YEAR) + s2(calendar.get(Calendar.MONTH) + 1)
            + s2(calendar.get(Calendar.DAY_OF_MONTH)) + "-" + s2(calendar.get(Calendar.HOUR_OF_DAY))
            + s2(calendar.get(Calendar.MINUTE)) + s2(calendar.get(Calendar.SECOND)) + ".log";
    try {
        printer = new PrintStream(new FileOutputStream(logpath + "/" + filename), true);

        log.info("Creating log " + logpath + "/" + filename);
    } catch (FileNotFoundException ex) {
        log.warn("Log file " + filename + " could not be created, logger has been disabled!", ex);
        printer = null;
    }
}

From source file:com.iflytek.spider.util.LogUtil.java

/** Returns a stream that, when written to, adds log lines. */
private static PrintStream getLogStream(final Log logger, final Method method) {
    return new PrintStream(new ByteArrayOutputStream() {
        private int scan = 0;

        private boolean hasNewline() {
            for (; scan < count; scan++) {
                if (buf[scan] == '\n')
                    return true;
            }//w w w.  j  a  v a 2 s . c  o  m
            return false;
        }

        public void flush() throws IOException {
            if (!hasNewline())
                return;
            try {
                method.invoke(logger, new Object[] { toString().trim() });
            } catch (Exception e) {
                if (LOG.isFatalEnabled()) {
                    LOG.fatal("Cannot log with method [" + method + "]", e);
                }
            }
            reset();
            scan = 0;
        }
    }, true);
}

From source file:com.glaf.core.util.LogUtils.java

/** Returns a stream that, when written to, adds log lines. */
private static PrintStream getLogStream(final Log logger, final Method method) {
    return new PrintStream(new ByteArrayOutputStream() {
        private int scan = 0;

        public void flush() throws IOException {
            if (!hasNewline())
                return;
            try {
                method.invoke(logger, new Object[] { toString().trim() });
            } catch (Exception e) {
                if (LOG.isErrorEnabled()) {
                    LOG.error("Cannot log with method [" + method + "]", e);
                }//from ww  w  . ja v a2s  .c  om
            }
            reset();
            scan = 0;
        }

        private boolean hasNewline() {
            for (; scan < count; scan++) {
                if (buf[scan] == '\n')
                    return true;
            }
            return false;
        }
    }, true);
}

From source file:io.restassured.itest.java.GivenWhenThenLoggingITest.java

@Test
public void logResponseThatHasCookiesWithLogDetailCookiesUsingGivenWhenThenSyntax() throws Exception {
    final StringWriter writer = new StringWriter();
    final PrintStream captor = new PrintStream(new WriterOutputStream(writer), true);
    given().config(RestAssuredConfig.config()
            .logConfig(LogConfig.logConfig().defaultStream(captor).and().enablePrettyPrinting(false))).when()
            .get("/multiCookie").then().log().cookies().body(equalTo("OK"));
    assertThat(writer.toString(), allOf(startsWith(
            "cookie1=cookieValue1;Domain=localhost\ncookie1=cookieValue2;Comment=\"My Purpose\";Path=/;Domain=localhost;Max-Age=1234567;Secure;Expires="),
            endsWith(";Version=1" + LINE_SEPARATOR)));
}

From source file:hudson.console.AnnotatedLargeTextTest.java

@Test
public void smokes() throws Exception {
    ByteBuffer buf = new ByteBuffer();
    PrintStream ps = new PrintStream(buf, true);
    ps.print("Some text.\n");
    ps.print("Go back to " + TestNote.encodeTo("/root", "your home") + ".\n");
    ps.print("More text.\n");
    AnnotatedLargeText<Void> text = new AnnotatedLargeText<>(buf, Charsets.UTF_8, true, null);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    text.writeLogTo(0, baos);//from   w w  w  .  j ava2s  . co  m
    assertEquals("Some text.\nGo back to your home.\nMore text.\n", baos.toString());
    StringWriter w = new StringWriter();
    text.writeHtmlTo(0, w);
    assertEquals("Some text.\nGo back to <a href='/root'>your home</a>.\nMore text.\n", w.toString());
}

From source file:com.example.todo.selenium.RestTestSupport.java

@Before
public final void setUpConfig() {

    // Initialization of applicationContextUrl
    RestAssured.baseURI = applicationContextUrl + "/api/v1/todos";
    RestAssured.config = config().logConfig(logConfig().enablePrettyPrinting(false));
    writer = new StringWriter();
    captor = new PrintStream(new WriterOutputStream(writer), true);
}