예제 #1
0
 public static void main(String[] args) {
   // TODO Auto-generated method stub
   Socket socket = null;
   try {
     socket = new Socket(SERVER, PORT);
     socket.setSoTimeout(TIMEOUT);
     OutputStream out = socket.getOutputStream();
     Writer writer = new OutputStreamWriter(out, "UTF-8");
     writer = new BufferedWriter(writer);
     InputStream in = socket.getInputStream();
     BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
     for (String word : args) define(word, writer, reader);
     writer.write("quit\r\n");
     writer.flush();
   } catch (IOException e) {
     // TODO: handle exception
     System.err.println(e);
   } finally {
     if (socket != null) {
       try {
         socket.close();
       } catch (IOException e2) {
         // TODO: handle exception
       }
     }
   }
 }
예제 #2
0
 private void writeTextCollapseWhiteSpace(final int end, final int depth) throws IOException {
   // sets index to end
   // assert index < end
   boolean lastWasWhiteSpace = false;
   updateNextTag();
   while (index < end) {
     while (nextTag != null && index == nextTag.begin) {
       if (lastWasWhiteSpace) {
         writer.write(' ');
         lastWasWhiteSpace = false;
       }
       writeTag(nextTag, depth, end);
       if (index == end) return;
     }
     final char ch = sourceText.charAt(index++);
     if (Segment.isWhiteSpace(ch)) {
       lastWasWhiteSpace = true;
     } else {
       if (lastWasWhiteSpace) {
         writer.write(' ');
         lastWasWhiteSpace = false;
       }
       writer.write(ch);
     }
   }
   if (lastWasWhiteSpace) writer.write(' ');
 }
예제 #3
0
    @Override
    @SuppressWarnings("SleepWhileHoldingLock")
    public void run() {
      try {
        // initialize the statusbar
        status.removeAll();
        JProgressBar progress = new JProgressBar();
        progress.setMinimum(0);
        progress.setMaximum(doc.getLength());
        status.add(progress);
        status.revalidate();

        // start writing
        Writer out = new FileWriter(f);
        Segment text = new Segment();
        text.setPartialReturn(true);
        int charsLeft = doc.getLength();
        int offset = 0;
        while (charsLeft > 0) {
          doc.getText(offset, Math.min(4096, charsLeft), text);
          out.write(text.array, text.offset, text.count);
          charsLeft -= text.count;
          offset += text.count;
          progress.setValue(offset);
          try {
            Thread.sleep(10);
          } catch (InterruptedException e) {
            Logger.getLogger(FileSaver.class.getName()).log(Level.SEVERE, null, e);
          }
        }
        out.flush();
        out.close();
      } catch (IOException e) {
        final String msg = e.getMessage();
        SwingUtilities.invokeLater(
            new Runnable() {

              public void run() {
                JOptionPane.showMessageDialog(
                    getFrame(),
                    "Could not save file: " + msg,
                    "Error saving file",
                    JOptionPane.ERROR_MESSAGE);
              }
            });
      } catch (BadLocationException e) {
        System.err.println(e.getMessage());
      }
      // we are done... get rid of progressbar
      status.removeAll();
      status.revalidate();
    }
예제 #4
0
 static void define(String word, Writer writer, BufferedReader reader)
     throws IOException, UnsupportedEncodingException {
   writer.write("DEFINE fd-eng-lat " + word + "\r\n");
   writer.flush();
   for (String line = reader.readLine(); line != null; line = reader.readLine()) {
     if (line.startsWith("250 ")) return;
     else if (line.startsWith("552")) {
       System.out.println("no definition found for " + word);
       return;
     } else if (line.matches("\\d\\d\\d .*")) continue;
     else if (line.trim().equals(".")) continue;
     else System.out.println(line);
   }
 }
 public static void main(String[] args) throws Exception {
   String sourceUrlString = "data/test.html";
   if (args.length == 0)
     System.err.println("Using default argument of \"" + sourceUrlString + '"');
   else sourceUrlString = args[0];
   if (sourceUrlString.indexOf(':') == -1) sourceUrlString = "file:" + sourceUrlString;
   StreamedSource streamedSource = new StreamedSource(new URL(sourceUrlString));
   // streamedSource.setBuffer(new char[65000]); // uncomment this to use a fixed buffer size
   Writer writer = null;
   try {
     writer =
         new OutputStreamWriter(
             new FileOutputStream("StreamedSourceCopyOutput.html"), streamedSource.getEncoding());
     System.out.println("Processing segments:");
     int lastSegmentEnd = 0;
     for (Segment segment : streamedSource) {
       System.out.println(segment.getDebugInfo());
       if (segment.getEnd() <= lastSegmentEnd)
         continue; // if this tag is inside the previous tag (e.g. a server tag) then ignore it as
                   // it was already output along with the previous tag.
       lastSegmentEnd = segment.getEnd();
       if (segment instanceof Tag) {
         Tag tag = (Tag) segment;
         // HANDLE TAG
         // Uncomment the following line to ensure each tag is valid XML:
         // writer.write(tag.tidy()); continue;
       } else if (segment instanceof CharacterReference) {
         CharacterReference characterReference = (CharacterReference) segment;
         // HANDLE CHARACTER REFERENCE
         // Uncomment the following line to decode all character references instead of copying them
         // verbatim:
         // characterReference.appendCharTo(writer); continue;
       } else {
         // HANDLE PLAIN TEXT
       }
       // unless specific handling has prevented getting to here, simply output the segment as is:
       writer.write(segment.toString());
     }
     writer.close();
     System.err.println(
         "\nA copy of the source document has been output to StreamedSourceCopyOuput.html");
   } catch (Exception ex) {
     if (writer != null)
       try {
         writer.close();
       } catch (IOException ex2) {
       }
     throw ex;
   }
 }
예제 #6
0
 public void write(byte[] b, int off, int len) throws IOException {
   for (int i = off; i < off + len; i++) {
     int n = b[i];
     n = ((n >>> 4) & 0xF) * 16 + (n & 0xF);
     out.write(n);
   }
 }
예제 #7
0
 private void writeLineKeepWhiteSpace(final int end, final int depth) throws IOException {
   // Writes the first line from the source text starting from index, ending at the specified end
   // position.
   // The line break characters are not written.
   // Sets index to the position following the first line break character(s), or end if the text
   // contains no line breaks. index is guaranteed <= end.
   // Any tags encountered are written using the writeTag method, whose output may include line
   // breaks.
   // assert index < end
   updateNextTag();
   while (true) {
     while (nextTag != null && index == nextTag.begin) {
       writeTag(nextTag, depth, end);
       if (index == end) return;
     }
     final char ch = sourceText.charAt(index);
     if (ch == '\r') {
       final int nextindex = index + 1;
       if (nextindex < end && sourceText.charAt(nextindex) == '\n') {
         index += 2;
         return;
       }
     }
     if (ch == '\n') {
       index++;
       return;
     }
     writer.write(ch);
     if (++index == end) return;
   }
 }
예제 #8
0
 public void writeTo(final Writer writer) throws IOException {
   this.writer = writer;
   if (segment instanceof Source) ((Source) segment).fullSequentialParse();
   nextTag = segment.source.findNextTag(segment.begin);
   index = segment.begin;
   writeContent(segment.end, segment.getChildElements(), 0);
   writer.flush();
 }
예제 #9
0
 public void write(byte[] b) throws IOException {
   for (int i = 0; i < b.length; i++) {
     int n = b[i];
     // Convert byte to ubyte
     n = ((n >>> 4) & 0xF) * 16 + (n & 0xF);
     out.write(n);
   }
 }
예제 #10
0
 private void writeTag(final Tag tag, final int depth, final int end) throws IOException {
   // sets index to last position written, guaranteed < end
   // assert index==tag.begin
   // assert index < end
   nextTag = tag.findNextTag();
   final int tagEnd = (tag.end < end) ? tag.end : end;
   // assert index < tagEnd
   if (tag.getTagType() == StartTagType.COMMENT
       || tag.getTagType() == StartTagType.CDATA_SECTION
       || tag.getTagType().isServerTag()) {
     writeTextPreserveIndentation(tagEnd, depth);
   } else if (tidyTags) {
     final String tidyTag = tag.tidy();
     if ((tag instanceof StartTag) && ((StartTag) tag).getAttributes() != null)
       writer.write(tidyTag);
     else writeSpecifiedTextInline(tidyTag, depth);
     index = tagEnd;
   } else {
     writeTextInline(
         tagEnd, depth,
         true); // Write tag keeping linefeeds. This will add an indent to any attribute values
     // containing linefeeds, but the normal situation where line breaks are between
     // attributes will look nice.
   }
   if (end <= tag.end || !(tag instanceof StartTag)) return;
   if ((tag.name == HTMLElementName.SCRIPT && !indentScriptElements)
       || tag.getTagType().isServerTag()) {
     // NOTE SERVER ELEMENTS CONTAINING NON-INLINE TAGS WILL NOT FORMAT PROPERLY. NEED TO
     // INVESTIGATE INCLUDING SUCH SERVER ELEMENTS IN DOCUMENT HIERARCHY.
     // this is a script or server start tag, we may need to write the whole element:
     final Element element = tag.getElement();
     final EndTag endTag = element.getEndTag();
     if (endTag == null) return;
     final int contentEnd = (end < endTag.begin) ? end : endTag.begin;
     boolean singleLineContent = true;
     if (index != contentEnd) {
       // elementContainsMarkup should be made into a TagType property one day.
       // for the time being assume all server element content is code, although this is not true
       // for some Mason elements.
       final boolean elementContainsMarkup = false;
       if (elementContainsMarkup) {
         singleLineContent = writeTextInline(contentEnd, depth + 1, false);
       } else {
         singleLineContent = writeTextPreserveIndentation(contentEnd, depth);
       }
     }
     if (endTag.begin >= end) return;
     if (!singleLineContent) {
       writeEssentialNewLine(); // some server or client side scripting languages might need the
       // final new line
       writeIndent(depth);
     }
     // assert index==endTag.begin
     writeTag(endTag, depth, end);
   }
 }
예제 #11
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String path = request.getPathInfo();
    boolean htmlOutput = true;
    String language = null;
    String contentType = "text/html; charset='utf-8'";

    if (path != null) {
      if (path.endsWith(".rdf")) {
        contentType = "application/rdf+xml; charset='utf-8'";
        htmlOutput = false;
        language = "RDF/XML";
      } else if (path.endsWith(".xml")) {
        contentType = "application/xml; charset='utf-8'";
        htmlOutput = false;
        language = "RDF/XML";
      } else if (path.endsWith(".n3")) {
        contentType = "text/n3; charset='utf-8'";
        htmlOutput = false;
        language = "N3";
      }
    }

    response.setContentType(contentType);
    response.setStatus(HttpServletResponse.SC_OK);

    Writer writer = response.getWriter();

    synchronized (board) {
      if (htmlOutput) {
        writer.write(
            "<!DOCTYPE html>\n"
                + "<html lang='en'>"
                + "<head><meta charset='utf-8'/><title>MATe model</title></head>"
                + "<body><ul>");
        StmtIterator it = model.listStatements();
        /* TODO: well, this could be prettier */
        while (it.hasNext()) writer.write("<li>" + it.nextStatement() + "</li>");
        writer.write("<ul></body></html>");
      } else model.write(writer, language);
    }
  }
예제 #12
0
 private void writeContentPreformatted(final int end, final int depth) throws IOException {
   // sets index to end
   // assert index < end
   updateNextTag();
   do {
     while (nextTag != null && index == nextTag.begin) {
       writeTag(nextTag, depth, end);
       if (index == end) return;
     }
     writer.write(sourceText.charAt(index));
   } while (++index < end);
 }
예제 #13
0
  @Override
  public void render(Parameters blockParameters, Writer w, RenderHints hints)
      throws FrameworkException {

    if (decorate) {
      try {
        decorateIntro(hints, w, null);
      } catch (IOException ioe) {
        throw new FrameworkException(ioe);
      }
    }
    String name = getResource();
    ResourceLoader loader = ResourceLoader.Type.valueOf(resourceType.toUpperCase()).get();
    try {
      InputStream is = loader.getResourceAsStream(name);
      if (is == null)
        throw new FrameworkException(
            "No such resource " + loader.getResource(name) + " in " + loader);
      if (xsl == null) {
        Reader r = loader.getReader(is, name);
        char[] buf = new char[1000];
        int c;
        while ((c = r.read(buf, 0, 1000)) > 0) {
          w.write(buf, 0, c);
        }
      } else {
        /// convert using the xsl and spit out that.
        URL x = ResourceLoader.getConfigurationRoot().getResource(xsl);
        Utils.xslTransform(blockParameters, loader.getResource(name), is, w, x);
      }
    } catch (IOException ioe) {
      throw new FrameworkException(ioe);
    } catch (javax.xml.transform.TransformerException te) {
      throw new FrameworkException(te.getMessage(), te);
    } catch (RuntimeException e) {
      log.debug(e.getMessage(), e);
      throw e;
    } finally {
      if (decorate) {
        try {
          decorateOutro(hints, w);
        } catch (IOException ioe) {
          throw new FrameworkException(ioe);
        }
      }
    }
  }
예제 #14
0
 private int writeSpecifiedLine(final CharSequence text, int i) throws IOException {
   // Writes the first line from the specified text starting from the specified position.
   // The line break characters are not written.
   // Returns the position following the first line break character(s), or text.length() if the
   // text contains no line breaks.
   final int textLength = text.length();
   while (true) {
     final char ch = text.charAt(i);
     if (ch == '\r') {
       final int nexti = i + 1;
       if (nexti < textLength && text.charAt(nexti) == '\n') return i + 2;
     }
     if (ch == '\n') return i + 1;
     writer.write(ch);
     if (++i >= textLength) return i;
   }
 }
예제 #15
0
 private void writeEssentialNewLine() throws IOException {
   writer.write(newLine);
 }
예제 #16
0
 private void writeFormattingNewLine() throws IOException {
   if (!removeLineBreaks) writer.write(newLine);
 }
예제 #17
0
 private void writeIndent(final int depth) throws IOException {
   if (!removeLineBreaks) for (int x = 0; x < depth; x++) writer.write(indentString);
 }
예제 #18
0
 public static void copyStream(Reader reader, Writer writer) throws IOException {
   int count;
   char[] buffer = new char[1024];
   while ((count = reader.read(buffer)) > 0) writer.write(buffer, 0, count);
 }
예제 #19
0
 public void write(int i) throws IOException {
   out.write(i);
 }
예제 #20
0
 public static void saveURL(URL url, Writer writer) throws IOException {
   BufferedInputStream in = new BufferedInputStream(url.openStream());
   for (int c = in.read(); c != -1; c = in.read()) {
     writer.write(c);
   }
 }