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:mercury.BaseHandler.java

protected void returnJson(final JSONObject json, final HttpServletResponse response) {
    try {//from   w w  w  . ja v  a  2  s  .c o  m
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        final PrintWriter out = response.getWriter();

        String r = json.toString();
        out.write(r.replaceAll("<", "&lt;").replace(">", "&gt;"));
        out.close();
    } catch (Exception e) {
        logError(e.getMessage(), e);
    }
}

From source file:com.bitranger.parknshop.seller.controller.SellerPublishProductCtrl.java

@RequestMapping(value = "/seller/getcategory", method = RequestMethod.POST)
public void getCategories(HttpServletRequest request, HttpServletResponse response) throws IOException {

    List<PsCategory> categories = categoryDAO.findAll();

    PrintWriter out = response.getWriter();

    JsonConfig jsonConfig = new JsonConfig();

    jsonConfig.setIgnoreDefaultExcludes(false);

    jsonConfig.setExcludes(new String[] { "psItems" });

    JSONArray jsonArray = JSONArray.fromObject(categories, jsonConfig);

    out.write(jsonArray.toString());
    out.flush();/*from   w  w  w  .ja v a2s  .c  o m*/
    out.close();

}

From source file:com.jredrain.startup.Bootstrap.java

/**
 *
 * @throws Exception/* ww w. ja  v a2s  .  co  m*/
 */

private void shutdown() throws Exception {
    /**
     * connect to startup socket and send stop command
     */
    Socket socket = new Socket("localhost", RedrainProperties.getInt("redrain.shutdown"));
    OutputStream os = socket.getOutputStream();
    PrintWriter pw = new PrintWriter(os);
    InputStream is = socket.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    pw.write(shutdown);
    pw.flush();
    socket.shutdownOutput();
    String reply = null;
    while (!((reply = br.readLine()) == null)) {
        logger.info("[redrain]shutdown:{}" + reply);
    }
    br.close();
    is.close();
    pw.close();
    os.close();
    socket.close();
}

From source file:com.bc.fiduceo.matchup.MatchupTool.java

void printUsageTo(OutputStream outputStream) {
    final String ls = System.lineSeparator();
    final PrintWriter writer = new PrintWriter(outputStream);
    writer.write("matchup-tool version " + VERSION_NUMBER);
    writer.write(ls + ls);//  w  ww  .  java2s.c o m

    final HelpFormatter helpFormatter = new HelpFormatter();
    helpFormatter.printHelp(writer, 120, "matchup-tool <options>", "Valid options are:", getOptions(), 3, 3,
            "");

    writer.flush();
}

From source file:colectordedatos.Generador.java

private void AnadirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AnadirActionPerformed

    String serie_nue = Serie_nueva.getText();
    String nom_nuevo = Nombre_nuevo.getText();
    String entity_nuevo = Enti_nueva.getText();
    JSONObject seriesArray1 = new JSONObject();
    seriesArray1 = this.seriesArray;

    JSONObject metricMatchCriteriaTemplate;
    try {/*from w  ww  .  jav  a 2  s.c  o  m*/
        metricMatchCriteriaTemplate = seriesArray1.getJSONObject("metricMatchCriteriaTemplate");
        JSONObject metricExpressionTemplate = metricMatchCriteriaTemplate
                .getJSONObject("metricExpressionTemplate");
        JSONObject scopeEntity = metricExpressionTemplate.getJSONObject("scopeEntity");
        try {
            seriesArray1.put("name", serie_nue);
            metricExpressionTemplate.put("metricPath", nom_nuevo);
            scopeEntity.put("entityName", entity_nuevo);

            this.seriesArray = seriesArray1;
        } catch (JSONException ex) {
            Logger.getLogger(Generador.class.getName()).log(Level.SEVERE, null, ex);
        }
    } catch (JSONException ex) {
        Logger.getLogger(Generador.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        dashboard.put("widgetTemplates", arrJSON);
    } catch (JSONException ex) {
        Logger.getLogger(Generador.class.getName()).log(Level.SEVERE, null, ex);
    }
    File f;
    f = new File("C:\\Users\\Administrador\\Documents\\NetBeansProjects\\GADD\\data.json");
    FileWriter w = null;
    try {
        w = new FileWriter(f);
    } catch (IOException ex) {
        Logger.getLogger(Generador.class.getName()).log(Level.SEVERE, null, ex);
    }
    BufferedWriter bw = new BufferedWriter(w);
    PrintWriter wr = new PrintWriter(bw);
    wr.write(dashboard.toString());//escribimos en el archivo
    wr.close();
    try {
        bw.close();
    } catch (IOException ex) {
        Logger.getLogger(Generador.class.getName()).log(Level.SEVERE, null, ex);
    }

    JOptionPane.showMessageDialog(this, "los datos se han transferido con exito", "mensaje",
            JOptionPane.INFORMATION_MESSAGE);

}

From source file:controllers.ServerController.java

public void uploadFile(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    String UPLOAD_DIRECTORY = "/opt/ppd";
    int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
    int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
    int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(MEMORY_THRESHOLD);
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(MAX_REQUEST_SIZE);

    File uploadDir = new File(UPLOAD_DIRECTORY);
    if (!uploadDir.exists())
        uploadDir.mkdir();/*from w  w  w.  ja  v  a 2 s.c  om*/

    try {
        // parses the request's content to extract file data
        @SuppressWarnings("unchecked")
        List<FileItem> formItems = upload.parseRequest(request);
        if (formItems != null && formItems.size() > 0) {
            // iterates over form's fields
            for (FileItem item : formItems) {
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    String filePath = UPLOAD_DIRECTORY + File.separator + fileName;
                    File storeFile = new File(filePath);
                    item.write(storeFile);
                    PrintWriter out = response.getWriter();
                    Runtime runtime = Runtime.getRuntime();
                    Process process = runtime.exec("/opt/script.sh " + fileName);
                    out.write("uplad success");
                    out.close();
                }
            }
        }
    } catch (Exception ex) {
        PrintWriter out = response.getWriter();
        out.write("There was an error: " + ex.getMessage().toString());
        out.close();
    }

}

From source file:com.github.zhanhb.ckfinder.connector.handlers.command.FileUploadCommand.java

/**
 * Executes file upload command.//w  w w.ja v a 2  s  . c o m
 *
 * @param param the parameter
 * @param request request
 * @param response
 * @param context ckfinder context
 * @throws ConnectorException when error occurs.
 * @throws IOException when IO Exception occurs.
 */
@Override
@SuppressWarnings("FinalMethod")
final void execute(FileUploadParameter param, HttpServletRequest request, HttpServletResponse response,
        CKFinderContext context) throws ConnectorException, IOException {
    String errorMsg = "";
    try {
        checkParam(param); // set in method initParams
        uploadFile(request, param, context);
        param.setUploaded(true);
        checkParam(param); // set in method uploadFile
    } catch (ConnectorException ex) {
        param.setErrorCode(ex.getErrorCode());
        errorMsg = ex.getMessage();
    }
    errorMsg = errorMsg.replace("%1", param.getNewFileName());
    String path = "";

    if (!param.isUploaded()) {
        param.setNewFileName("");
        param.setCurrentFolder("");
    } else {
        path = param.getType().getUrl() + param.getCurrentFolder();
    }
    setContentType(param, response);
    PrintWriter writer = response.getWriter();
    if ("txt".equals(param.getResponseType())) {
        writer.write(param.getNewFileName() + "|" + errorMsg);
    } else if (checkFuncNum(param)) {
        handleOnUploadCompleteCallFuncResponse(writer, errorMsg, path, param);
    } else {
        handleOnUploadCompleteResponse(writer, errorMsg, param);
    }
    writer.flush();
}

From source file:com.globalsight.connector.mindtouch.MindTouchCreateJobHandler.java

/**
 * Upload the job attachment file to server, and store it in session for
 * later use./*from ww w.  j a v a  2  s.co m*/
 */
@ActionHandler(action = "uploadAttachment", formClass = "")
public void uploadAttachment(HttpServletRequest request, HttpServletResponse response, Object form)
        throws Exception {
    FileUploader uploader = new FileUploader();
    File file = uploader.upload(request);

    HttpSession session = request.getSession();
    SessionManager sessionMgr = (SessionManager) session.getAttribute(SESSION_MANAGER);
    sessionMgr.setAttribute("uploadAttachment", file.getAbsolutePath());

    PrintWriter writer = response.getWriter();
    writer.write("<script type='text/javascript'>window.parent.addAttachment(' ')</script>;");

    pageReturn();
}

From source file:eg.agrimarket.controller.SignUpController.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request//from  w w  w . j a v a 2  s .  c  o m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("iam in get signup ");
    boolean CreditMsgIndicator = true;
    User user = new User();
    Credit credit = new Credit();
    UserDao userDaoImpl = new UserDaoImpl();
    String creditNumber = request.getParameter("creditnumber");

    System.out.println("iam in get signup credit number is :" + creditNumber);
    user.setCreditNumber(creditNumber);
    credit.setNumber(creditNumber);
    CreditDao creditDao = new CreditDaoImpl();
    PrintWriter printWriter = response.getWriter();

    if (creditDao.checkCredit(credit)) {//credit number is exist is 

        if (!(userDaoImpl.isCreditNumberAssigned(credit))) {
            System.out.println("creditExist = true;");
            printWriter.write("");
        } else {
            printWriter.write("we are sorry.. credit number is Assigened to other client .. !");

            CreditMsgIndicator = false;
            System.out.println("creditExist = falsefalse;");

        }
    } else {

        if (CreditMsgIndicator) {
            printWriter.write("This credit number doesn't exist");
            System.out.println("creditExist=false;");

        }
        CreditMsgIndicator = true;
        System.out.println("creditExist=false;");

    }

}

From source file:com.haulmont.ext.core.app.restapi.CreateCallfromOktell.java

@RequestMapping(method = RequestMethod.GET, value = "/task/call")
public void getTaskStates(HttpServletResponse response, @RequestParam(value = "s") String sessionId,
        @RequestParam(value = "p") String phone) throws IOException, JSONException {
    Authentication authentication = Authentication.me(sessionId);
    if (authentication == null) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;/*from  www. j a va2  s.  c  o  m*/
    }
    try {

        Call call = new Call();

        call.setName("? :" + phone);

        LoadContext catctx = new LoadContext(Category.class);
        catctx.setQueryString("select t from sys$Category t where t.id = :uuid").addParameter("uuid",
                UUID.fromString("053ae7ee-d327-4a90-909a-f540e4357324"));
        DataService catService = Locator.lookup(DataService.NAME);
        Category cat = catService.load(catctx);
        call.setCategory(cat);

        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String stringDate = formatter.format(TimeProvider.currentTimestamp());
        call.setCallDescription("?  ? : " + stringDate);

        Priority priority = findPriorityByOrder(3);
        call.setPriority(priority);
        call.setNumber(callGNS.getNextNumber(call));

        LoadContext procctx = new LoadContext(Proc.class);
        procctx.setQueryString("select p from wf$Proc p where p.name =:name").addParameter("name",
                " ");
        procctx.setView("edit");
        DataService procService = Locator.lookup(DataService.NAME);
        Proc proc = procService.load(procctx);
        call.setProc(proc);

        String roleInitiator = "oktell";
        String roleExecutor = "office_manager";

        String initiator = findUserByRole(roleInitiator).getLogin();
        String executor = findUserByRole(roleExecutor).getLogin();

        if (call.getRoles() == null) {
            call.setRoles(new ArrayList<CardRole>());
        }

        for (ProcRole procRole : proc.getRoles()) {
            if ((roleInitiator).equals(procRole.getCode()) && initiator != null) {
                updateCardRole(procRole, call, initiator);
            } else if ((roleExecutor).equals(procRole.getCode()) && executor != null)
                updateCardRole(procRole, call, executor);
        }

        Set<Entity> toCommit = new HashSet<Entity>();

        MetaClass metaClass = call.getMetaClass();
        for (MetaProperty metaProperty : metaClass.getProperties()) {
            Object value = call.getValue(metaProperty.getName());
            if (value instanceof List) {
                for (Object entity : ((List) value))
                    toCommit.add((Entity) entity);
            }
        }

        LoadContext extClt = new LoadContext(ExtClient.class);
        extClt.setQueryString("select c from ext$Client c where c.numberTel = :phone").addParameter("phone",
                phone);
        extClt.setView("_local");
        DataService dataServiceClt = Locator.lookup(DataService.NAME);
        ExtClient extClient = dataServiceClt.load(extClt);

        if (extClient != null) {
            call.setExtClient(extClient);
            call.setTelephoneNumber(extClient.getNumberTel());
            call.setCallDescription("?  ? : " + stringDate
                    + "  " + extClient.getName());
        }
        call.setTelephoneNumber(phone);

        //List<CardRole> roleList = call.getRoles().get(0).getProcRole().;

        toCommit.add(call);
        dataService.commit(new CommitContext(toCommit));

        wfService.startProcess(call);

        response.setStatus(HttpServletResponse.SC_OK);
        PrintWriter writer = new PrintWriter(response.getOutputStream());
        JSONObject responseJson = new JSONObject();
        responseJson.put("id", call.getId());
        writer.write(responseJson.toString());
        writer.close();

    } finally {
        authentication.forget();
    }
}