Example #1
1
  @Override
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    String text = null;

    try {
      text = getText(mapping, form, request, response);
    } catch (Exception e) {
      PortalUtil.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e, request, response);

      return null;
    }

    response.setContentType(ContentTypes.TEXT_PLAIN_UTF8);
    response.setHeader(HttpHeaders.CACHE_CONTROL, HttpHeaders.CACHE_CONTROL_NO_CACHE_VALUE);

    PrintWriter printWriter = response.getWriter();

    printWriter.write(text);

    printWriter.close();

    return null;
  }
Example #2
1
  public void run() {
    if (ServerSocket == null) return;
    while (true) {
      try {
        InetAddress address;
        int port;
        DatagramPacket packet;
        byte[] data = new byte[1460];
        packet = new DatagramPacket(data, data.length);
        ServerSocket.receive(packet);
        //
        //
        address = packet.getAddress();
        port = packet.getPort();
        System.out.println("get the Client port is: " + port);
        System.out.println("get the data length is: " + data.length);

        FileWriter fw = new FileWriter("Fortunes.txt");
        PrintWriter out = new PrintWriter(fw);
        for (int i = 0; i < data.length; i++) {
          out.print(data[i] + "  ");
        }
        out.close();
        System.out.println("Data has been writen to destination!");

        packet = new DatagramPacket(data, data.length, address, port);
        ServerSocket.send(packet);
        System.out.println("Respond has been made!");
      } catch (Exception e) {
        System.err.println("Exception: " + e);
        e.printStackTrace();
      }
    }
  }
  public static void main(String args[]) {

    long start = System.currentTimeMillis();

    PrintWriter outputStream = null;
    try {
      BufferedReader inputStream = new BufferedReader(new FileReader("myBinaryIntegers.dat"));
      outputStream = new PrintWriter(new FileOutputStream("myBinaryIntegers.txt"));

      System.out.println("Loading binary integers...");

      String line = inputStream.readLine();

      while (line != null) {
        // System.out.println(line);
        outputStream.print(line);
        line = inputStream.readLine();
      }

      outputStream.close();
      inputStream.close();
      System.out.println("Done with read in binary integers!");
    } catch (FileNotFoundException e) {
      System.out.println("File cannot be found when open for read.");
    } catch (IOException e) {
      System.out.println("Error reading.");
    }

    long end = System.currentTimeMillis();
    System.out.println("Took: " + ((end - start)) + "ms");
  }
Example #4
1
  public static void coding(String resource, String target) {
    BufferedReader reader = null;
    PrintWriter writer = null;
    try {
      FileInputStream in = new FileInputStream(resource);

      reader = new BufferedReader(new InputStreamReader(in, "GBK"));
      writer = new PrintWriter(target, "UTF-8");
      String line = null;
      while ((line = reader.readLine()) != null) {
        writer.println(line);
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      writer.close();
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
Example #5
1
  private void get(HttpServletRequest request, HttpServletResponse response) throws IOException {
    PrintWriter out = response.getWriter();
    String sPage = request.getParameter("page");
    String sRows = request.getParameter("rows");
    String order = request.getParameter("order");
    String sort = request.getParameter("sort");
    int page = 0;
    int rows = 0;
    if (sPage != null && sRows != null) {
      page = Integer.parseInt(sPage);
      rows = Integer.parseInt(sRows);
    }

    int total = service.count();
    List list = service.get(page, rows, order, sort);
    Map m = new HashMap();
    m.put("total", total);
    m.put("rows", list);

    JSONArray jsonArray = new JSONArray().fromObject(m);
    String json = jsonArray.toString();
    String j = json.substring(1, json.lastIndexOf("]"));

    out.write(j);
  }
  /**
   * Displays a message in the standard error stream if the value specified
   * by parameter <code>condition<code> is <code>false</code>.
   *
   * @param message  the error message.
   * @param condition  the test condition.
   */
  public static void assertTrue(String message, boolean condition) {

    if (!condition) {
      stdErr.print("** Test failure ");
      stdErr.println(message);
    }
  }
 @Override
 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
     throws Exception {
   Object usrLogin = request.getSession().getAttribute(Constants.SESS_USER_KEY);
   String sevPath = request.getServletPath();
   logger.info("ServletPath: " + sevPath);
   String rootPath = "";
   if (!StringUtil.isBlankOrNull(sevPath)
       && !sevPath.equals("/" + showLogin)
       && !sevPath.equals("/" + login)) {
     int len = sevPath.split("/").length;
     for (int i = 2; i < len; i++) {
       rootPath += "../";
     }
     if (usrLogin == null) {
       // response.sendRedirect(rootPath+showLogin);
       StringBuffer toLoginScript = new StringBuffer();
       toLoginScript.append("<script type=\"text/javascript\">");
       toLoginScript.append("top.window.location=\"" + rootPath + showLogin + "\"");
       toLoginScript.append("</script>");
       logger.info(toLoginScript);
       PrintWriter writer = response.getWriter();
       writer.write(toLoginScript.toString());
       writer.flush();
     }
   }
   return true;
 }
 /**
  * This is for debug only: print out training matrices in a CSV type format so that the matrices
  * can be examined in a spreadsheet program for debugging purposes.
  */
 private void WriteCSVfile(
     List<String> rowNames, List<String> colNames, float[][] buf, String fileName) {
   p("tagList.size()=" + tagList.size());
   try {
     FileWriter fw = new FileWriter(fileName + ".txt");
     PrintWriter bw = new PrintWriter(new BufferedWriter(fw));
     // write the first title row:
     StringBuffer sb = new StringBuffer(500);
     for (int i = 0, size = colNames.size(); i < size; i++) {
       sb.append("," + colNames.get(i));
     }
     bw.println(sb.toString());
     // loop on remaining rows:
     for (int i = 0, size = buf.length; i < size; i++) {
       sb.delete(0, sb.length());
       sb.append(rowNames.get(i));
       for (int j = 0, size2 = buf[i].length; j < size2; j++) {
         sb.append("," + buf[i][j]);
       }
       bw.println(sb.toString());
     }
     bw.close();
   } catch (IOException ioe) {
     ioe.printStackTrace();
   }
 }
 public void print(String filename, String text) throws IOException {
   PrintWriter out = new PrintWriter(filename);
   out.write(text);
   out.close();
   File file = new File(filename);
   System.out.println(file.getPath());
 }
  @Test
  public void testOpenSessionByNormalUser() throws Exception {
    long sessionLong = 555;
    String actionString = Action.OpenSession.toString();
    when(mockHttpServletRequest.getParameter(ServletUtil.ACTION)).thenReturn(actionString);
    when(mockHttpServletRequest.getParameter(ServletUtil.PROJECT)).thenReturn(projectString);

    // set AuthenticateOneTimeUser false
    prepareEnterAuthenticateOneTimeUser(false);
    User user = stubbingCheckUser();

    UsersCache userCacheHelper = mock(UsersCache.class);
    mockStatic(UsersCacheFactory.class);
    when(UsersCacheFactory.getInstance()).thenReturn(userCacheHelper);
    when(userCacheHelper.logWithProjectLabel(loginString, CLIENT_TYPE, projectString))
        .thenReturn(sessionLong);

    // RUN...
    defaultConnectionStrategy.execute(mockHttpServletRequest, mockHttpServletResponse);

    verifyNecessaryChecks(actionString);

    verifyStatic(org.mockito.Mockito.times(1));
    ConnectionUtil.checkUser(loginString, password, false);

    PrintWriter writer = mockHttpServletResponse.getWriter();
    writer.flush();
    System.out.println(outStringWriter.toString());
    // ASSERT...
    assertThat(outStringWriter.toString(), is("RESPONSE:" + String.valueOf(sessionLong)));
  }
  @Test
  public void testListProjectsActionByNormalUser() throws Exception {
    String actionString = Action.ListProjects.toString();

    when(mockHttpServletRequest.getParameter(ServletUtil.ACTION)).thenReturn(actionString);

    // set AuthenticateOneTimeUser false
    prepareEnterAuthenticateOneTimeUser(false);
    User user = stubbingCheckUser();

    String xmi = constructProjectsObjectsXmi();
    doThrow(
            new org.talend.gwtadministrator.server.remoteconnection.ConnectionUtil
                .ResponseException(xmi))
        .when(ConnectionUtil.class);
    ConnectionUtil.listAuthorizedProjects(user);

    // RUN...
    defaultConnectionStrategy.execute(mockHttpServletRequest, mockHttpServletResponse);

    verifyNecessaryChecks(actionString);

    verifyStatic(org.mockito.Mockito.times(1));
    ConnectionUtil.checkUser(loginString, password, false);

    verifyStatic(org.mockito.Mockito.times(1));
    ConnectionUtil.listAuthorizedProjects(user);

    PrintWriter writer = mockHttpServletResponse.getWriter();
    writer.flush();
    System.out.println(outStringWriter.toString());
    // ASSERT...
    assertThat(outStringWriter.toString(), is("RESPONSE:" + xmi));
  }
  @Test
  public void testLoginActionByAuthenticateOneTimeUser() throws Exception {
    String actionString = Action.Login.toString();
    when(mockHttpServletRequest.getParameter(ServletUtil.ACTION)).thenReturn(actionString);
    when(mockHttpServletRequest.getParameter(ServletUtil.PROJECT)).thenReturn(projectString);

    // set AuthenticateOneTimeUser true
    prepareEnterAuthenticateOneTimeUser(true);

    String xmi = constructProjectsObjectsXmi();
    doThrow(
            new org.talend.gwtadministrator.server.remoteconnection.ConnectionUtil
                .ResponseException(xmi))
        .when(ConnectionUtil.class);
    ConnectionUtil.returnProjectAndUsers(anyString(), (User) any(), anyBoolean());

    // RUN...
    defaultConnectionStrategy.execute(mockHttpServletRequest, mockHttpServletResponse);

    verifyNecessaryChecks(actionString);

    // verify called listAllProjects once
    verifyStatic(org.mockito.Mockito.times(1));
    ConnectionUtil.returnProjectAndUsers(anyString(), (User) any(), anyBoolean());

    PrintWriter writer = mockHttpServletResponse.getWriter();
    writer.flush();
    System.out.println(outStringWriter.toString());
    // ASSERT...
    assertThat(outStringWriter.toString(), is("RESPONSE:" + xmi));
  }
Example #13
0
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    // String county= request.getParameter("county").toString();
    String countyid = request.getParameter("countyid");
    String id = request.getParameter("id");
    String value = request.getParameter("value");
    String columnName = request.getParameter("columnName");
    String columnId = request.getParameter("columnId");
    String columnPosition = request.getParameter("columnPosition");
    String rowId = request.getParameter("rowId");
    response.getWriter().print(value);
    HttpSession session;

    session = request.getSession(true);
    //  String unique=(String)session.getAttribute("countyid");
    dbConnect conn = new dbConnect();

    String query =
        "update behaviourscode set BehavioursCode='"
            + value
            + "'where BehavioursCodeID='"
            + id
            + "'";

    try {
      conn.state.executeUpdate(query);

      //                   response.sendRedirect("CountyServlet");
    } catch (SQLException ex) {
      Logger.getLogger(UpdateBehaviour.class.getName()).log(Level.SEVERE, null, ex);
      out.println(ex.toString());
    }
  }
  static {
    String dummy = System.getenv(EnvVarNames.CCP_TASKSYSTEMID);
    taskid = -1;
    if (!Utility.isNullOrEmpty(dummy)) {
      try {
        taskid = Integer.parseInt(dummy);
      } catch (NumberFormatException e) {
        // taskid stays at -1;
      }
    }

    dummy = System.getenv(EnvVarNames.CCP_JOBID);
    jobid = -1;
    if (!Utility.isNullOrEmpty(dummy)) {
      try {
        jobid = Integer.parseInt(dummy);
      } catch (NumberFormatException e) {
        // jobid stays at -1;
      }
    }

    dummy = System.getenv(EnvVarNames.LONG_LOADING_TEST);
    if (!Utility.isNullOrEmpty(dummy)) {
      try {
        Thread.sleep(30 * 1000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }

    scheduler = System.getenv(EnvVarNames.CCP_SCHEDULER);
    try {
      String logPath = System.getenv(EnvVarNames.GRACEFUL_EXIT);
      if (!Utility.isNullOrEmpty(logPath)) {
        File baseDir = new File(logPath);
        File logDir = new File(baseDir, "CCP_AITest_Trace_" + jobid);
        File logFile = new File(logDir, taskid + ".txt");

        if (!System.getenv("CCP_OnAzure").equals("1")) {
          try {
            logDir.mkdirs();
          } catch (Exception e) {
            e.printStackTrace();
          }
          PrintWriter writer = new PrintWriter(new FileWriter(logFile, true));
          writer.println(Utility.getCurrentTime() + ": Svchost starts.");
          writer.close();
        }
        System.out.println(Utility.getCurrentTime() + ": Svchost starts.");

        ServiceContext.exitingEvents.addMyEventListener(new DefaultOnExitHandler(logFile));
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    String pid = ManagementFactory.getRuntimeMXBean().getName();
    int index = pid.indexOf("@");
    processId = Integer.parseInt(pid.substring(0, index));
  }
Example #15
0
  // Implementation methods
  // -------------------------------------------------------------------------
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    try {
      WebClient client = WebClient.getWebClient(request);
      Session session = client.getSession();
      Queue queue = getQueue(request, session);
      if (queue == null) {
        throw new ServletException("No queue URI specified");
      }

      String msgId = request.getParameter("msgId");
      if (msgId == null) {
        MessageRenderer renderer = getMessageRenderer(request);
        configureRenderer(request, renderer);

        String selector = getSelector(request);
        QueueBrowser browser = session.createBrowser(queue, selector);
        renderer.renderMessages(request, response, browser);
      } else {
        XmlMessageRenderer renderer = new XmlMessageRenderer();
        QueueBrowser browser = session.createBrowser(queue, "JMSMessageID='" + msgId + "'");
        if (!browser.getEnumeration().hasMoreElements()) {
          response.sendError(HttpServletResponse.SC_NOT_FOUND);
          return;
        }
        Message message = (Message) browser.getEnumeration().nextElement();

        PrintWriter writer = response.getWriter();
        renderer.renderMessage(writer, request, response, browser, message);
        writer.flush();
      }
    } catch (JMSException e) {
      throw new ServletException(e);
    }
  }
  protected void processDocument(
      String jsonDocument,
      PrintWriter writer,
      List<Class<? extends AbstractBpmnFactory>> factoryClasses)
      throws JSONException, BpmnConverterException {
    Diagram diagram = DiagramBuilder.parseJson(jsonDocument);

    // TODO: validate edges that are not in the java object model
    //		ArrayList<Shape> edges =
    this.getEdgesFromDiagram(diagram.getChildShapes());

    String type = diagram.getStencilset().getNamespace();
    SyntaxChecker checker = null;

    if (type != null
        && (type.equals("http://b3mn.org/stencilset/bpmn2.0#")
            || type.equals("http://b3mn.org/stencilset/bpmn2.0choreography#")
            || type.equals("http://b3mn.org/stencilset/bpmn2.0conversation#"))) {
      checker = getCheckerBPMN2(diagram, factoryClasses);
    }

    if (checker == null) {
      writer.print("{}");
    } else {
      checker.checkSyntax();
      writer.print(checker.getErrorsAsJson().toString());
    }
  }
Example #17
0
  public synchronized String format(LogRecord record) {
    StringBuffer sb = new StringBuffer();
    date.setTime(record.getMillis() + timeDiff);
    sb.append(dFormat.format(date));
    if (isShowingThreads) {
      Thread currentThread = Thread.currentThread();
      if (currentThread != lastThread) {
        lastThread = currentThread;
        lastThreadName = currentThread.getName();
      }
      sb.append(" [").append(lastThreadName).append(']');
    }
    sb.append(' ')
        .append(record.getLevel())
        .append(' ')
        .append(getAliasFor(record.getLoggerName()))
        .append('|')
        .append(record.getMessage())
        .append(EOL);

    if (record.getThrown() != null) {
      try {
        StringWriter out = new StringWriter();
        PrintWriter pout = new PrintWriter(out);
        record.getThrown().printStackTrace(pout);
        pout.close();
        sb.append(out.toString());
      } catch (Exception e) {
        // Ignore any errors while extracting stack trace
      }
    }

    return sb.toString();
  }
  @Test
  public void testCloseSessionByNormalUser() throws Exception {
    String sessionIdString = "555";
    String actionString = Action.CloseSession.toString();
    long sessionIdLong = Long.parseLong(sessionIdString);
    when(mockHttpServletRequest.getParameter(ServletUtil.ACTION)).thenReturn(actionString);
    when(mockHttpServletRequest.getParameter(ServletUtil.SESSION_ID)).thenReturn(sessionIdString);

    // set AuthenticateOneTimeUser false
    prepareEnterAuthenticateOneTimeUser(false);
    User user = stubbingCheckUser();

    UsersCache userCacheHelper = mock(UsersCache.class);
    mockStatic(UsersCacheFactory.class);
    when(UsersCacheFactory.getInstance()).thenReturn(userCacheHelper);
    doNothing().when(userCacheHelper);
    userCacheHelper.remove(sessionIdLong);

    // RUN...
    defaultConnectionStrategy.execute(mockHttpServletRequest, mockHttpServletResponse);

    verifyNecessaryChecks(actionString);

    verifyStatic(org.mockito.Mockito.times(1));
    ConnectionUtil.checkUser(loginString, password, false);

    PrintWriter writer = mockHttpServletResponse.getWriter();
    writer.flush();
    System.out.println(outStringWriter.toString());
    // ASSERT...
    assertThat(outStringWriter.toString(), is("RESPONSE:" + String.valueOf(sessionIdLong)));
  }
  public static final String format(Throwable toss) {
    StringWriter sw = new StringWriter();

    // Improved nested exception handling
    PrintWriter pw =
        new PrintWriter(sw) {
          boolean stop = false;

          @Override
          public void print(String s) {
            if (s.startsWith("Caused by")) stop = true;
            else if (!s.startsWith(" ") && !s.startsWith("\t")) stop = false;
            if (!stop) super.print(s);
          }

          @Override
          public void println() {
            if (!stop) super.println();
          }
        };
    for (Throwable t = toss; t != null; ) {
      t.printStackTrace(pw);
      t = t.getCause();
      if (t != null) pw.append("Caused by: ");
    }
    return sw.toString();
  }
  public static void main(String[] args) throws IOException {
    BufferedReader f = new BufferedReader(new FileReader("beads.in"));
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("beads.out")));
    int n = Integer.parseInt(f.readLine());
    String s = f.readLine();
    int max = Integer.MIN_VALUE;

    for (int i = 0; i < n; i++) {
      String straight = s.substring(i + 1) + s.substring(0, i + 1);
      char[] beads = straight.toCharArray();
      int temp = 0;
      char color = ' ';
      for (int j = 0; j < n; j++) {
        char currColor = beads[j];
        if (color == ' ' && currColor != 'w') color = currColor;
        if (currColor == color || currColor == 'w') temp++;
        else break;
      }

      color = ' ';
      for (int j = n - 1; j > -1; j--) {
        char currColor = beads[j];
        if (color == ' ' && currColor != 'w') color = currColor;
        if (currColor == color || currColor == 'w') temp++;
        else break;
      }
      max = Math.max(temp, max);
    }
    if (max > n) max = n;
    out.println(max);
    out.close();
    System.exit(0);
  }
Example #21
0
  @Override
  protected void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/xml");
    response.setCharacterEncoding("UTF-8");

    System.out.println("*** Data tags");
    String sid = (String) request.getParameter("sid");
    if (sid == null) throw new IOException("Invalid session");

    String firstLetter = (String) request.getParameter("firstLetter");

    // Headers required by Internet Explorer
    response.setHeader("Pragma", "public");
    response.setHeader("Cache-Control", "must-revalidate, post-check=0,pre-check=0");
    response.setHeader("Expires", "0");

    PrintWriter writer = response.getWriter();
    writer.write("<list>");
    for (int i = 0; i < 1000; i++) {
      writer.print("<tag>");
      writer.print("<index>" + i + "</index>");
      if (firstLetter != null) {
        writer.print("<word>" + firstLetter.charAt(0) + "tag" + i + "</word>");
        writer.print("<count>" + i + "</count>");
      } else {
        writer.print("<word>tag" + i + "</word>");
        writer.print("<count></count>");
      }
      writer.print("</tag>");
    }
    writer.write("</list>");
  }
  public void solve() throws IOException {
    MyReader in = new MyReader();
    PrintWriter out = new PrintWriter(System.out);

    while (true) {
      int n = in.nextInt();
      if (n == 0) break;
      int m = in.nextInt(), g = in.nextInt(), score[] = new int[m];
      for (int i = 0; i < m; i++) score[i] = in.nextInt();

      Student students[] = new Student[n];
      for (int i = 0; i < n; i++) {
        String name = in.next();
        int cnt = in.nextInt(), totScore = 0;
        for (int j = 0; j < cnt; j++) totScore += score[in.nextInt() - 1];
        students[i] = new Student(name, totScore);
      }
      Arrays.sort(students);

      int pass_cnt = 0;
      for (; pass_cnt < n && students[pass_cnt].getScore() >= g; pass_cnt++) ;
      out.println(pass_cnt);
      for (int i = 0; i < pass_cnt; i++) students[i].print(out);

      out.flush();
    }
  }
Example #23
0
 /**
  * 返回处理结果给财付通服务器。
  *
  * @param msg: Success or fail。
  * @throws IOException
  */
 public void sendToCFT(String msg) throws IOException {
   String strHtml = msg;
   PrintWriter out = this.getHttpServletResponse().getWriter();
   out.println(strHtml);
   out.flush();
   out.close();
 }
Example #24
0
  public static void main(String[] args) throws IOException {
    int choice;

    PrintWriter pw = new PrintWriter(new FileWriter("csis.txt"));
    Decimal dec = new Decimal(pw);
    Binary bin = new Binary(pw);
    Hexadecimal hex = new Hexadecimal(pw);
    Menu menu = new Menu(pw);

    do {
      menu.display();
      choice = menu.getSelection();
      switch (choice) {
        case 1:
          dec.decToBin();
          break;
        case 2:
          dec.decToHex();
          break;
        case 3:
          bin.binToDec();
          break;
        case 4:
          bin.binToHex();
          break;
        case 5:
          hex.hexToDec();
          break;
        case 6:
          hex.hexToBin();
          break;
      }
    } while (choice != 7);
    pw.close();
  }
Example #25
0
  // 修改学院信息
  private void edit(HttpServletRequest request, HttpServletResponse response) throws IOException {
    PrintWriter out = response.getWriter();
    JsonBean j = new JsonBean();
    int id = Integer.parseInt(request.getParameter("id"));
    int college_num = Integer.parseInt(request.getParameter("college_num"));
    int college_state = Integer.parseInt(request.getParameter("college_state"));
    String college_name = request.getParameter("college_name");

    College co = new College();
    co.setCollege_name(college_name);
    co.setCollege_num(college_num);
    co.setCollege_state(college_state);
    co.setId(id);

    if (service.edit(co)) {
      j.setSuccess(true);
      j.setMsg("修改[" + college_name + "]成功!");
    } else {
      j.setMsg("修改[" + college_name + "]失败!");
    }

    JSONArray jsonArray = new JSONArray().fromObject(j);
    String jsonS = jsonArray.toString();
    String json = jsonS.substring(1, jsonS.lastIndexOf("]"));
    out.write(json);
  }
 private void write(HttpServletResponse response, String resultado) throws IOException {
   response.setContentType("text/html");
   PrintWriter writer = response.getWriter();
   writer.print(resultado);
   writer.flush();
   writer.close();
 }
  public void run() {
    System.out.println("New Communication Thread Started");

    try {
      PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
      BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

      String inputLine;
      String[] inputTemp = new String[3];

      while ((inputLine = in.readLine()) != null) {
        System.out.println("Server: " + inputLine);

        out.println(inputLine);

        if (inputLine.equals("Bye.")) break;
      }

      out.close();
      in.close();
      clientSocket.close();
    } catch (IOException e) {
      System.err.println("Problem with Communication Server");
      System.exit(1);
    }
  }
  protected void processDocument(Document document, PrintWriter writer) {
    String type = new StencilSetUtil().getStencilSet(document);
    SyntaxChecker checker = null;
    if (type != null) {
      if (type.equals("bpmn.json") || type.equals("bpmneec.json"))
        checker = getCheckerBPMN(document);
      else if (type.equals("bpmn1.1.json")) checker = getCheckerBPMN11(document);
      else if (type.equals("ibpmn.json")) checker = getCheckerIBPMN(document);
      else if (type.equals("interactionpetrinets.json")) checker = getCheckerIPN(document);
      else if (type.equals("epc.json")) checker = getCheckerEPC(document);
    }

    if (checker == null) { // try eRDF
      try {
        NamedNodeMap map =
            XPathAPI.selectSingleNode(document, "//a[@rel='oryx-stencilset']").getAttributes();
        type = map.getNamedItem("href").getNodeValue();
      } catch (TransformerException e) {
        e.printStackTrace();
      }
      if (type != null && type.endsWith("petrinet.json")) {
        checker = getCheckerPetriNet(document);
      }
    }

    if (checker == null) {
      writer.print("{}");
    } else {
      checker.checkSyntax();
      writer.print(checker.getErrorsAsJson().toString());
    }
  }
Example #29
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    // 接收时设置的编码
    request.setCharacterEncoding("utf-8");
    // 转发时设置的编码
    response.setCharacterEncoding("utf-8");
    // 以 超文本格式 方式转发
    response.setContentType("text/html");
    // 获取了一个输出流
    PrintWriter out = response.getWriter();

    // 修改库存数量Ajax
    String id = request.getParameter("id");
    String number = request.getParameter("number");
    NeProductsDao neProductsDao = new NeProductsDaoImpl();
    int count = neProductsDao.updateNumber(Integer.parseInt(id), Integer.parseInt(number));
    if (count > 0) {
      out.println("商品" + id + "库存数量修改成功");
    } else {
      out.println("商品" + id + "库存数量修改失败");
    }

    out.flush();
    out.close();
  }
Example #30
0
  public void run() {
    // on mac os x 10.5.x, when i run a 'sudo' command, i need to write
    // the admin password out immediately; that's why this code is
    // here.
    if (sudoIsRequested) {
      // doSleep(500);
      printWriter.println(adminPassword);
      printWriter.flush();
    }

    BufferedReader bufferedReader = null;
    try {
      bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
      String line = null;
      while ((line = bufferedReader.readLine()) != null) {
        outputBuffer.append(line + "\n");
      }
    } catch (IOException ioe) {

      ioe.printStackTrace();
    } catch (Throwable t) {

      t.printStackTrace();
    } finally {
      try {
        bufferedReader.close();
      } catch (IOException e) {
        // ignore this one
      }
    }
  }