Example usage for java.io PrintWriter write

List of usage examples for java.io PrintWriter write

Introduction

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

Prototype

public void write(String s) 

Source Link

Document

Writes a string.

Usage

From source file:edu.stanford.cfuller.colocalization3d.correction.Correction.java

/**
 * Writes the Correction to disk in binary format so it can be stored and retrieved later.
 *
 * @param filename              The filename to which to write the Correction.
 * @throws java.io.IOException  if the Correction cannot be written to disk.
 */// w  ww. j  av  a 2  s  .  co  m
public void writeToDisk(String filename) throws java.io.IOException {

    File f = new File(filename);

    FileOutputStream fo = new FileOutputStream(f);

    PrintWriter p = new PrintWriter(fo);

    p.write(this.writeToXML());

    p.close();

}

From source file:io.neba.core.resourcemodels.registration.ModelRegistryConsolePlugin.java

@Override
protected void renderContent(HttpServletRequest req, HttpServletResponse res) throws IOException {
    writeHeadnavigation(res);/* w w w.j  a  va 2 s .c o m*/

    PrintWriter writer = res.getWriter();
    writeScriptIncludes(res);

    writer.write("<table id=\"plugin_table\" class=\"nicetable tablesorter noauto\">");
    writer.write(
            "<thead><tr><th>Type</th><th>Model type</th><th>Model name</th><th>Source bundle</th></tr></thead>");
    writer.write("<tbody>");
    for (Entry<String, Collection<OsgiModelSource<?>>> entry : this.registry.getTypeMappings().entrySet()) {
        for (OsgiModelSource<?> source : entry.getValue()) {
            String sourceBundleName = displayNameOf(source.getBundle());

            writer.write("<tr data-modeltype=\"" + source.getModelType().getName() + "\">");
            String resourceType = buildLinkToResourceType(req, entry.getKey());
            writer.write("<td>" + resourceType + "</td>");
            writer.write("<td>" + source.getModelType().getName() + "</td>");
            writer.write("<td>" + source.getModelName() + "</td>");
            writer.write("<td><a href=\"bundles/" + source.getBundleId() + "\" " + "title=\"" + sourceBundleName
                    + "\">" + source.getBundleId() + "</a></td>");
            writer.write("</tr>");
        }
    }
    writer.write("</tbody>");
    writer.write("</table>");
}

From source file:biz.taoconsulting.dominodav.methods.AbstractDAVMethod.java

/**
 * @see biz.taoconsulting.dominodav.interfaces.IDAVProcessable#process(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse,
 *      biz.taoconsulting.dominodav.interfaces.IDAVRepository,
 *      biz.taoconsulting.dominodav.LockManager)
 *//*w  ww  . j av a2s . c o m*/
public void process(HttpServletRequest req, HttpServletResponse resp, IDAVRepository repository,
        LockManager lockmanager) throws IOException {
    this.repository = repository;
    this.req = req;
    this.resp = resp;
    this.lockManager = lockmanager;
    // extracts values from the requestheader
    this.interpretRequestHeader();
    try {
        this.writeInitialHeader();
    } catch (Exception e) {
        LOGGER.error("WriteInitialHeader failed", e);
    }
    try {
        // LOGGER.info("Start action for method "+this.getClass());
        this.action();
    } catch (Exception e) {
        LOGGER.error("Executing action failed:" + e.getMessage(), e);
        // Status auf 500 setzne..
        this.resp.setStatus(500);
        PrintWriter pw = this.getOutputWriter();
        pw.write("<h3>Error:" + e.getMessage() + "</h3>");
    }
}

From source file:org.ambraproject.cas.filter.GetGuidReturnEmailFilter.java

/**
 * For the HttpServletRequest Parameter <em>guid</em>, query the user database for that
 *   user's Email Address, write that Email Address to the HttpServletResponse, and then exit.
 * <p/>/*from  w  w  w .ja v a 2s . c o m*/
 * Returns <strong>only</strong> the user's Email Address.
 * <p/>
 * <strong>Caveat</strong>: Does <strong>not</strong> call <em>FilterChain.doFilter(...)</em>,
 *   but rather simply writes the String (which it hopes is the Email Address) to the Response
 *   and exits.
 *
 * @param request The incoming HttpServletRequest from which the Parameter <em>guid</em> is read
 * @param response The HttpServletResponse to which the results String is written
 * @param filterChain Passed in, but not used;
 *   <em>FilterChain.doFilter(...)</em> is <strong>never called</strong>.
 * @throws IOException Unlikely to be thrown except for an infrastructure failure
 * @throws ServletException Potentially thrown by interactions with <em>request</em>
 *   and <em>response</em>, but never explicitly raised in this method
 */
public void doFilter(final ServletRequest request, final ServletResponse response,
        final FilterChain filterChain) throws IOException, ServletException {

    HttpServletResponse httpResponse = (HttpServletResponse) response;

    if (log.isDebugEnabled()) {
        log.debug("Received the guid parameter: " + request.getParameter("guid"));
    }

    httpResponse.setHeader("Pragma", "no-cache");
    httpResponse.setHeader("Cache-Control", "no-store");
    httpResponse.setDateHeader("Expires", -1);

    final PrintWriter writer = response.getWriter();
    try {
        String emailFromGuid = databaseService.getEmailAddressFromGuid(request.getParameter("guid"));
        if (log.isDebugEnabled()) {
            log.debug("Now passing back the email address: " + emailFromGuid);
        }

        if (emailFromGuid != null) {
            writer.write(emailFromGuid);
        } else {
            writer.write(
                    "Unable to lookup email address from the CAS server. Please contact the system administrator.");
        }
    } catch (Exception e) {
        log.error("Unable to query an email address or to write that email address to ServletResponse."
                + "  Attempted to query an email address for the guid = " + request.getParameter("guid"), e);
        //  TODO: Replace this with some clever logic.  This is NOT something to show to the user.
        writer.write("fake_guid_returned_from_cas");
    }

    // This next command is somewhat unfortunate.  A Filter should always invoke "doFilter(...)" at this point, but doing so can break this fragile email lookup.
    //   A typical failure mode is to see the login page in the middle of the Edit User Profile page, where the user's Email Address should be.
    // The core issue is that one of the other Filters may require authentication, so it calls the "/login" URL and the default behavior
    //   for that URL is to send the user to the Login page.  Ambra is querying for a single String (the user's email address), so it takes the String
    //   (which might be the entire Login page) and shows it to the user.
    // It is, therefore, recommended that Ambra acquire its users' email addresses in a different manner.
    return;
    // filterChain.doFilter(httpRequest, response);
}

From source file:org.apache.cxf.fediz.spring.web.FederationAuthenticationEntryPoint.java

public final void commence(final HttpServletRequest servletRequest, final HttpServletResponse response,
        final AuthenticationException authenticationException) throws IOException, ServletException {

    FedizContext fedContext = federationConfig.getFedizContext();
    LOG.debug("Federation context: {}", fedContext);

    if (servletRequest.getRequestURL().indexOf(FederationConstants.METADATA_PATH_URI) != -1
            || servletRequest.getRequestURL().indexOf(getMetadataURI(fedContext)) != -1) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Metadata document requested");
        }/*from  w w  w  . ja  v a  2  s.  c om*/
        response.setContentType("text/xml");
        PrintWriter out = response.getWriter();

        FedizProcessor wfProc = FedizProcessorFactory.newFedizProcessor(fedContext.getProtocol());
        try {
            Document metadata = wfProc.getMetaData(servletRequest, fedContext);
            out.write(DOM2Writer.nodeToString(metadata));
            return;
        } catch (Exception ex) {
            LOG.warn("Failed to get metadata document: " + ex.getMessage());
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }
    }

    String redirectUrl = null;
    try {
        FedizProcessor wfProc = FedizProcessorFactory.newFedizProcessor(fedContext.getProtocol());
        RedirectionResponse redirectionResponse = wfProc.createSignInRequest(servletRequest, fedContext);
        redirectUrl = redirectionResponse.getRedirectionURL();

        if (redirectUrl == null) {
            LOG.warn("Failed to create SignInRequest. Redirect URL null");
            throw new ServletException("Failed to create SignInRequest. Redirect URL null");
        }

        Map<String, String> headers = redirectionResponse.getHeaders();
        if (!headers.isEmpty()) {
            for (String headerName : headers.keySet()) {
                response.addHeader(headerName, headers.get(headerName));
            }
        }

    } catch (ProcessingException ex) {
        LOG.warn("Failed to create SignInRequest", ex);
        throw new ServletException("Failed to create SignInRequest: " + ex.getMessage());
    }

    preCommence(servletRequest, response);
    if (LOG.isInfoEnabled()) {
        LOG.info("Redirecting to IDP: " + redirectUrl);
    }
    response.sendRedirect(redirectUrl);
}

From source file:org.apache.cxf.fediz.spring.web.FederationAuthenticationEntryPoint.java

@Override
public void commence(ServletRequest request, ServletResponse response, AuthenticationException authException)
        throws IOException, ServletException {

    HttpServletRequest hrequest = (HttpServletRequest) request;
    HttpServletResponse hresponse = (HttpServletResponse) response;
    FedizContext fedContext = federationConfig.getFedizContext();
    LOG.debug("Federation context: {}", fedContext);

    if (hrequest.getRequestURL().indexOf(FederationConstants.METADATA_PATH_URI) != -1
            || hrequest.getRequestURL().indexOf(getMetadataURI(fedContext)) != -1) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Metadata document requested");
        }/*  w ww . jav a 2  s  .  co m*/
        response.setContentType("text/xml");
        PrintWriter out = response.getWriter();

        FedizProcessor wfProc = FedizProcessorFactory.newFedizProcessor(fedContext.getProtocol());
        try {
            Document metadata = wfProc.getMetaData(hrequest, fedContext);
            out.write(DOM2Writer.nodeToString(metadata));
            return;
        } catch (Exception ex) {
            LOG.warn("Failed to get metadata document: " + ex.getMessage());
            hresponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }
    }

    String redirectUrl = null;
    try {
        FedizProcessor wfProc = FedizProcessorFactory.newFedizProcessor(fedContext.getProtocol());

        RedirectionResponse redirectionResponse = wfProc.createSignInRequest(hrequest, fedContext);
        redirectUrl = redirectionResponse.getRedirectionURL();

        if (redirectUrl == null) {
            LOG.warn("Failed to create SignInRequest.");
            hresponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Failed to create SignInRequest.");
        }

        Map<String, String> headers = redirectionResponse.getHeaders();
        if (!headers.isEmpty()) {
            for (String headerName : headers.keySet()) {
                hresponse.addHeader(headerName, headers.get(headerName));
            }
        }

    } catch (ProcessingException ex) {
        System.err.println("Failed to create SignInRequest: " + ex.getMessage());
        LOG.warn("Failed to create SignInRequest: " + ex.getMessage());
        hresponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to create SignInRequest.");
    }

    preCommence(hrequest, hresponse);
    if (LOG.isInfoEnabled()) {
        LOG.info("Redirecting to IDP: " + redirectUrl);
    }
    hresponse.sendRedirect(redirectUrl);

}

From source file:de.mpg.mpdl.inge.pubman.web.sword.PubManDepositServlet.java

/**
 * Process a POST request.// ww  w.  j  a v  a  2  s.  c  om
 * 
 * @param HttpServletRequest
 * @param HttpServletResponse
 * @throws ServletException
 * @throws IOException
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    this.pubMan = new PubManSwordServer();
    SwordUtil util = new SwordUtil();
    Deposit deposit = new Deposit();
    AccountUserVO user = null;
    this.errorDoc = new PubManSwordErrorDocument();
    DepositResponse dr = null;

    // Authentification ---------------------------------------------
    String usernamePassword = this.getUsernamePassword(request);
    if (usernamePassword == null) {
        this.errorDoc.setSummary("No user credentials provided.");
        this.errorDoc.setErrorDesc(swordError.ErrorBadRequest);
        this.validDeposit = false;
    } else {
        int p = usernamePassword.indexOf(":");
        if (p != -1) {
            deposit.setUsername(usernamePassword.substring(0, p));
            deposit.setPassword(usernamePassword.substring(p + 1));
            user = util.getAccountUser(deposit.getUsername(), deposit.getPassword());
            this.pubMan.setCurrentUser(user);
        }
    }

    try {
        // Deposit --------------------------------------------------
        // Check if login was successfull
        if (this.pubMan.getCurrentUser() == null && this.validDeposit) {
            this.errorDoc.setSummary("Login user: " + deposit.getUsername() + " failed.");
            this.errorDoc.setErrorDesc(swordError.AuthentificationFailure);
            this.validDeposit = false;
        }

        // Check if collection was provided
        this.collection = request.getParameter("collection");
        if ((this.collection == null || this.collection.equals("")) && this.validDeposit) {
            this.collection = request.getParameter("collection");
            this.errorDoc.setSummary("No collection provided in request.");
            this.errorDoc.setErrorDesc(swordError.ErrorBadRequest);
            this.validDeposit = false;
        }

        // Check if user has depositing rights for this collection
        else {
            if (!util.checkCollection(this.collection, user) && this.validDeposit) {
                this.errorDoc.setSummary("User: " + deposit.getUsername()
                        + " does not have depositing rights for collection " + this.collection + ".");
                this.errorDoc.setErrorDesc(swordError.AuthorisationFailure);
                this.validDeposit = false;
            }
        }

        deposit.setFile(request.getInputStream());
        deposit = this.readHttpHeader(deposit, request);

        // Check if metadata format is supported
        if (!util.checkMetadatFormat(deposit.getFormatNamespace())) {
            throw new SWORDContentTypeException();
        }

        if (this.validDeposit) {
            // Get the DepositResponse
            dr = this.pubMan.doDeposit(deposit, this.collection);
        }
    } catch (SWORDAuthenticationException sae) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, this.getError());
        this.logger.error(sae.toString());
        this.validDeposit = false;

    } catch (SWORDContentTypeException e) {
        this.errorDoc.setSummary("File format not supported.");
        this.errorDoc.setErrorDesc(swordError.ErrorContent);
        this.validDeposit = false;
    } catch (ContentStreamNotFoundException e) {
        this.errorDoc.setSummary("No metadata File was found.");
        this.errorDoc.setErrorDesc(swordError.ErrorBadRequest);
        this.validDeposit = false;
    } catch (ItemInvalidException e) {
        ValidationReportItemVO itemReport = null;
        ValidationReportVO report = e.getReport();
        String error = "";
        for (int i = 0; i < report.getItems().size(); i++) {
            itemReport = report.getItems().get(i);
            error += itemReport.getContent() + "\n";
        }
        this.errorDoc.setSummary(error);
        this.errorDoc.setErrorDesc(swordError.ValidationFailure);
        this.validDeposit = false;
    } catch (PubItemStatusInvalidException e) {
        logger.error("Error in sword processing", e);
        this.errorDoc.setSummary("Provided item has wrong status.");
        this.errorDoc.setErrorDesc(swordError.ErrorBadRequest);
        this.validDeposit = false;
    } catch (Exception ioe) {
        logger.error("Error in sword processing", ioe);
        this.errorDoc.setSummary("An internal server error occurred.");
        this.errorDoc.setErrorDesc(swordError.InternalError);
        this.validDeposit = false;
    }
    try {
        // Write response atom
        if (this.validDeposit) {
            response.setStatus(dr.getHttpResponse());
            response.setContentType("application/xml");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Location", dr.getEntry().getContent().getSource());
            PrintWriter out = response.getWriter();
            out.write(dr.marshall());
            out.flush();
        }
        // Write error document
        else {
            String errorXml = this.errorDoc.createErrorDoc();
            response.setStatus(this.errorDoc.getStatus());
            response.setContentType("application/xml");
            response.setCharacterEncoding("UTF-8");
            PrintWriter out = response.getWriter();
            out.write(errorXml);
            out.flush();
        }
    } catch (Exception e) {
        this.logger.error("Error document could not be created.", e);
        throw new RuntimeException();
    }

    this.pubMan.setCurrentUser(null);
    this.validDeposit = true;
}

From source file:nl.minbzk.dwr.zoeken.enricher.uploader.ElasticSearchResultUploader.java

/**
 * {@inheritDoc}//from  w  ww .  ja v  a 2 s . c  o m
 */
@Override
public void writeOut(final String databaseName, final PrintWriter writer) {
    writer.write(format("ElasticSearch with database name %s", databaseName));
}

From source file:de.mpg.escidoc.pubman.sword.PubManDepositServlet.java

/**
 * Process a POST request./*from w ww . j a  v  a2  s. c o  m*/
 * @param HttpServletRequest
 * @param HttpServletResponse
 * @throws ServletException
 * @throws IOException
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    this.pubMan = new PubManSwordServer();
    SwordUtil util = new SwordUtil();
    Deposit deposit = new Deposit();
    AccountUserVO user = null;
    this.errorDoc = new PubManSwordErrorDocument();
    DepositResponse dr = null;

    // Authentification ---------------------------------------------
    String usernamePassword = this.getUsernamePassword(request);
    if (usernamePassword == null) {
        this.errorDoc.setSummary("No user credentials provided.");
        this.errorDoc.setErrorDesc(swordError.ErrorBadRequest);
        this.validDeposit = false;
    } else {
        int p = usernamePassword.indexOf(":");
        if (p != -1) {
            deposit.setUsername(usernamePassword.substring(0, p));
            deposit.setPassword(usernamePassword.substring(p + 1));
            user = util.getAccountUser(deposit.getUsername(), deposit.getPassword());
            this.pubMan.setCurrentUser(user);
        }
    }

    try {
        // Deposit --------------------------------------------------
        //Check if login was successfull
        if (this.pubMan.getCurrentUser() == null && this.validDeposit) {
            this.errorDoc.setSummary("Login user: " + deposit.getUsername() + " failed.");
            this.errorDoc.setErrorDesc(swordError.AuthentificationFailure);
            this.validDeposit = false;
        }

        //Check if collection was provided
        this.collection = request.getParameter("collection");
        if ((this.collection == null || this.collection.equals("")) && this.validDeposit) {
            this.collection = request.getParameter("collection");
            this.errorDoc.setSummary("No collection provided in request.");
            this.errorDoc.setErrorDesc(swordError.ErrorBadRequest);
            this.validDeposit = false;
        }

        //Check if user has depositing rights for this collection
        else {
            if (!util.checkCollection(this.collection, user) && this.validDeposit) {
                this.errorDoc.setSummary("User: " + deposit.getUsername()
                        + " does not have depositing rights for collection " + this.collection + ".");
                this.errorDoc.setErrorDesc(swordError.AuthorisationFailure);
                this.validDeposit = false;
            }
        }

        deposit.setFile(request.getInputStream());
        deposit = this.readHttpHeader(deposit, request);

        //Check if metadata format is supported
        if (!util.checkMetadatFormat(deposit.getFormatNamespace())) {
            throw new SWORDContentTypeException();
        }

        if (this.validDeposit) {
            // Get the DepositResponse
            dr = this.pubMan.doDeposit(deposit, this.collection);
        }
    } catch (SWORDAuthenticationException sae) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, this.getError());
        this.logger.error(sae.toString());
        this.validDeposit = false;

    } catch (SWORDContentTypeException e) {
        this.errorDoc.setSummary("File format not supported.");
        this.errorDoc.setErrorDesc(swordError.ErrorContent);
        this.validDeposit = false;
    } catch (ContentStreamNotFoundException e) {
        this.errorDoc.setSummary("No metadata File was found.");
        this.errorDoc.setErrorDesc(swordError.ErrorBadRequest);
        this.validDeposit = false;
    } catch (ItemInvalidException e) {
        ValidationReportItemVO itemReport = null;
        ValidationReportVO report = e.getReport();
        String error = "";
        for (int i = 0; i < report.getItems().size(); i++) {
            itemReport = report.getItems().get(i);
            error += itemReport.getContent() + "\n";
        }
        this.errorDoc.setSummary(error);
        this.errorDoc.setErrorDesc(swordError.ValidationFailure);
        this.validDeposit = false;
    } catch (PubItemStatusInvalidException e) {
        logger.error("Error in sword processing", e);
        this.errorDoc.setSummary("Provided item has wrong status.");
        this.errorDoc.setErrorDesc(swordError.ErrorBadRequest);
        this.validDeposit = false;
    } catch (Exception ioe) {
        logger.error("Error in sword processing", ioe);
        this.errorDoc.setSummary("An internal server error occurred.");
        this.errorDoc.setErrorDesc(swordError.InternalError);
        this.validDeposit = false;
    }
    try {
        //Write response atom
        if (this.validDeposit) {
            response.setStatus(dr.getHttpResponse());
            response.setContentType("application/xml");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Location", dr.getEntry().getContent().getSource());
            PrintWriter out = response.getWriter();
            out.write(dr.marshall());
            out.flush();
        }
        //Write error document
        else {
            String errorXml = this.errorDoc.createErrorDoc();
            response.setStatus(this.errorDoc.getStatus());
            response.setContentType("application/xml");
            response.setCharacterEncoding("UTF-8");
            PrintWriter out = response.getWriter();
            out.write(errorXml);
            out.flush();
        }
    } catch (Exception e) {
        this.logger.error("Error document could not be created.", e);
        throw new RuntimeException();
    }

    this.pubMan.setCurrentUser(null);
    this.validDeposit = true;
}

From source file:de.haber.xmind2latex.XMindToLatexExporter.java

/**
 * Stores the given <b>content</b> into the configured target file.
 *  //from www .  java2s .c  o  m
 * @param content content to save
 * @throws IOException either writer {@link IOException}, or if the target file already exists and fore overwrite is not enabled.
 */
private void save(String content) throws IOException {
    File tf = getTargetFile();
    if (tf.getParentFile() != null && !tf.getParentFile().exists()) {
        tf.getParentFile().mkdirs();
    }
    if (!tf.exists() || isOverwriteExistingFile()) {
        PrintWriter pw = new PrintWriter(tf, "UTF-8");
        pw.write(content);
        pw.close();
    } else {
        throw new FileAlreadyExistsException(tf.getAbsolutePath(), "",
                "If you want to overwrite existing files use param " + CliParameters.FORCE);
    }
}