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:com.sccl.attech.modules.sys.web.DictController.java

@RequiresPermissions("sys:dict:view")
@RequestMapping(value = { "list", "" })
public String list(Dict dict, HttpServletRequest request, HttpServletResponse response, Model model)
        throws Exception {
    DictVo vo = new DictVo();

    // ???????/*from  w  w  w .  ja v a 2s  .com*/
    String searchLable = "";
    if (StringUtils.isNotBlank(dict.getLabel())) {
        searchLable = EncodedUtil.decodeValue(dict.getLabel());
        dict.setLabel(searchLable);
        vo.setLabel(searchLable);
    }
    String parentId = request.getParameter("parentId");
    String type = request.getParameter("dictType");
    if (null != type && !"".equals(type)) {
        dict.setType(type);
        vo.setType(type);

        Page<Dict> page = dictService.find(new Page<Dict>(request, response), dict);
        model.addAttribute("page", page);
        // this.sendObjectToJson(page, response);

        String dictJson = JsonMapper.getInstance().toJson(page);

        List<DictVo> list = dictService.findTree(vo);

        String content = JsonMapper.getInstance().toJson(list);//json
        String dictStart = dictJson.substring(0, dictJson.indexOf("["));
        String dictEnd = dictJson.substring(dictJson.indexOf("]") + 1);

        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter pw = response.getWriter();
        pw.write(dictStart + content + dictEnd);
        pw.flush();
        pw.close();

    }
    return null;
}

From source file:org.piraso.server.spring.web.PirasoServlet.java

private void writeResponse(HttpServletResponse response, String contentType, String str) throws IOException {
    PrintWriter out = response.getWriter();

    try {/*  w ww . j  a v a 2s.  co m*/
        response.setContentType(contentType);
        response.setCharacterEncoding(ENCODING_UTF_8);

        out.write(str);
        out.flush();
    } finally {
        out.close();
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.SparqlQueryServlet.java

private void executeQuery(HttpServletResponse response, String resultFormatParam, String rdfResultFormatParam,
        String queryParam, RDFService rdfService) throws IOException {

    ResultSetFormat rsf = null;//from   w  w w  .  jav a2 s.c o  m
    /* BJL23 2008-11-06
     * modified to support CSV output.
     * Unfortunately, ARQ doesn't make it easy to
     * do this by implementing a new ResultSetFormat, because 
     * ResultSetFormatter is hardwired with expected values.
     * This slightly ugly approach will have to do for now. 
     */
    if (!("vitro:csv").equals(resultFormatParam)) {
        rsf = formatSymbols.get(resultFormatParam);
    }
    String mimeType = mimeTypes.get(resultFormatParam);

    try {
        Query query = SparqlQueryUtils.create(queryParam);
        if (query.isSelectType()) {
            ResultSet results = null;
            results = ResultSetFactory
                    .fromJSON(rdfService.sparqlSelectQuery(queryParam, RDFService.ResultFormat.JSON));
            response.setContentType(mimeType);
            if (rsf != null) {
                OutputStream out = response.getOutputStream();
                ResultSetFormatter.output(out, results, rsf);
            } else {
                Writer out = response.getWriter();
                toCsv(out, results);
            }
        } else {
            Model resultModel = null;
            if (query.isConstructType()) {
                resultModel = RDFServiceUtils.parseModel(
                        rdfService.sparqlConstructQuery(queryParam, RDFService.ModelSerializationFormat.N3),
                        RDFService.ModelSerializationFormat.N3);
            } else if (query.isDescribeType()) {
                resultModel = RDFServiceUtils.parseModel(
                        rdfService.sparqlDescribeQuery(queryParam, RDFService.ModelSerializationFormat.N3),
                        RDFService.ModelSerializationFormat.N3);
            } else if (query.isAskType()) {
                // Irrespective of the ResultFormatParam, 
                // this always prints a boolean to the default OutputStream.
                String result = (rdfService.sparqlAskQuery(queryParam) == true) ? "true" : "false";
                PrintWriter p = response.getWriter();
                p.write(result);
                return;
            }
            response.setContentType(rdfFormatSymbols.get(rdfResultFormatParam));
            OutputStream out = response.getOutputStream();
            resultModel.write(out, rdfResultFormatParam);
        }
    } catch (RDFServiceException e) {
        throw new RuntimeException(e);
    }
}

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

/**
 * (non-Javadoc)/*from w w  w. j a  va 2  s .  c  o  m*/
 * 
 * @see biz.taoconsulting.dominodav.methods.AbstractDAVMethod#action()
 */
@SuppressWarnings("deprecation")
protected void action() throws Exception {
    // TODO Implement!
    IDAVRepository rep = this.getRepository();
    String curURI = (String) this.getHeaderValues().get("uri");
    IDAVResource resource = null;
    String relockToken = this.getRelockToken(this.getReq());
    LockManager lm = this.getLockManager();
    // int status = HttpServletResponse.SC_OK; // We presume success
    LockInfo li = null;
    HttpServletResponse resp = this.getResp();
    Long TimeOutValue = this.getTimeOutValue(this.getReq());
    try {
        // LOGGER.info("getResource");
        resource = rep.getResource(curURI, true);

    } catch (DAVNotFoundException e) {
        // This exception isn't a problem since we just can create the new
        // URL
        // LOGGER.info("Exception not found resource");

    }
    if (resource == null) {
        // LOGGER.info("Error, resource is null");
        // Set the return error
        // Unprocessable Entity (see
        // http://www.webdav.org/specs/rfc2518.html#status.code.extensions.to.http11)
        this.setHTTPStatus(403);
        return;
    }
    if (resource.isReadOnly()) {
        this.setHTTPStatus(403);
        return;
    }
    if (relockToken != null) {
        li = lm.relock(resource, relockToken, TimeOutValue);
        if (li == null) {
            String eString = "Relock failed for " + relockToken;
            LOGGER.debug(eString);
            this.setErrorMessage(eString, 423); // Precondition failed
            this.setHTTPStatus(423);
            return;
        }
    }
    String creationDate = null, modifiedDate = null;
    Date dt = new Date();
    Date dtM = new Date();
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    LOGGER.info("DB Factory built OK");
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    LOGGER.info("Document builder OK");
    Document doc = dBuilder.parse(this.getReq().getInputStream());
    LOGGER.info("XML Doc ok read");
    if (doc != null) {
        LOGGER.info("doc is not null");
        NodeList nlCreation = doc.getElementsByTagName("Z:Win32CreationTime");
        NodeList nlModified = doc.getElementsByTagName("Z:Win32LastModifiedTime");
        if (nlCreation != null) {
            LOGGER.info("nlCreation not null");
            Node nNodeCreation = nlCreation.item(0);
            if (nNodeCreation != null) {
                LOGGER.info("nNodeCreation not null, is " + nNodeCreation.getTextContent());
                creationDate = nNodeCreation.getTextContent();
                LOGGER.info("Creation date=" + creationDate + "  Locale is "
                        + this.getReq().getLocale().toString());
                DateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.getDefault());
                LOGGER.info("SimpleDate Format ok created");
                try {
                    dt = df.parse(creationDate);
                } catch (Exception e) {
                    creationDate += "+00";
                    dt = df.parse(creationDate);
                }
                try {
                    // dt.setTime(dt.getTime()-3*60*60*1000);
                    resource.patchCreationDate(dt);
                } catch (Exception e) {
                }
                LOGGER.info("Date dt parsed with value=" + dt.toString());
            }
        }
        if (nlModified != null) {
            LOGGER.info("nlModified not null");
            Node nNodeModified = nlModified.item(0);
            if (nNodeModified != null) {
                LOGGER.info("nNodeModified not null");
                modifiedDate = nNodeModified.getTextContent();
                LOGGER.info("Modified date=" + modifiedDate);
                Locale defLoc = Locale.getDefault();
                // This is the crap reason why Win7 didn;t work!
                DateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", defLoc);
                try {
                    dtM = df.parse(modifiedDate);
                } catch (Exception e) {
                    modifiedDate += "+00";
                    dtM = df.parse(modifiedDate);
                }
                try {
                    // dtM.setTime(dtM.getTime()-3*60*60*1000);
                    resource.patchLastModified(dtM);
                } catch (Exception e) {
                }
                LOGGER.info("Date dtM parsed with value=" + dtM.toString());
            }
        }
    }

    IDAVXMLResponse xr = DavXMLResponsefactory.getXMLResponse(null, false);
    xr.openTag("multistatus");
    resource.addToDavXMLResponsePROPPATCH(xr);
    xr.closeDocument();
    this.setHTTPStatus(DAVProperties.STATUS_MULTIPART);
    // FIXME: this is depricated!
    resp.setStatus(DAVProperties.STATUS_MULTIPART, DAVProperties.STATUS_MULTIPART_STRING);
    resp.setContentType(DAVProperties.TYPE_XML);
    String result = xr.toString();
    resp.setContentLength(result.length());
    PrintWriter out = resp.getWriter();
    out.write(result);
    out.close();
}

From source file:de.metanome.algorithms.testing.example_ind_algorithm.ExampleAlgorithm.java

@Override
public void execute() throws AlgorithmExecutionException {
    File tempFile = tempFileGenerator.getTemporaryFile();
    PrintWriter tempWriter;
    try {//from w w w  .  ja v a2  s . c  om
        tempWriter = new PrintWriter(tempFile);
    } catch (FileNotFoundException e) {
        throw new AlgorithmExecutionException("File not found.");
    }
    tempWriter.write("table1");
    tempWriter.close();

    try {
        FileUtils.readFileToString(tempFile);
    } catch (IOException e) {
        throw new AlgorithmExecutionException("Could not read from file.");
    }

    if ((tableName != null) && fileInputSet && (numberOfTables != -1)) {
        resultReceiver.receiveResult(new InclusionDependency(
                new ColumnPermutation(new ColumnIdentifier("WDC_planets.csv", "Name"),
                        new ColumnIdentifier("WDC_planets.csv", "Type")),
                new ColumnPermutation(new ColumnIdentifier("WDC_planets.csv", "Mass"),
                        new ColumnIdentifier("WDC_planets.csv", "Rings"))));
    }
}

From source file:org.tec.webapp.web.ErrorServlet.java

/**
 * process the error/*from ww w  . ja  v a2  s .c  o  m*/
 * @param request the request instance
 * @param response the response instance
 * @throws IOException if processing fails
 */
protected void processError(HttpServletRequest request, HttpServletResponse response) throws IOException {
    Throwable throwable = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
    Integer statusCode = (Integer) request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
    String requestUri = (String) request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI);

    LOGGER.error("failed to process " + requestUri + " error code: " + statusCode);

    WebError we;
    if (throwable != null) {
        LOGGER.error("error", throwable);
        we = new WebError(throwable.getMessage(), ErrorCodes.UNRESOLVEABLE_ERROR);
    } else {
        we = new WebError("error", ErrorCodes.UNRESOLVEABLE_ERROR);
    }

    PrintWriter pw = null;
    try {
        response.setStatus(statusCode != null ? statusCode : HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentType(MimeTypeUtils.APPLICATION_JSON_VALUE);
        pw = response.getWriter();
        pw.write(we.toJSON());
        pw.flush();
    } finally {
        if (pw != null) {
            pw.close();
        }
    }
}

From source file:org.opendatakit.aggregate.servlet.GetActiveUsersServlet.java

/**
 * Handler for HTTP Get request that returns the list of roles assigned to this user.
 * //  ww  w  .j  a va  2s . co  m
 * Assumed to return a entity body that is a JSON serialization of a list.
 *
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 */
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    CallingContext cc = ContextFactory.getCallingContext(this, req);

    TreeSet<GrantedAuthorityName> grants;
    try {
        grants = SecurityServiceUtil.getCurrentUserSecurityInfo(cc);
    } catch (ODKDatastoreException e) {
        logger.error("Retrieving users persistence error: " + e.toString());
        e.printStackTrace();
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                ErrorConsts.PERSISTENCE_LAYER_PROBLEM + "\n" + e.toString());
        return;
    }

    boolean returnFullList = false;
    for (GrantedAuthorityName grant : grants) {
        if (grant.equals(GrantedAuthorityName.ROLE_SITE_ACCESS_ADMIN)
                || grant.equals(GrantedAuthorityName.ROLE_ADMINISTER_TABLES)
                || grant.equals(GrantedAuthorityName.ROLE_SUPER_USER_TABLES)) {
            returnFullList = true;
            break;
        }
    }

    // returned object (will be JSON serialized).
    ArrayList<HashMap<String, Object>> listOfUsers = new ArrayList<HashMap<String, Object>>();

    HashMap<String, Object> hashMap;
    if (!returnFullList) {
        // only return ourself -- we don't have privileges to see everyone
        hashMap = new HashMap<String, Object>();
        User user = cc.getCurrentUser();
        if (user.isAnonymous()) {
            hashMap.put(USER_ID, "anonymous");
            hashMap.put(FULL_NAME, User.ANONYMOUS_USER_NICKNAME);
        } else {
            RegisteredUsersTable entry;
            try {
                entry = RegisteredUsersTable.getUserByUri(user.getUriUser(), cc.getDatastore(),
                        cc.getCurrentUser());
            } catch (ODKDatastoreException e) {
                logger.error("Retrieving users persistence error: " + e.toString());
                e.printStackTrace();
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        ErrorConsts.PERSISTENCE_LAYER_PROBLEM + "\n" + e.toString());
                return;
            }
            if (user.getEmail() == null) {
                hashMap.put(USER_ID, "username:" + entry.getUsername());
                if (user.getNickname() == null) {
                    hashMap.put(FULL_NAME, entry.getUsername());
                } else {
                    hashMap.put(FULL_NAME, user.getNickname());
                }
            } else {
                hashMap.put(USER_ID, entry.getEmail());
                if (user.getNickname() == null) {
                    hashMap.put(FULL_NAME, entry.getEmail().substring(EmailParser.K_MAILTO.length()));
                } else {
                    hashMap.put(FULL_NAME, user.getNickname());
                }
            }
        }
        processRoles(grants, hashMap);
        listOfUsers.add(hashMap);
    } else {
        // we have privileges to see all users -- return the full mapping
        try {
            ArrayList<UserSecurityInfo> allUsers = SecurityServiceUtil.getAllUsers(true, cc);
            for (UserSecurityInfo i : allUsers) {
                hashMap = new HashMap<String, Object>();
                if (i.getType() == UserType.ANONYMOUS) {
                    hashMap.put(USER_ID, "anonymous");
                    hashMap.put(FULL_NAME, User.ANONYMOUS_USER_NICKNAME);
                } else if (i.getEmail() == null) {
                    hashMap.put(USER_ID, "username:" + i.getUsername());
                    if (i.getFullName() == null) {
                        hashMap.put(FULL_NAME, i.getUsername());
                    } else {
                        hashMap.put(FULL_NAME, i.getFullName());
                    }
                } else {
                    // already has the mailto: prefix
                    hashMap.put(USER_ID, i.getEmail());
                    if (i.getFullName() == null) {
                        hashMap.put(FULL_NAME, i.getEmail().substring(EmailParser.K_MAILTO.length()));
                    } else {
                        hashMap.put(FULL_NAME, i.getFullName());
                    }
                }
                processRoles(i.getGrantedAuthorities(), hashMap);
                listOfUsers.add(hashMap);
            }
        } catch (DatastoreFailureException e) {
            logger.error("Retrieving users persistence error: " + e.toString());
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    ErrorConsts.PERSISTENCE_LAYER_PROBLEM + "\n" + e.toString());
            return;
        } catch (AccessDeniedException e) {
            logger.error("Retrieving users access denied error: " + e.toString());
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
            return;
        }
    }

    resp.addHeader(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION);
    resp.addHeader("Access-Control-Allow-Origin", "*");
    resp.addHeader("Access-Control-Allow-Credentials", "true");
    resp.addHeader(HttpHeaders.HOST, cc.getServerURL());
    resp.setContentType(HtmlConsts.RESP_TYPE_JSON);
    resp.setCharacterEncoding(HtmlConsts.UTF8_ENCODE);

    PrintWriter out = resp.getWriter();
    out.write(mapper.writeValueAsString(listOfUsers));
    out.flush();

    resp.setStatus(HttpStatus.SC_OK);
}

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

/**
 *  Locate an existing locations by its Latitude & Longitude values.
 * //from   www . j  a  v a2 s .  c o m
 * @param req
 * @param resp
 */
private void findLatLongLocation(HttpServletRequest req, HttpServletResponse resp) {
    String lat = req.getParameter("lat");
    String lng = req.getParameter("lng");

    try {
        ArrayList<HashMap<String, String>> list = m_helper.locationsLikeLatLng(Float.valueOf(lat).floatValue(),
                Float.valueOf(lng).floatValue());
        m_logger.debug("locationFilter locn lookup: " + lat + ", " + lng + " -- List Size: " + list.size());

        resp.setContentType("text/json");
        PrintWriter pm = resp.getWriter();
        pm.write(JSONValue.toJSONString(list));
        pm.close();
    } catch (PaperMinerException ex) {
        m_logger.error("lookup failed", ex);
        req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e305");
    } catch (IOException ex) {
        req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e114");
    }
}

From source file:com.rapid.server.RapidHttpServlet.java

public void sendMessage(HttpServletResponse response, int status, String title, String message)
        throws IOException {

    response.setStatus(status);//from   w w  w  .j  a v a2 s . c  o  m

    response.setContentType("text/html");

    PrintWriter out = response.getWriter();

    // write a header
    out.write("<html>\n  <head>\n    <title>Rapid - " + title
            + "</title>\n    <meta charset=\"utf-8\"/>\n    <link rel='stylesheet' type='text/css' href='styles/index.css'></link>\n  </head>\n");

    // write no permission
    out.write(
            "  <body>\n    <div class=\"image\"><img src=\"images/RapidLogo_60x40.png\" /></div>\n    <div class=\"title\"><span>Rapid - "
                    + title + "</span></div>\n    <div class=\"info\"><p>" + message
                    + "</p></div>\n  </body>\n</html>");

    out.println();

    out.close();

}

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

/**
 * Locate an existing location by its name, and optionally, state (short form) and/or country (long form).
 * @param req/*from w  w w . ja  va 2s  .  c om*/
 * @param resp
 */
private void findLocation(HttpServletRequest req, HttpServletResponse resp) {
    String locnName = req.getParameter("ln");
    String stateName = req.getParameter("sn");
    String cntryName = req.getParameter("cn");

    try {
        ArrayList<HashMap<String, String>> list = m_helper.locationsLike(locnName, stateName, cntryName);
        m_logger.debug("locationFilter locn lookup: " + locnName + " (" + stateName + ", " + cntryName + "): "
                + list.size());

        resp.setContentType("text/json");
        PrintWriter pm = resp.getWriter();
        pm.write(JSONValue.toJSONString(list));
        pm.close();
    } catch (PaperMinerException ex) {
        m_logger.error("lookup failed", ex);
        req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e305");
    } catch (IOException ex) {
        req.setAttribute(PaperMinerConstants.ERROR_PAGE, "e114");
    }
}