Example usage for java.io PrintStream flush

List of usage examples for java.io PrintStream flush

Introduction

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

Prototype

public void flush() 

Source Link

Document

Flushes the stream.

Usage

From source file:org.pentaho.di.shared.SharedObjects.java

public void saveToFile() throws IOException, KettleException {
    FileObject fileObject = KettleVFS.getFileObject(filename);

    if (fileObject.exists()) {
        // Create a backup before overwriting...
        ////from   w  ww.j a v a 2  s  . c o m
        FileObject backupFile = KettleVFS.getFileObject(filename + ".backup");
        fileObject.moveTo(backupFile);
    }

    OutputStream outputStream = KettleVFS.getOutputStream(fileObject, false);

    PrintStream out = new PrintStream(outputStream);

    out.print(XMLHandler.getXMLHeader(Const.XML_ENCODING));
    out.println("<" + XML_TAG + ">");

    Collection<SharedObjectInterface> collection = objectsMap.values();
    for (SharedObjectInterface sharedObject : collection) {
        out.println(sharedObject.getXML());
    }

    out.println("</" + XML_TAG + ">");

    out.flush();
    out.close();
    outputStream.close();
}

From source file:org.apache.cassandra.tools.SSTableExport.java

/**
 * Export specific rows from an SSTable and write the resulting JSON to a PrintStream.
 * /*from ww  w  .j a  va  2  s. co  m*/
 * @param ssTableFile the SSTableScanner to export the rows from
 * @param outs PrintStream to write the output to
 * @param toExport the keys corresponding to the rows to export
 * @param excludes keys to exclude from export
 * @throws IOException on failure to read/write input/output
 */
public static void export(String ssTableFile, PrintStream outs, Collection<String> toExport, String[] excludes)
        throws IOException {
    SSTableReader reader = SSTableReader.open(Descriptor.fromFilename(ssTableFile));
    SSTableScanner scanner = reader.getDirectScanner(BufferedRandomAccessFile.DEFAULT_BUFFER_SIZE);

    IPartitioner<?> partitioner = StorageService.getPartitioner();

    if (excludes != null)
        toExport.removeAll(Arrays.asList(excludes));

    outs.println("{");

    int i = 0;

    // last key to compare order
    DecoratedKey lastKey = null;

    for (String key : toExport) {
        DecoratedKey decoratedKey = partitioner.decorateKey(hexToBytes(key));

        if (lastKey != null && lastKey.compareTo(decoratedKey) > 0)
            throw new IOException("Key out of order! " + lastKey + " > " + decoratedKey);

        lastKey = decoratedKey;

        scanner.seekTo(decoratedKey);

        if (!scanner.hasNext())
            continue;

        SSTableIdentityIterator row = (SSTableIdentityIterator) scanner.next();
        if (!row.getKey().equals(decoratedKey))
            continue;

        serializeRow(row, decoratedKey, outs);

        if (i != 0)
            outs.println(",");

        i++;
    }

    outs.println("\n}");
    outs.flush();

    scanner.close();
}

From source file:org.openmrs.module.pacsintegration.component.HL7ListenerComponentTest.java

@Test
public void shouldListenForAndParseORM_001Message() throws Exception {

    ModuleActivator activator = new PacsIntegrationActivator();
    activator.started();//from  www . j  a v  a  2s .co  m
    Context.getService(PacsIntegrationService.class).initializeHL7Listener();

    List<Patient> patients = patientService.getPatients(null, "101-6",
            Collections.singletonList(emrApiProperties.getPrimaryIdentifierType()), true);
    assertThat(patients.size(), is(1)); // sanity check
    Patient patient = patients.get(0);
    List<Encounter> encounters = encounterService.getEncounters(patient, null, null, null, null,
            Collections.singletonList(radiologyProperties.getRadiologyStudyEncounterType()), null, null, null,
            false);
    assertThat(encounters.size(), is(0)); // sanity check

    try {

        String message = "MSH|^~\\&|HMI||RAD|REPORTS|20130228174643||ORM^O01|RTS01CE16057B105AC0|P|2.3|\r"
                + "PID|1||101-6||Patient^Test^||19770222|M||||||||||\r" + "ORC|\r"
                + "OBR|1||0000001297|127689^SOME_X-RAY|||20130228170350||||||||||||MBL^CR||||||P|||||||&Goodrich&Mark&&&&^||||20130228170350\r"
                + "OBX|1|RP|||||||||F\r" + "OBX|2|TX|EventType^EventType|1|REVIEWED\r"
                + "OBX|3|CN|Technologist^Technologist|1|1435^Duck^Donald\r"
                + "OBX|4|TX|ExamRoom^ExamRoom|1|100AcreWoods\r"
                + "OBX|5|TS|StartDateTime^StartDateTime|1|20111009215317\r"
                + "OBX|6|TS|StopDateTime^StopDateTime|1|20111009215817\r"
                + "OBX|7|TX|ImagesAvailable^ImagesAvailable|1|1\r"
                + "ZDS|2.16.840.1.113883.3.234.1.3.101.1.2.1013.2011.15607503.2^HMI^Application^DICOM\r";

        Thread.sleep(2000); // give the simple server time to start

        Socket socket = new Socket("127.0.0.1", 6665);

        PrintStream writer = new PrintStream(socket.getOutputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        writer.print(header);
        writer.print(message);
        writer.print(trailer + "\r");
        writer.flush();

        Thread.sleep(2000);

        // confirm that study encounter has been created and has obs (we more thoroughly test the handler in the ORU_R01 handler and Radiology Service (in emr module) tests)
        encounters = encounterService.getEncounters(patient, null, null, null, null,
                Collections.singletonList(radiologyProperties.getRadiologyStudyEncounterType()), null, null,
                null, false);
        assertThat(encounters.size(), is(1));
        assertThat(encounters.get(0).getObs().size(), is(3));

        // confirm that the proper ack is sent out
        String response = reader.readLine();
        assertThat(response, containsString("|ACK|"));
    } finally {
        activator.stopped();
    }

}

From source file:com.bigdata.dastor.tools.SSTableExport.java

/**
 * Export specific rows from an SSTable and write the resulting JSON to a PrintStream.
 * //from   ww w .  ja v  a2s .c  om
 * @param ssTableFile the SSTable to export the rows from
 * @param outs PrintStream to write the output to
 * @param keys the keys corresponding to the rows to export
 * @throws IOException on failure to read/write input/output
 */
public static void export(String ssTableFile, PrintStream outs, String[] keys, String[] excludes)
        throws IOException {
    SSTableReader reader = SSTableReader.open(ssTableFile);
    SSTableScanner scanner = reader.getScanner(INPUT_FILE_BUFFER_SIZE);
    IPartitioner<?> partitioner = DatabaseDescriptor.getPartitioner();
    Set<String> excludeSet = new HashSet();
    int i = 0;

    if (excludes != null)
        excludeSet = new HashSet<String>(Arrays.asList(excludes));

    outs.println("{");

    for (String key : keys) {
        if (excludeSet.contains(key))
            continue;
        DecoratedKey<?> dk = partitioner.decorateKey(key);
        scanner.seekTo(dk);

        i++;

        if (scanner.hasNext()) {
            IteratingRow row = scanner.next();
            try {
                String jsonOut = serializeRow(row);
                if (i != 1)
                    outs.println(",");
                outs.print("  " + jsonOut);
            } catch (IOException ioexc) {
                System.err.println("WARNING: Corrupt row " + key + " (skipping).");
                continue;
            } catch (OutOfMemoryError oom) {
                System.err.println("ERROR: Out of memory deserializing row " + key);
                continue;
            }
        }
    }

    outs.println("\n}");
    outs.flush();
}

From source file:de.uni_koblenz.jgralab.utilities.tg2dot.Tg2Dot.java

public InputStream convertToGraphVizStream(GraphVizProgram prog) throws IOException {
    String executionString = String.format("%s%s -T%s", prog.path, prog.layouter, prog.outputFormat);
    final Process process = Runtime.getRuntime().exec(executionString);
    InputStream inputStream = new BufferedInputStream(process.getInputStream());
    new Thread() {
        @Override//w w  w . j a  v a2s  .c o m
        public void run() {
            PrintStream ps = new PrintStream(process.getOutputStream());
            convert(ps);
            ps.flush();
            ps.close();
        };
    }.start();
    return inputStream;
}

From source file:de.uni_koblenz.jgralab.utilities.tg2dot.Tg2Dot.java

public void pipeToGraphViz(GraphVizProgram prog) throws IOException {
    String executionString = String.format("%s%s -T%s -o%s", prog.path, prog.layouter, prog.outputFormat,
            outputName);//from w w w .  j  a  va 2  s.  com
    final Process process = Runtime.getRuntime().exec(executionString);
    new Thread() {
        @Override
        public void run() {
            PrintStream ps = new PrintStream(process.getOutputStream());
            convert(ps);
            ps.flush();
            ps.close();
        };
    }.start();
    try {
        int retVal = process.waitFor();
        if (retVal != 0) {
            throw new RuntimeException("GraphViz process failed! Error code = " + retVal);
        }
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.codehaus.enunciate.modules.jaxws_client.JAXWSClientDeploymentModule.java

/**
 * Reads a resource into string form.//from   w  ww.  j  a  v  a 2 s  .  c  om
 *
 * @param resource The resource to read.
 * @return The string form of the resource.
 */
protected String readResource(String resource) throws IOException, EnunciateException {
    HashMap<String, Object> model = new HashMap<String, Object>();
    model.put("sample_service_method", getModelInternal().findExampleWebMethod());
    model.put("sample_resource", getModelInternal().findExampleResource());

    URL res = JAXWSClientDeploymentModule.class.getResource(resource);
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    PrintStream out = new PrintStream(bytes);
    try {
        processTemplate(res, model, out);
        out.flush();
        bytes.flush();
        return bytes.toString("utf-8");
    } catch (TemplateException e) {
        throw new EnunciateException(e);
    }
}

From source file:org.intermine.web.struts.TemplateAction.java

/**
 * Build a query based on the template and the input from the user. There
 * are some request parameters that, if present, effect the behaviour of the
 * action. These are://from www.j a  va2 s.  com
 *
 * <dl>
 * <dt>skipBuilder</dt>
 * <dd>If this attribute is specifed (with any value) then the action will
 * forward directly to the object details page if the results contain just
 * one object.</dd>
 * <dt>noSaveQuery</dt>
 * <dd>If this attribute is specifed (with any value) then the query is not
 * automatically saved in the user's query history.</dd>
 * </dl>
 *
 * @param mapping
 *            The ActionMapping used to select this instance
 * @param form
 *            The optional ActionForm bean for this request (if any)
 * @param request
 *            The HTTP request we are processing
 * @param response
 *            The HTTP response we are creating
 * @return an ActionForward object defining where control goes next
 *
 * @exception Exception
 *                if the application business logic throws an exception
 */
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    HttpSession session = request.getSession();
    final InterMineAPI im = SessionMethods.getInterMineAPI(session);

    TemplateForm tf = (TemplateForm) form;
    String templateName = tf.getName();
    boolean saveQuery = (request.getParameter("noSaveQuery") == null);
    boolean skipBuilder = (request.getParameter(SKIP_BUILDER_PARAMETER) != null);
    boolean editTemplate = (request.getParameter("editTemplate") != null);
    boolean editQuery = (request.getParameter("editQuery") != null);

    // Note this is a workaround and will fail if a user has a template with the same name as
    // a public template but has executed the public one.  TemplateManager always give
    // precedence to user templates when there is a naming clash.
    String scope = tf.getScope();
    if (StringUtils.isBlank(scope)) {
        scope = Scope.ALL;
    }

    SessionMethods.logTemplateQueryUse(session, scope, templateName);

    Profile profile = SessionMethods.getProfile(session);
    TemplateManager templateManager = im.getTemplateManager();

    TemplateQuery template = templateManager.getTemplate(profile, templateName, scope);
    //If I'm browsing from the history or from saved query the template is in the session
    //with the values edited by the user, from this template we retrieve the original name
    //that we use to call the TemplateManager
    if (template == null) {
        PathQuery query = SessionMethods.getQuery(session);
        if (query instanceof TemplateQuery) {
            TemplateQuery currentTemplate = (TemplateQuery) query;
            template = templateManager.getTemplate(profile, currentTemplate.getName(), scope);
        } else {
            //from the template click edit query and then back (in this case in the session
            //there is a pathquery)
            template = templateManager.getTemplate(profile, (String) session.getAttribute("templateName"),
                    scope);
        }
    }
    if (template == null) {
        throw new RuntimeException("Could not find a template called " + session.getAttribute("templateName"));
    }
    TemplateQuery populatedTemplate = TemplatePopulator.getPopulatedTemplate(template,
            templateFormToTemplateValues(tf, template));

    //displayconstraint list used to display  constraints edited by the user
    DisplayConstraintFactory factory = new DisplayConstraintFactory(im, null);
    DisplayConstraint displayConstraint = null;
    List<DisplayConstraint> displayConstraintList = new ArrayList<DisplayConstraint>();
    for (PathConstraint pathConstraint : populatedTemplate.getEditableConstraints()) {
        displayConstraint = factory.get(pathConstraint, profile, populatedTemplate);
        displayConstraintList.add(displayConstraint);
    }
    session.setAttribute("dcl", displayConstraintList);

    String url = new URLGenerator(request).getPermanentBaseURL();

    if (!populatedTemplate.isValid()) {
        recordError(new ActionMessage("errors.template.badtemplate",
                StringUtil.prettyList(populatedTemplate.verifyQuery())), request);
        return mapping.findForward("template");
    }

    if (!editQuery && !skipBuilder && !editTemplate && forwardToLinksPage(request)) {

        Properties webProperties = SessionMethods.getWebProperties(request.getSession().getServletContext());

        WebserviceCodeGenInfo info = new WebserviceCodeGenInfo(populatedTemplate, url,
                webProperties.getProperty("project.title"), webProperties.getProperty("perl.wsModuleVer"),
                WebserviceCodeGenAction.templateIsPublic(template, im, profile), profile.getUsername());
        WebserviceCodeGenerator codeGen = new WebserviceJavaScriptCodeGenerator();
        String code = codeGen.generate(info);
        session.setAttribute("realCode", code);
        String escapedCode = StringEscapeUtils.escapeHtml(code);
        session.setAttribute("jsCode", escapedCode);

        return mapping.findForward("serviceLink");
    }

    if (!editQuery && !skipBuilder && !editTemplate && wantsWebserviceURL(request)) {
        TemplateResultLinkGenerator gen = new TemplateResultLinkGenerator();
        String webserviceUrl = gen.getTabLink(url, populatedTemplate);

        response.setContentType("text/plain");

        PrintStream out;
        try {
            out = new PrintStream(response.getOutputStream());
            out.print(webserviceUrl);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    if (!editQuery && !skipBuilder && !editTemplate && exportTemplate(request)) {
        SessionMethods.loadQuery(populatedTemplate, request.getSession(), response);
        return mapping.findForward("export");
    }

    if (!editQuery && !skipBuilder && !editTemplate && codeGenTemplate(request)) {
        SessionMethods.loadQuery(populatedTemplate, request.getSession(), response);
        return new ForwardParameters(mapping.findForward("codeGen"))
                .addParameter("method", request.getParameter("actionType"))
                .addParameter("source", "templateQuery").forward();
    }

    // We're editing the query: load as a PathQuery
    if (!skipBuilder && !editTemplate) {
        SessionMethods.loadQuery(new PathQuery(populatedTemplate), request.getSession(), response);
        session.setAttribute("templateName", populatedTemplate.getName());
        session.removeAttribute(Constants.NEW_TEMPLATE);
        session.removeAttribute(Constants.EDITING_TEMPLATE);
        form.reset(mapping, request);
        return mapping.findForward("query");
    } else if (editTemplate) {
        // We want to edit the template: Load the query as a TemplateQuery
        // Don't care about the form
        // Reload the initial template
        session.removeAttribute(Constants.NEW_TEMPLATE);
        session.setAttribute(Constants.EDITING_TEMPLATE, Boolean.TRUE);
        if (template == null) {
            recordMessage(new ActionMessage("errors.edittemplate.empty"), request);
            return mapping.findForward("template");
        }
        SessionMethods.loadQuery(template, request.getSession(), response);
        if (!template.isValid()) {
            recordError(new ActionMessage("errors.template.badtemplate",
                    StringUtil.prettyList(template.verifyQuery())), request);
        }

        return mapping.findForward("query");
    }

    // Otherwise show the results: load the modified query from the template
    if (saveQuery) {
        SessionMethods.loadQuery(populatedTemplate, request.getSession(), response);
    }
    form.reset(mapping, request);

    String qid = SessionMethods.startQueryWithTimeout(request, saveQuery, populatedTemplate);
    Thread.sleep(200);

    //tracks the template execution
    im.getTrackerDelegate().trackTemplate(populatedTemplate.getName(), profile, session.getId());

    String trail = "";
    // only put query on the trail if we are saving the query
    // otherwise its a "super top secret" query, e.g. quick search
    // also, note we are not saving any previous trails. trail resets at
    // queries and bags
    if (saveQuery) {
        trail = "|query";
    } else {
        trail = "";
        // session.removeAttribute(Constants.QUERY);
    }

    return new ForwardParameters(mapping.findForward("waiting")).addParameter("qid", qid)
            .addParameter("trail", trail).forward();
}

From source file:org.codehaus.enunciate.modules.objc.ObjCDeploymentModule.java

/**
 * Reads a resource into string form./*from  w w  w .java 2 s .  c o m*/
 *
 * @param resource The resource to read.
 * @return The string form of the resource.
 */
protected String readResource(String resource) throws IOException, EnunciateException {
    HashMap<String, Object> model = new HashMap<String, Object>();
    ResourceMethod exampleResource = getModelInternal().findExampleResourceMethod();
    String label = getLabel() == null
            ? getEnunciate().getConfig() == null ? "enunciate" : getEnunciate().getConfig().getLabel()
            : getLabel();
    model.put("label", label);
    NameForTypeDefinitionMethod nameForTypeDefinition = new NameForTypeDefinitionMethod(
            getTypeDefinitionNamePattern(), label, getModelInternal().getNamespacesToPrefixes(),
            this.packageIdentifiers);

    if (exampleResource != null) {
        if (exampleResource.getEntityParameter() != null
                && exampleResource.getEntityParameter().getXmlElement() != null) {
            ElementDeclaration el = exampleResource.getEntityParameter().getXmlElement();
            TypeDefinition typeDefinition = null;
            if (el instanceof RootElementDeclaration) {
                typeDefinition = getModelInternal().findTypeDefinition((RootElementDeclaration) el);
            } else if (el instanceof LocalElementDeclaration
                    && ((LocalElementDeclaration) el).getElementTypeDeclaration() instanceof ClassDeclaration) {
                typeDefinition = getModelInternal().findTypeDefinition(
                        (ClassDeclaration) ((LocalElementDeclaration) el).getElementTypeDeclaration());
            }

            if (typeDefinition != null) {
                model.put("input_element_name", nameForTypeDefinition.calculateName(typeDefinition));
            }
        }

        if (exampleResource.getRepresentationMetadata() != null
                && exampleResource.getRepresentationMetadata().getXmlElement() != null) {
            ElementDeclaration el = exampleResource.getRepresentationMetadata().getXmlElement();
            TypeDefinition typeDefinition = null;
            if (el instanceof RootElementDeclaration) {
                typeDefinition = getModelInternal().findTypeDefinition((RootElementDeclaration) el);
            } else if (el instanceof LocalElementDeclaration
                    && ((LocalElementDeclaration) el).getElementTypeDeclaration() instanceof ClassDeclaration) {
                typeDefinition = getModelInternal().findTypeDefinition(
                        (ClassDeclaration) ((LocalElementDeclaration) el).getElementTypeDeclaration());
            }

            if (typeDefinition != null) {
                model.put("output_element_name", nameForTypeDefinition.calculateName(typeDefinition));
            }
        }

        model.put("resource_url", exampleResource.getFullpath());
        model.put("resource_method", exampleResource.getHttpMethods().isEmpty() ? "GET"
                : exampleResource.getHttpMethods().iterator().next());
    }

    URL res = ObjCDeploymentModule.class.getResource(resource);
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    PrintStream out = new PrintStream(bytes);
    try {
        processTemplate(res, model, out);
        out.flush();
        bytes.flush();
        return bytes.toString("utf-8");
    } catch (TemplateException e) {
        throw new EnunciateException(e);
    }
}

From source file:hudson.scm.CvsTagsParamDefinition.java

@Exported
public ListBoxModel getSymbolicNames() {
    ListBoxModel model = new ListBoxModel();
    CvsChangeSet changeSet = null;//www  .j a  v  a2s . co m

    RlogCommand statusCommand = new RlogCommand();
    statusCommand.setHeaderOnly(true);
    statusCommand.setModule(moduleName);
    statusCommand.setRecursive(true);

    try {
        final File tempRlogSpill = File.createTempFile("cvs",
                "status );                                                                                                                                                                                                 `                                                                                                                                                                                                                                                                                                                                                                   ");
        final DeferredFileOutputStream outputStream = new DeferredFileOutputStream(100 * 1024, tempRlogSpill);
        final PrintStream logStream = new PrintStream(outputStream, true,
                getCvsDescriptor().getChangelogEncoding());

        final OutputStream errorOutputStream = new OutputStream() {
            final StringBuffer buffer = new StringBuffer();

            @Override
            public void write(int b) throws IOException {
                if ((int) ("\n".getBytes()[0]) == b) {
                    flush();
                } else {
                    buffer.append(new String(new byte[] { (byte) b }));
                }
            }

            @Override
            public void flush() throws IOException {
                logger.info(buffer.toString());
                buffer.delete(0, buffer.length());
                super.flush();
            }

            public void close() throws IOException {
                flush();
                super.close();
            }
        };
        final PrintStream errorPrintStream = new PrintStream(errorOutputStream);
        Client cvsClient = getCvsClient(cvsRoot, passwordRequired, password);
        cvsClient.getEventManager().addCVSListener(new BasicListener(logStream, errorPrintStream));
        cvsClient.executeCommand(statusCommand, getGlobalOptions(cvsRoot));

        logStream.close();
        errorPrintStream.flush();
        errorPrintStream.close();

        CvsLog parser = new CvsLog() {
            @Override
            public Reader read() throws IOException {
                if (outputStream.isInMemory())
                    return new InputStreamReader(new ByteArrayInputStream(outputStream.getData()),
                            getCvsDescriptor().getChangelogEncoding());
                else
                    return new InputStreamReader(new FileInputStream(outputStream.getFile()),
                            getCvsDescriptor().getChangelogEncoding());
            }

            @Override
            public void dispose() {
                tempRlogSpill.delete();
            }
        };

        changeSet = parser.mapCvsLog(cvsRoot, new CvsRepositoryLocation.HeadRepositoryLocation());

    } catch (IOException ex) {
        model.add(new ListBoxModel.Option("Could not load symbolic names - " + ex.getLocalizedMessage()));
        return model;
    } catch (CommandAbortedException ex) {
        model.add(new ListBoxModel.Option("Could not load symbolic names - " + ex.getLocalizedMessage()));
        return model;
    } catch (CommandException ex) {
        model.add(new ListBoxModel.Option("Could not load symbolic names - " + ex.getLocalizedMessage()));
        return model;
    } catch (AuthenticationException ex) {
        model.add(new ListBoxModel.Option("Could not load symbolic names - " + ex.getLocalizedMessage()));
        return model;
    }

    model.add(new ListBoxModel.Option("Head", "HEAD"));

    for (String branchName : changeSet.getBranchNames()) {
        model.add(new ListBoxModel.Option(branchName + " (Branch)", branchName));
    }

    for (String tagName : changeSet.getTagNames()) {
        model.add(new ListBoxModel.Option(tagName + " (Tag)", tagName));
    }

    return model;
}