Example usage for java.io PrintWriter append

List of usage examples for java.io PrintWriter append

Introduction

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

Prototype

public PrintWriter append(char c) 

Source Link

Document

Appends the specified character to this writer.

Usage

From source file:org.codice.ddf.registry.federationadmin.service.impl.FederationAdminServiceImpl.java

private String stringifyProcessingErrors(Set<ProcessingDetails> details) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);

    for (ProcessingDetails detail : details) {
        pw.append(detail.getSourceId());
        pw.append(":");
        if (detail.hasException()) {
            detail.getException().printStackTrace(pw);
        }//  w  w w. java 2  s  . c o m
        pw.append(System.lineSeparator());
    }
    return pw.toString();
}

From source file:com.alexkli.jhb.Worker.java

@Override
public void run() {
    try {/*from   w w w .  j a  va2 s  .  c  o m*/
        while (true) {
            long start = System.nanoTime();

            QueueItem<HttpRequestBase> item = queue.take();

            idleAvg.add(System.nanoTime() - start);

            if (item.isPoisonPill()) {
                return;
            }

            HttpRequestBase request = item.getRequest();

            if ("java".equals(config.client)) {
                System.setProperty("http.keepAlive", "false");

                item.sent();

                try {
                    HttpURLConnection http = (HttpURLConnection) new URL(request.getURI().toString())
                            .openConnection();
                    http.setConnectTimeout(5000);
                    http.setReadTimeout(5000);
                    int statusCode = http.getResponseCode();

                    consumeAndCloseStream(http.getInputStream());

                    if (statusCode == 200) {
                        item.done();
                    } else {
                        item.failed();
                    }
                } catch (IOException e) {
                    System.err.println("Failed request: " + e.getMessage());
                    e.printStackTrace();
                    //                        System.exit(2);
                    item.failed();
                }
            } else if ("ahc".equals(config.client)) {
                try {
                    item.sent();

                    try (CloseableHttpResponse response = httpClient.execute(request, context)) {
                        int statusCode = response.getStatusLine().getStatusCode();
                        if (statusCode == 200) {
                            item.done();
                        } else {
                            item.failed();
                        }
                    }
                } catch (IOException e) {
                    System.err.println("Failed request: " + e.getMessage());
                    item.failed();
                }
            } else if ("fast".equals(config.client)) {
                try {
                    URI uri = request.getURI();

                    item.sent();

                    InetAddress addr = InetAddress.getByName(uri.getHost());
                    Socket socket = new Socket(addr, uri.getPort());
                    PrintWriter out = new PrintWriter(socket.getOutputStream());
                    //                        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    // send an HTTP request to the web server
                    out.println("GET / HTTP/1.1");
                    out.append("Host: ").append(uri.getHost()).append(":").println(uri.getPort());
                    out.println("Connection: Close");
                    out.println();
                    out.flush();

                    // read the response
                    consumeAndCloseStream(socket.getInputStream());
                    //                        boolean loop = true;
                    //                        StringBuilder sb = new StringBuilder(8096);
                    //                        while (loop) {
                    //                            if (in.ready()) {
                    //                                int i = 0;
                    //                                while (i != -1) {
                    //                                    i = in.read();
                    //                                    sb.append((char) i);
                    //                                }
                    //                                loop = false;
                    //                            }
                    //                        }
                    item.done();
                    socket.close();

                } catch (IOException e) {
                    e.printStackTrace();
                    item.failed();
                }
            } else if ("nio".equals(config.client)) {
                URI uri = request.getURI();

                item.sent();

                String requestBody = "GET / HTTP/1.1\n" + "Host: " + uri.getHost() + ":" + uri.getPort() + "\n"
                        + "Connection: Close\n\n";

                try {
                    InetSocketAddress addr = new InetSocketAddress(uri.getHost(), uri.getPort());
                    SocketChannel channel = SocketChannel.open();
                    channel.socket().setSoTimeout(5000);
                    channel.connect(addr);

                    ByteBuffer msg = ByteBuffer.wrap(requestBody.getBytes());
                    channel.write(msg);
                    msg.clear();

                    ByteBuffer buf = ByteBuffer.allocate(1024);

                    int count;
                    while ((count = channel.read(buf)) != -1) {
                        buf.flip();

                        byte[] bytes = new byte[count];
                        buf.get(bytes);

                        buf.clear();
                    }
                    channel.close();

                    item.done();

                } catch (IOException e) {
                    e.printStackTrace();
                    item.failed();
                }
            }
        }
    } catch (InterruptedException e) {
        System.err.println("Worker thread [" + this.toString() + "] was interrupted: " + e.getMessage());
    }
}

From source file:com.silverpeas.form.displayers.AbstractFileFieldDisplayer.java

/**
 * Prints the javascripts which will be used to control the new value given to the named field.
 * The error messages may be adapted to a local language. The FieldTemplate gives the field type
 * and constraints. The FieldTemplate gives the local labeld too. Never throws an Exception but
 * log a silvertrace and writes an empty string when :
 * <UL>//from   w  w w  .jav a2  s  .c  o m
 * <LI>the fieldName is unknown by the template.
 * <LI>the field type is not a managed type.
 * </UL>
 *
 * @param pageContext
 */
@Override
public void displayScripts(final PrintWriter out, final FieldTemplate template, final PagesContext pageContext)
        throws IOException {
    checkFieldType(template.getTypeName(), "AbstractFileFieldDisplayer.displayScripts");
    String language = pageContext.getLanguage();
    String fieldName = template.getFieldName();
    if (template.isMandatory() && pageContext.useMandatory()) {
        out.append("  if (isWhitespace(stripInitialWhitespace(field.value))) {\n").append("   var ")
                .append(fieldName).append("Value = document.getElementById('").append(fieldName)
                .append(FileField.PARAM_ID_SUFFIX).append("').value;\n").append("   var ").append(fieldName)
                .append("Operation = document.").append(pageContext.getFormName()).append(".").append(fieldName)
                .append(OPERATION_KEY).append(".value;\n").append("   if (").append(fieldName)
                .append("Value=='' || ").append(fieldName).append("Operation=='")
                .append(Operation.DELETION.name()).append("') {\n").append("     errorMsg+=\"  - '")
                .append(EncodeHelper.javaStringToJsString(template.getLabel(language))).append("' ")
                .append(Util.getString("GML.MustBeFilled", language)).append("\\n \";\n")
                .append("     errorNb++;\n").append("   }\n").append(" }\n");
    }

    if (!template.isReadOnly()) {
        Util.includeFileNameLengthChecker(template, pageContext, out);
        Util.getJavascriptChecker(template.getFieldName(), pageContext, out);
    }
}

From source file:org.uberfire.server.UberfireServlet.java

private void loadUserInfo(PrintWriter writer) {
    final Subject subject = SecurityFactory.getIdentity();

    final Map<String, String> map = new HashMap<String, String>() {
        {//from  www  .  ja  v  a 2 s .c o  m
            put("name", subject.getName());
            put("roles", collectionAsString(subject.getRoles()));
            put("properties", mapAsString(subject.getProperties()));
        }
    };

    final String content = TemplateRuntime.execute(userDataTemplate, map).toString();

    writer.append(content);
}

From source file:com.softwarementors.extjs.djn.router.RequestRouter.java

public void processSourceRequest(BufferedReader reader, PrintWriter writer, String pathInfo) {
    assert reader != null;
    assert writer != null;
    assert pathInfo != null;

    int lastIndex = pathInfo.lastIndexOf(SOURCE_NAME_PREFIX);
    int position = lastIndex + SOURCE_NAME_PREFIX.length();
    String sourceName = pathInfo.substring(position + 1);
    if (!this.registry.hasSource(sourceName)) {
        RequestException ex = RequestException.forSourceNotFound(sourceName);
        logger.error(sourceName);//  w  w  w . j ava 2 s  .c  o m
        throw ex;
    }
    String code = this.registry.getSource(sourceName);
    assert code != null;
    writer.append(code);
}

From source file:tpt.dbweb.cat.Compare.java

public void compare(List<Iterator<TaggedText>> ttIts, List<String> infos, Path out,
          List<ComparisonResult> evaluations) throws IOException {
      boolean docEvaluationNotFound = false;

      StringWriter sw = new StringWriter();
      PrintWriter ps = new PrintWriter(sw);
      ps.append("<annotators>\n");
      // load files and print annotator info
      for (int i = 0; i < ttIts.size(); i++) {
          ps.append("\t<annotator id='" + i + "' file='");
          ps.append(StringEscapeUtils.escapeXml11(infos.get(i)));
          ps.append("'/>\n");
      }/*  w  ww. ja  va 2s.c  om*/
      ps.append("</annotators>\n");

      // print evaluation
      List<Map<String, EvaluationStatistics>> evals = new ArrayList<>();
      Map<String, EvaluationStatistics> eval;
      if (evaluations != null) {
          for (int i = 0; i < evaluations.size(); i++) {
              ComparisonResult combinedEvaluations = evaluations.get(i).combine();
              eval = new TreeMap<>();
              evals.add(eval);

              // type is macro / micro
              for (String type : combinedEvaluations.docidToMetricToResult.keySet()) {
                  Map<String, EvaluationStatistics> metricToResult = combinedEvaluations.docidToMetricToResult
                          .get(type);
                  for (String metric : metricToResult.keySet()) {
                      eval.put(metric + " (" + type + ")", metricToResult.get(metric));
                  }
              }
          }
          ps.print(printMetrics(evals));
          evals.clear();
      }

      // print comparison of articles
      while (ttIts.stream().allMatch(it -> it.hasNext())) {
          List<TaggedText> tts = ttIts.stream().map(it -> it.next()).collect(Collectors.toList());
          tts.forEach(tt -> cleanUp(tt));
          if (!checkTaggedTexts(infos, tts)) {
              break;
          }

          // do comparison and write to output
          ps.print("  <article id='");
          ps.print(tts.get(0).id);
          ps.println("'>");

          ps.print(compare(tts));
          ps.println();

          // print evaluation of article
          if (evaluations != null) {
              docEvaluationNotFound = true;
              for (int i = 0; i < evaluations.size(); i++) {
                  eval = evaluations.get(i).docidToMetricToResult.get(tts.get(0).id);
                  evals.add(eval);
                  if (eval != null) {
                      docEvaluationNotFound = false;
                  }
              }
              if (docEvaluationNotFound == false) {
                  ps.print(printMetrics(evals));
              } else {
              }
          } else {
              docEvaluationNotFound = true;
          }
          if (docEvaluationNotFound) {
              log.warn("evaluation not found for {}", tts.get(0).id);
          }
          ps.println("  </article>");
      }

      if (docEvaluationNotFound && evaluations != null && evaluations.size() > 0) {
          log.warn("available evaluations: {}", evaluations.get(0).docidToMetricToResult.keySet());
      }

      // load template and replace <article/>
      String template = Utility.readResourceAsString("compare-template.xml");
      sw.toString();
      String output = template.replace("<article/>", sw.toString());
      FileUtils.writeStringToFile(out.toFile(), output);
  }

From source file:org.pentaho.platform.pdi.WebContextServlet.java

private void writeDocumentWriteResource(PrintWriter writer, String location) {
    boolean isJavascript = location.endsWith(".js");

    writer.write("document.write(\"");

    if (isJavascript) {
        writer.write("<script type='text/javascript' src=");
    } else {/*from  w w w  . j  av a 2  s .c o m*/
        writer.write("<link rel='stylesheet' type='text/css' href=");
    }

    writer.write("'\" + CONTEXT_PATH + \"" + location + "'>");

    writer.append(isJavascript ? ("</scr\" + \"ipt>") : "");
    writer.write("\");\n");
}

From source file:org.silverpeas.core.notification.sse.AbstractServerEventDispatcherTaskTest.java

SilverpeasAsyncContext newMockedAsyncContext(final String sessionId) throws Exception {
    SilverpeasAsyncContext mock = mock(SilverpeasAsyncContext.class);
    HttpServletRequest mockedRequest = mock(HttpServletRequest.class);
    HttpServletResponse mockedResponse = mock(HttpServletResponse.class);
    PrintWriter mockedPrintWriter = mock(PrintWriter.class);
    when(mock.getMutex()).thenReturn(mock);
    when(mock.isSendPossible()).thenReturn(true);
    when(mock.getUser()).thenReturn(new UserDetail());
    when(mock.getRequest()).thenReturn(mockedRequest);
    when(mock.getResponse()).thenReturn(mockedResponse);
    when(mock.getSessionId()).thenReturn(sessionId);
    when(mock.getLastServerEventId()).thenReturn(null);
    when(mockedRequest.getRequestURI()).thenReturn(EVENT_SOURCE_REQUEST_URI);
    when(mockedResponse.getWriter()).thenReturn(mockedPrintWriter);
    when(mockedPrintWriter.append(anyString())).thenReturn(mockedPrintWriter);
    return mock;//ww  w. j  ava  2s .c  o m
}

From source file:org.opentox.toxotis.client.https.PostHttpsClient.java

private void postMultiPart() throws ServiceInvocationException {
    String charset = "UTF-8";
    String LINE_FEED = "\r\n";
    InputStream is;/*from w  w  w . j a v a 2s .c o  m*/

    try {
        getPostLock().lock(); // LOCK

        is = new FileInputStream(fileContentToPost);

        // creates a unique boundary based on time stamp
        long boundaryTs = System.currentTimeMillis();
        String boundary = "===" + boundaryTs + "===";

        HttpURLConnection httpConn = connect(getUri().toURI());
        httpConn.setUseCaches(false);
        httpConn.setDoOutput(true); // indicates POST method
        httpConn.setDoInput(true);
        httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=\"" + boundary + "\"");
        httpConn.setRequestProperty("User-Agent", "CodeJava Agent");
        httpConn.setRequestProperty("Test", "Bonjour");

        OutputStream outputStream = httpConn.getOutputStream();
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true);

        final int nParams = postParameters.size();

        if (nParams > 0) {

            for (Map.Entry<String, String> e : postParameters.entrySet()) {
                writer.append("--" + boundary).append(LINE_FEED);
                writer.append("Content-Disposition: form-data; name=\"" + e.getKey() + "\"").append(LINE_FEED);
                writer.append("Content-Type: text/plain; charset=" + charset).append(LINE_FEED);
                writer.append(LINE_FEED);
                writer.append(e.getValue()).append(LINE_FEED);
                writer.flush();
            }
        }

        if (is.read() > 0) {
            is.reset();
            writer.append("--" + boundary).append(LINE_FEED);
            writer.append("Content-Disposition: form-data; name=\"" + fileUploadFieldName + "\"; filename=\""
                    + fileUploadFilename + "\"").append(LINE_FEED);
            writer.append(
                    "Content-Type: " + java.net.URLConnection.guessContentTypeFromName(fileUploadFilename))
                    .append(LINE_FEED);
            writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
            writer.append(LINE_FEED);
            writer.flush();

            byte[] buffer = new byte[4096];
            int bytesRead = -1;
            while ((bytesRead = is.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.flush();
            is.close();

            writer.append(LINE_FEED);
            writer.flush();
            writer.append(LINE_FEED).flush();
        }

        writer.append("--" + boundary + "--").append(LINE_FEED);
        writer.close();
    } catch (final IOException ex) {
        ConnectionException postException = new ConnectionException(
                "Exception caught while posting the parameters to the " + "remote web service located at '"
                        + getUri() + "'",
                ex);
        postException.setActor(getUri() != null ? getUri().toString() : "N/A");
        throw postException;
    } finally {
        getPostLock().unlock(); // UNLOCK
    }
}

From source file:com.silverpeas.form.displayers.VideoFieldDisplayer.java

@Override
public void displayScripts(final PrintWriter out, final FieldTemplate template, final PagesContext pageContext)
        throws IOException {
    checkFieldType(template.getTypeName(), "VideoFieldDisplayer.displayScripts");
    String language = pageContext.getLanguage();
    String fieldName = template.getFieldName();
    if (template.isMandatory() && pageContext.useMandatory()) {
        out.append("   if (isWhitespace(stripInitialWhitespace(field.value))) {\n").append("      var ")
                .append(fieldName).append("Value = document.getElementById('").append(fieldName)
                .append(Field.FILE_PARAM_NAME_SUFFIX).append("').value;\n").append("   var ").append(fieldName)
                .append("Operation = document.").append(pageContext.getFormName()).append(".").append(fieldName)
                .append(OPERATION_KEY).append(".value;\n").append("      if (").append(fieldName)
                .append("Value=='' || ").append(fieldName).append("Operation=='")
                .append(Operation.DELETION.name()).append("') {\n").append("         errorMsg+=\"  - '")
                .append(EncodeHelper.javaStringToJsString(template.getLabel(language))).append("' ")
                .append(Util.getString("GML.MustBeFilled", language)).append("\\n \";\n")
                .append("         errorNb++;\n").append("      }\n").append("   }\n");
    }//  w  ww  .j  av  a 2 s .  c om

    Util.includeFileNameLengthChecker(template, pageContext, out);
    Util.getJavascriptChecker(template.getFieldName(), pageContext, out);
}