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:de.akra.idocit.wsdl.services.WSDLParserTest.java

/**
 * Tests {@link WSDLParser#parse(org.eclipse.core.resources.IFile)} with file
 * "wsdl_100001.wsdl".//ww  w.ja  v  a 2s.c o m
 * 
 * @throws Exception
 */
@Test
public void testParseWsdl_100001WSDL() throws Exception {
    /*
     * Positive tests
     * ******************************************************************************
     * Test case #1: Parse the PortType of the WSDL file {@link
     * Constants#FOLDER_SOURCE}/CustomerService.xml". One PortType is expected.
     * ******************************************************************************
     */
    {
        InterfaceArtifact iStruct = null;
        WSDLParserMock parser = new WSDLParserMock();

        iStruct = parser.parse(new File(Constants.FOLDER_SOURCE + "wsdl_100001.wsdl"));
        // iStruct = parser.parse(new File(Constants.FOLDER_SOURCE + "wsdl_46001"));

        assertEquals(1, iStruct.getInterfaces().size());

        StringBuffer parseResult = new StringBuffer();
        TestUtils.buildHierarchy(parseResult, iStruct, 0);

        /*
         * write the result to a file
         */
        PrintWriter writer = new PrintWriter(new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(Constants.FOLDER_OUT + "wsdl_100001.wsdl.out"),
                        Charset.forName(Misc.DEFAULT_CHARSET))));
        writer.write(parseResult.toString());
        writer.close();
    }

    /*
     * Negative tests
     * ***************************************************************************
     * Test case #1: three WSDL-operations should be classified correctly
     * ****************************************************************************
     * None
     */
}

From source file:au.org.paperminer.main.UserFilter.java

/**
 * Either extracts the current user editable data (email and trove key) for possible
 * user modification, or resets the DB data to passed values.
 * @param req/*from  w w  w .  j av  a2  s. co m*/
 * @param resp
 */
private void updateUser(HttpServletRequest req, HttpServletResponse resp) {
    String id = req.getParameter("id");
    m_logger.info("updating user info " + id);
    if ((id != null) && id.length() > 0) {
        resetUserData(id, req, resp);
    } else {
        id = CookieHelper.getCookieValue(req, PaperMinerConstants.PMC_USER_ID);
        if (id == null) {
            req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e110");
        } else {
            m_logger.debug("retrieving user info");
            UserHelper helper = new UserHelper(id);
            if (!helper.isKnownUser()) {
                req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e106");
            } else {
                try {
                    resp.setContentType("text/html");
                    PrintWriter pm = resp.getWriter();
                    pm.write("<form id=\"user-mod\" action=\"\" method=\"post\">");
                    pm.append("<input id=\"id\" type=\"hidden\" value=\"" + helper.get(UserHelper.ID) + "\"/>");
                    pm.append("<table>");
                    pm.append("<tr><td>eMail address </td><td><input id=\"em\" type=\"text=\" value=\""
                            + helper.get(UserHelper.EMAIL) + "\"/></td></tr>");
                    pm.append("<tr><td>TROVE Key </td><td><input id=\"tk\" type=\"text=\" value=\""
                            + helper.get(UserHelper.TROVE_KEY) + "\"/></td></tr>");
                    pm.append("</table>");
                    pm.append(
                            "<p><input id=\"vfy\" name=\"usr-cb\" type=\"checkbox\" value=\"verify\"/> Verify my eMail Address.");
                    pm.append("</form>");
                } catch (IOException ex) {
                    req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e107");
                }
            }
        }
    }
}

From source file:com.suntek.gztpb.controller.ChangeCarControll.java

@RequestMapping(value = "saveCarInfo.htm", method = RequestMethod.POST)
public @ResponseBody String saveTest(CarChangeModel carInfo, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    response.setContentType("text/html");
    response.setCharacterEncoding("utf-8");
    PrintWriter out = response.getWriter();

    String applyNum = IdGenerator.getInstance().getBizCode("ITMS_SEQ", 5);
    carInfo.setApplynum(applyNum);/* ww  w.  ja  v a  2  s .c o m*/

    carInfo.setCreatedtime(new Date());
    carInfo.setFirstregdate(new Date());
    carInfo.setFinish(0);
    carInfo.setSource(0);
    carInfo.setSubmittime(new Date());

    carInfo.setCreator(request.getParameter("ownername"));

    try {
        carChangeService.signUp(carInfo);
        out.write("<script>parent.saveCallback(1,'" + applyNum + "')</script>");
    } catch (Exception e) {
        e.printStackTrace();
        out.write("<script>parent.saveCallback(0)</script>");
    }
    return null;
}

From source file:com.googlecode.jsfFlex.filter.JsfFlexResourceFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest httpRequest = HttpServletRequest.class.cast(request);
    HttpServletResponse httpResponse = HttpServletResponse.class.cast(response);

    JsfFlexResponseWrapper jsfFlexResponseWrapper = new JsfFlexResponseWrapper(httpResponse);
    AbstractJsfFlexResource jsfFlexResource = AbstractJsfFlexResource.getInstance();

    String requestURI = httpRequest.getRequestURI();
    String[] requestURISplitted = requestURI.split("/");

    if (isRequestForResource(requestURI)) {
        /** If request is of resource, process it and return */
        jsfFlexResource.processRequestResource(httpResponse, requestURISplitted);
        return;/*  ww w .  j  ava2 s.c om*/
    }

    /** Perform the regular path of request/response */

    chain.doFilter(request, jsfFlexResponseWrapper);

    jsfFlexResponseWrapper.finishResponse();

    /** Finished with the usual path of request/response. Now specific for JSF Flex*/

    if (jsfFlexResponseWrapper.getContentType() != null
            && isValidContentType(jsfFlexResponseWrapper.getContentType())) {

        Matcher headMatcher = HEAD_PATTERN.matcher(jsfFlexResponseWrapper.toString());
        boolean headMatchedBoolean = headMatcher.find();

        PrintWriter actualWriter = httpResponse.getWriter();

        if (headMatchedBoolean) {
            int headMatchIndex = headMatcher.start();

            actualWriter.write(jsfFlexResponseWrapper.toString().substring(0, headMatchIndex + 5));

            Matcher endTagCharMatcher = END_TAG_CHAR_PATTERN.matcher(jsfFlexResponseWrapper.toString());
            endTagCharMatcher.find(headMatchIndex);

            int endTagCharIndex = endTagCharMatcher.start();

            actualWriter.write(
                    jsfFlexResponseWrapper.toString().substring(headMatchIndex + 5, endTagCharIndex + 1));

            if (isDebugMode) {
                actualWriter.write(META_HTTP_EQUIV_EXPIRE);
                actualWriter.write(META_HTTP_EQUIV_PRAGMA_NO_CACHE);
                actualWriter.write(META_HTTP_EQUIV_CACHE_CONTROL_NO_CACHE);
            }

            Collection<String> resourceCollection = jsfFlexResource.getResources();
            String resourceConvertedToScriptElements = constructResourceToScriptTags(resourceCollection,
                    requestURISplitted);

            actualWriter.write(resourceConvertedToScriptElements);

            actualWriter.write(jsfFlexResponseWrapper.toString().substring(endTagCharIndex + 1));

        } else {

            Matcher bodyMatcher = BODY_PATTERN.matcher(jsfFlexResponseWrapper.toString());
            boolean bodyMatched = bodyMatcher.find();

            if (bodyMatched) {
                int bodyMatchIndex = bodyMatcher.start();

                actualWriter.write(jsfFlexResponseWrapper.toString().substring(0, bodyMatchIndex));

                actualWriter.write(HEAD_START_TAG);

                if (isDebugMode) {
                    actualWriter.write(META_HTTP_EQUIV_EXPIRE);
                    actualWriter.write(META_HTTP_EQUIV_PRAGMA_NO_CACHE);
                    actualWriter.write(META_HTTP_EQUIV_CACHE_CONTROL_NO_CACHE);
                }

                Collection<String> resourceCollection = jsfFlexResource.getResources();
                String resourceConvertedToScriptElements = constructResourceToScriptTags(resourceCollection,
                        requestURISplitted);

                actualWriter.write(resourceConvertedToScriptElements);

                actualWriter.write(HEAD_END_TAG);

                actualWriter.write(jsfFlexResponseWrapper.toString().substring(bodyMatchIndex));
            } else {
                //Must not be for mxml components, so flush
                actualWriter.write(jsfFlexResponseWrapper.toString());
            }
        }

        actualWriter.flush();
    }

}

From source file:com.zxy.commons.web.exception.CustomMappingExceptionResolver.java

@Override
protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response,
        Object handler, Exception ex) {
    logger.error(ex.getMessage(), ex);/*from   w  w  w  . java  2  s  . co  m*/
    // Expose ModelAndView for chosen error view.
    String viewName = determineViewName(ex, request);
    if (viewName != null) {
        if (!(request.getHeader("accept").indexOf("application/json") > -1
                || (request.getHeader("X-Requested-With") != null
                        && request.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1))) {
            // ?
            // Apply HTTP status code for error views, if specified.
            // Only apply it if we're processing a top-level request.
            Integer statusCode = determineStatusCode(request, viewName);
            if (statusCode != null) {
                applyStatusCodeIfPossible(request, response, statusCode);
            }
            return getModelAndView(viewName, ex, request);
        } else {// JSON?
            PrintWriter out = null;
            try {
                out = response.getWriter();
                String msg = "?:" + ex.getMessage();
                if (ex instanceof UnauthorizedException) {
                    msg = "??????!";
                }
                JsonObject json = JsonObject.create().put("flag", false).put("msg", msg);
                out.write(json.toJSONString());
                out.flush();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            } finally {
                if (out != null) {
                    out.close();
                }
            }
            return null;
        }
    } else {
        return null;
    }
}

From source file:eu.comvantage.dataintegration.QueryDistributionServiceImpl.java

private void print(String outstring, HttpServletResponse response) throws IOException {
    //parallel console output
    String[] strings = outstring.split("</br>");
    for (String s : strings)
        System.out.println(s);/*  www.  j  a va 2  s.co m*/

    //writing character response stream
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.write(outstring);
}

From source file:javax.portlet.tck.portlets.AddlRequestTests_SPEC2_11_ActionReq.java

@SuppressWarnings("deprecation")
@Override/*from  ww  w. ja v a 2 s. co m*/
public void render(RenderRequest portletReq, RenderResponse portletResp) throws PortletException, IOException {

    long tid = Thread.currentThread().getId();
    portletReq.setAttribute(THREADID_ATTR, tid);

    PrintWriter writer = portletResp.getWriter();

    PortletSession ps = portletReq.getPortletSession();
    String msg = (String) ps.getAttribute(RESULT_ATTR_PREFIX + "AddlRequestTests_SPEC2_11_ActionReq",
            APPLICATION_SCOPE);
    if (msg != null) {
        writer.write("<p>" + msg + "</p><br/>\n");
        ps.removeAttribute(RESULT_ATTR_PREFIX + "AddlRequestTests_SPEC2_11_ActionReq", APPLICATION_SCOPE);
    }

    /* TestCase: V2AddlRequestTests_SPEC2_11_ActionReq_contentType1 */
    /* Details: "The getResponseContentType method returns a String */
    /* representing the default content type the portlet container */
    /* assumes for the output" */
    {
        PortletURL aurl = portletResp.createActionURL();
        aurl.setParameters(portletReq.getPrivateParameterMap());
        TestButton tb = new TestButton(V2ADDLREQUESTTESTS_SPEC2_11_ACTIONREQ_CONTENTTYPE1, aurl);
        tb.writeTo(writer);
    }

    /* TestCase: V2AddlRequestTests_SPEC2_11_ActionReq_contentType2 */
    /* Details: "The getResponseContentTypes method returns an */
    /* Enumeration of String elements representing the acceptable content */
    /* types for the output in order of preference" */
    {
        PortletURL aurl = portletResp.createActionURL();
        aurl.setParameters(portletReq.getPrivateParameterMap());
        TestButton tb = new TestButton(V2ADDLREQUESTTESTS_SPEC2_11_ACTIONREQ_CONTENTTYPE2, aurl);
        tb.writeTo(writer);
    }

    /* TestCase: V2AddlRequestTests_SPEC2_11_ActionReq_contentType3 */
    /* Details: "The first element of the Enumeration returned by the */
    /* getResponseContentTypes method must equal the value returned by */
    /* the getResponseContentType method" */
    {
        PortletURL aurl = portletResp.createActionURL();
        aurl.setParameters(portletReq.getPrivateParameterMap());
        TestButton tb = new TestButton(V2ADDLREQUESTTESTS_SPEC2_11_ACTIONREQ_CONTENTTYPE3, aurl);
        tb.writeTo(writer);
    }

    /* TestCase: V2AddlRequestTests_SPEC2_11_ActionReq_windowId4 */
    /* Details: "The string returned by getWindowID method must be the */
    /* same ID used for scoping portlet-scope session attributes" */
    {
        PortletURL aurl = portletResp.createActionURL();
        aurl.setParameters(portletReq.getPrivateParameterMap());
        portletReq.getPortletSession().setAttribute("tr5", portletReq.getWindowID(), PORTLET_SCOPE);
        TestButton tb = new TestButton(V2ADDLREQUESTTESTS_SPEC2_11_ACTIONREQ_WINDOWID4, aurl);
        tb.writeTo(writer);
    }

    /* TestCase: V2AddlRequestTests_SPEC2_11_ActionReq_contentType6 */
    /* Details: "Within the processAction method, the content type must */
    /* include only the MIME type, not the character set" */
    {
        PortletURL aurl = portletResp.createActionURL();
        aurl.setParameters(portletReq.getPrivateParameterMap());
        TestButton tb = new TestButton(V2ADDLREQUESTTESTS_SPEC2_11_ACTIONREQ_CONTENTTYPE6, aurl);
        tb.writeTo(writer);
    }

}

From source file:de.undercouch.gradle.tasks.download.ETagTest.java

@Override
protected Handler[] makeHandlers() throws IOException {
    ContextHandler lastModifiedHandler = new ContextHandler("/" + ETAG) {
        @Override/* ww  w.  ja va2 s .c om*/
        public void handle(String target, HttpServletRequest request, HttpServletResponse response,
                int dispatch) throws IOException, ServletException {
            String ifNoneMatch = request.getHeader("If-None-Match");
            if (etag != null && etag.equals(ifNoneMatch)) {
                response.setStatus(304);
                response.flushBuffer();
            } else {
                response.setStatus(200);
                if (etag != null) {
                    response.setHeader("ETag", etag);
                }
                PrintWriter rw = response.getWriter();
                rw.write("etag: " + etag);
                rw.close();
            }
        }
    };
    return new Handler[] { lastModifiedHandler };
}

From source file:acoli.controller.Controller.java

/**
 *
 * @param request//from w ww . j a  va 2s .c  o  m
 * @param response
 * @throws ServletException
 * @throws IOException
 * @throws FileNotFoundException
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, FileNotFoundException {

    // Get servlet context.
    ServletContext servletContext = this.getServletConfig().getServletContext();
    String path = servletContext.getRealPath("/");
    //System.out.println(path);
    // Previously used way to obtain servlet context doesn't work.
    //ServletContext context = request.getServletContext();
    //String path = context.getRealPath("/");
    //System.out.println("ServletContext.getRealPath():" + path + "<--");

    String forward = "";
    // Get a map of the request parameters
    @SuppressWarnings("unchecked")
    Map parameters = request.getParameterMap();

    if (parameters.containsKey("grammar")) {
        HttpSession session = request.getSession(false);
        String absoluteUnzippedGrammarDir = (String) session.getAttribute("absoluteUnzippedGrammarDir");
        //System.out.println("Uploaded file to analyze: " + absoluteUnzippedGrammarDir);

        // User-selected port.
        String javaport = (String) request.getParameter("javaport");

        System.out.println("User selected port: " + javaport);
        String traleport = String.valueOf((Integer.parseInt(javaport) - 1000));

        // Check if these ports are already in use
        // if so, kill the grammar in the corresponding directory and start a new one.
        if (portAvailable(Integer.parseInt(javaport)) && portAvailable(Integer.parseInt(traleport))) {
            System.out.println("Both javaport/traleport: " + javaport + "/" + traleport + " available!");
        } else {
            // Java port not free.
            if (!portAvailable(Integer.parseInt(javaport))) {
                System.out.println("Port: " + javaport + " not available!");
                // Get the grammar directory that is running on this port and kill it.
                if (portToGrammarFolderMappings.containsKey(javaport)) {
                    String grammarDirToKill = portToGrammarFolderMappings.get(javaport);
                    // Stop grammar.
                    runBashScript(path, "./single_grammar_stop.sh", grammarDirToKill, "");

                } else {
                    killProcessID(path, "./free_java_port.sh", javaport);
                }
            }
            // Trale port not free.
            if (!portAvailable(Integer.parseInt(traleport))) {
                killProcessID(path, "./free_sicstus_port.sh", traleport);
            }
        }
        // Generate port-specific files
        // which will be redirected by the script later.
        PrintWriter w = new PrintWriter(new File(absoluteUnzippedGrammarDir + "/" + "javaserverport.txt"));
        w.write(javaport);
        w.flush();
        w.close();

        w = new PrintWriter(new File(absoluteUnzippedGrammarDir + "/" + "traleserverstart.pl"));
        w.write("trale_server_start(" + traleport + ").\n"); // 1000 port ids less than the java id.
        w.flush();
        w.close();

        // Copy wtx.pl and tokenization.pl into the grammar directory.
        File tokenizationFile = new File(path + "/resources/servertrale_files/tokenization.pl");
        File wtxFile = new File(path + "/resources/servertrale_files/wtx.pl");

        //System.out.println("tokenizationFile: " + tokenizationFile.getAbsolutePath());
        //System.out.println("wtxFile: " + wtxFile.getAbsolutePath());
        File destinationDir = new File(absoluteUnzippedGrammarDir + "/");
        //System.out.println("destinationDir: " + absoluteUnzippedGrammarDir);
        FileUtils.copyFileToDirectory(tokenizationFile, destinationDir);
        FileUtils.copyFileToDirectory(wtxFile, destinationDir);

        // Start grammar.
        // Check webtrale version from user selection.
        String labelVersion = (String) request.getParameter("webtraleVersion");
        System.out.println("User selected label version: " + labelVersion);

        switch (labelVersion) {
        case "webtralePS94":
            runBashScript(path, "./single_grammar_start.sh", absoluteUnzippedGrammarDir,
                    "webtrale_green_labels.jar");
            break;
        case "webtraleAprilLabels":
            // April labels.
            runBashScript(path, "./single_grammar_start.sh", absoluteUnzippedGrammarDir,
                    "webtrale_green_aprillabels.jar");
            break;
        case "webtraleMayLabels":
            // May labels.
            runBashScript(path, "./single_grammar_start.sh", absoluteUnzippedGrammarDir,
                    "webtrale_green_maylabels.jar");
            break;
        case "webtraleJuneLabels":
            // June labels.
            runBashScript(path, "./single_grammar_start.sh", absoluteUnzippedGrammarDir,
                    "webtrale_green_junelabels.jar");
            break;
        default:
            // Standard labels.
            runBashScript(path, "./single_grammar_start.sh", absoluteUnzippedGrammarDir,
                    "webtrale_green_nolabels.jar");
            break;
        }

        portToGrammarFolderMappings.put(javaport, absoluteUnzippedGrammarDir);
        session.setAttribute("javaport", javaport);
        System.out.println("Used ports and grammar directories: " + portToGrammarFolderMappings + "\n");

        forward = GRAMMAR_JSP;
    } else if (parameters.containsKey("run")) {
        forward = RUN_JSP;
    } else if (parameters.containsKey("admin")) {
        System.out.println("Accessing grammar admin.");
        // Check which ports are still non-available.
        TreeMap<String, String> tmpMap = new TreeMap<>();
        for (String aJavaPort : portToGrammarFolderMappings.keySet()) {
            if (!portAvailable(Integer.parseInt(aJavaPort))) {
                tmpMap.put(aJavaPort, portToGrammarFolderMappings.get(aJavaPort));
            }
        }

        portToGrammarFolderMappings.clear();
        portToGrammarFolderMappings = tmpMap;
        System.out
                .println("Used ports and grammar directories in admin: " + portToGrammarFolderMappings + "\n");

        // only testing.
        //portToGrammarFolderMappings.put("7001", "/var/lib/tomcat7/webapps/servertrale/resources/uploads/BEBFECC89/posval");
        //portToGrammarFolderMappings.put("7002", "/var/lib/tomcat7/webapps/servertrale/resources/uploads/B02CA6BAA/4_Semantics_Raising");

        // Save all used ports and directories in this session attribute.
        HttpSession session = request.getSession(false);
        String portToGrammarFolderMappingsString = portToGrammarFolderMappings.toString().substring(1,
                portToGrammarFolderMappings.toString().length() - 1);
        session.setAttribute("runningGrammars", portToGrammarFolderMappingsString.split("\\, "));

        forward = ADMIN_JSP;

    } // Upload (START PAGE)
    else {

        //            HttpSession session = request.getSession(false);
        //            String absoluteUnzippedGrammarDir = (String) session.getAttribute("absoluteUnzippedGrammarDir");
        //            if (absoluteUnzippedGrammarDir != null) {
        //                // Stop grammar.
        //                runBashScript(path, "./single_grammar_stop.sh", absoluteUnzippedGrammarDir);
        //                // Remove this java port from the list of occupied ports.
        //                TreeMap<String, String> tmpMap = new TreeMap<>();
        //                for(String aJavaPort : portToGrammarFolderMappings.keySet()) {
        //                    String aGrammarDir = portToGrammarFolderMappings.get(aJavaPort);
        //                    if(aGrammarDir.equals(absoluteUnzippedGrammarDir)) {
        //                        // Java port should be removed. So ignore it.
        //                    }
        //                    else {
        //                        tmpMap.put(aJavaPort, absoluteUnzippedGrammarDir);
        //                    }
        //                }
        //                portToGrammarFolderMappings.clear();
        //                portToGrammarFolderMappings = tmpMap;
        //                System.out.println("Used ports and grammar directories: " + portToGrammarFolderMappings + "\n\n");
        //                
        //            } else {
        //                System.out.println("No grammar to kill.");
        //            }
        forward = UPLOAD_JSP;
    }

    RequestDispatcher view = request.getRequestDispatcher(forward);
    view.forward(request, response);
}