示例#1
0
  public static void main(String[] args) {
    try {
      BufferedReader br1 =
          new BufferedReader(new InputStreamReader(new FileInputStream(args[0]), "UTF-8"));

      BufferedReader br2 =
          new BufferedReader(new InputStreamReader(new FileInputStream(args[1]), "UTF-8"));

      OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream("merge.txt"), "UTF-8");

      String cell1 = br1.readLine();
      String cell2 = br2.readLine();
      while (cell1 != null && cell2 != null) {

        String merge = cell1 + "\t" + cell2;
        System.out.println(merge);
        out.write(merge);
        out.write("\n");
        out.flush();

        cell1 = br1.readLine();
        cell2 = br2.readLine();
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
示例#2
0
  public void flush() throws IOException {
    if (!dirty) return;

    FileOutputStream fos = null;
    OutputStreamWriter osw = null;
    try {
      fos = new FileOutputStream(filePath);
      osw = new OutputStreamWriter(fos, charset);

      // 全局数据
      for (Line l : globalLines) {
        osw.write(l.toString());
        osw.write('\n');
      }

      // 各个块
      for (Sector s : sectors) {
        osw.write(s.toString());
      }

      dirty = false;
    } finally {
      // XXX 因为stream之间有一定的依赖顺序,必须按照一定的顺序关闭流
      if (osw != null) osw.close();
      if (fos != null) fos.close();
    }
  }
示例#3
0
 private void sendMSG(String msg) throws IOException {
   try {
     out.write(msg);
     out.flush();
   } catch (IOException ioe) {
     throw (ioe);
   }
 }
示例#4
0
 public void show(OutputStreamWriter out) throws IOException {
   out.write("<H2>Current Time:</H2>");
   Calendar c = new GregorianCalendar();
   out.write("<CENTER><H3><FONT color=\"blue\">");
   out.write(c.getTime().toString());
   out.write("</FONT></H3></CENTER><HR>");
   out.write("<P><A HREF=\"demo.html\">Return to the home page.</A>");
 }
示例#5
0
  public void Connect() throws IOException {
    try {
      InetAddress addr = InetAddress.getByName(server);
      Socket socket = new Socket(addr, port);

      in = new InputStreamReader(socket.getInputStream());
      out = new OutputStreamWriter(socket.getOutputStream());

      char c[] = new char[LINE_LENGTH];

      boolean authed = false;

      while (true) {
        if (in.read(c) > 0) {
          String msg = new String(c).trim();

          if (!authed) {
            if (msg.endsWith("No Ident response")) {

              System.out.println("...sending identity...");
              out.write(String.format("NICK %s\r\n", nickname));
              out.write(String.format("USER %s %s %s :s\r\n", nickname, host, server, realname));
              out.flush();

              authed = true;

              for (IRCAuthListener a : authListeners) {
                a.afterAuthentication(this);
              }
            }
          }

          if (msg.startsWith("PING")) {
            System.out.println("Sending pong...");
            out.write("PONG\r\n");
            out.flush();
          }

          for (IRCRawDataListener d : rawDataListeners) {
            d.processRawData(this, msg);
          }

          c = new char[LINE_LENGTH];
        } else {
          System.out.println("Oops, if you see this we just got kicked or connection timed out...");
          break;
        }
      }
    } catch (IOException ioe) {
      throw (ioe);
    }
  }
示例#6
0
 private Object request(
     String url, boolean post, Hashtable params, boolean basicAuth, boolean processOutput)
     throws Exception {
   HttpConnection conn = null;
   Writer writer = null;
   InputStream is = null;
   try {
     if (!post && (params != null)) {
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       OutputStreamWriter osw = new OutputStreamWriter(baos, this.encoding);
       this.encodeParams(params, osw);
       osw.flush();
       osw.close();
       osw = null;
       url += "?" + new String(baos.toByteArray(), this.encoding);
       baos = null;
     }
     conn = (HttpConnection) Connector.open(url);
     conn.setRequestMethod(post ? HttpConnection.POST : HttpConnection.GET);
     if (basicAuth) {
       if (!this.areCredentialsSet()) throw new Exception("Credentials are not set");
       String token = base64Encode((this.user + ":" + this.pass).getBytes(this.encoding));
       conn.setRequestProperty("Authorization", "Basic " + token);
     }
     if (post && (params != null)) {
       OutputStream os = conn.openOutputStream();
       writer = new OutputStreamWriter(os, this.encoding);
       this.encodeParams(params, writer);
       writer.flush();
       writer.close();
       os = null;
       writer = null;
     }
     int code = conn.getResponseCode();
     if ((code != 200) && (code != 302))
       throw new Exception("Unexpected response code " + code + ": " + conn.getResponseMessage());
     is = conn.openInputStream();
     if (processOutput) {
       synchronized (this.json) {
         return this.json.parse(is);
       }
     } else {
       this.pump(is, System.out, 1024);
       return null;
     }
   } finally {
     if (writer != null) writer.close();
     if (is != null) is.close();
     if (conn != null) conn.close();
   }
 }
示例#7
0
  public void end() throws Exception {
    FunMessage.Builder fm = FunMessage.newBuilder().setGameId(gameId).setFunScore(rate());
    URL url = new URL("http://localhost:5000/gameFinish");
    URLConnection urlCon = url.openConnection();
    urlCon.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(urlCon.getOutputStream());
    wr.write("rating=");
    wr.flush();
    fm.build().writeTo(urlCon.getOutputStream());
    urlCon.getOutputStream().close();

    // No network I/O happens until you ask for feedback apparently
    urlCon.getInputStream();
  }
    @Override
    public void run() {
      // long startTime = System.nanoTime();
      synchronized (configFile) {
        if (pendingDiskWrites.get() > 1) {
          // Writes can be skipped, because they are stored in a queue (in the executor).
          // Only the last is actually written.
          pendingDiskWrites.decrementAndGet();
          // LOGGER.log(Level.INFO, configFile + " skipped writing in " + (System.nanoTime() -
          // startTime) + " nsec.");
          return;
        }
        try {
          Files.createParentDirs(configFile);

          if (!configFile.exists()) {
            try {
              LOGGER.log(Level.INFO, tl("creatingEmptyConfig", configFile.toString()));
              if (!configFile.createNewFile()) {
                LOGGER.log(Level.SEVERE, tl("failedToCreateConfig", configFile.toString()));
                return;
              }
            } catch (IOException ex) {
              LOGGER.log(Level.SEVERE, tl("failedToCreateConfig", configFile.toString()), ex);
              return;
            }
          }

          final FileOutputStream fos = new FileOutputStream(configFile);
          try {
            final OutputStreamWriter writer = new OutputStreamWriter(fos, UTF8);

            try {
              writer.write(data);
            } finally {
              writer.close();
            }
          } finally {
            fos.close();
          }
        } catch (IOException e) {
          LOGGER.log(Level.SEVERE, e.getMessage(), e);
        } finally {
          // LOGGER.log(Level.INFO, configFile + " written to disk in " + (System.nanoTime() -
          // startTime) + " nsec.");
          pendingDiskWrites.decrementAndGet();
        }
      }
    }
示例#9
0
  /**
   * Writes the XML Declaration and the opening RDF tag to the print Writer. Encoding attribute is
   * specified as the encoding argument.
   *
   * @param out PrintWriter
   * @throws IOException
   */
  protected void writeHeader(OutputStreamWriter out) throws IOException {

    // validate
    if (out != null) {

      // wrapper for output stream writer (enable autoflushing)
      PrintWriter writer = new PrintWriter(out, true);

      // get encoding from the Encoding map
      String encoding = EncodingMap.getJava2IANAMapping(out.getEncoding());

      // only insert encoding if there is a value
      if (encoding != null) {

        // print opening tags <?xml version="1.0" encoding=*encoding*?>
        writer.println("<?xml version=\"1.0\" encoding=\"" + encoding + "\"?>");
      } else {

        // print opening tags <?xml version="1.0"?>
        writer.println("<?xml version=\"1.0\"?>");
      }

      // print the Entities
      this.writeXMLEntities(writer);

      // print the opening RDF tag (including namespaces)
      this.writeRDFHeader(writer);
    } else {

      throw new IllegalArgumentException("Cannot write to null Writer.");
    }
  }
示例#10
0
  protected void writeParseTree(String filename, AST ast) {
    try {
      PrintStream stream = new PrintStream(new FileOutputStream(filename));
      stream.println("<?xml version=\"1.0\"?>");
      stream.println("<document>");
      OutputStreamWriter writer = new OutputStreamWriter(stream);
      if (ast != null) {
        ((CommonAST) ast).xmlSerialize(writer);
      }
      writer.flush();
      stream.println("</document>");
      writer.close();
    } catch (IOException e) {

    }
  }
 private static void writePatchesToFile(
     final Project project,
     final String path,
     final List<FilePatch> remainingPatches,
     CommitContext commitContext) {
   OutputStreamWriter writer;
   try {
     writer = new OutputStreamWriter(new FileOutputStream(path), CharsetToolkit.UTF8_CHARSET);
     try {
       UnifiedDiffWriter.write(project, remainingPatches, writer, "\n", commitContext);
     } finally {
       writer.close();
     }
   } catch (IOException e) {
     LOG.error(e);
   }
 }
示例#12
0
  public String getBody(String url, String text, LinkedHashMap header) {
    if (text != null && text.length() > 0) {
      File tmpFile = new File("/tmp/aa");
      OutputStreamWriter out = null;
      try {
        // write the input
        out = new OutputStreamWriter(new FileOutputStream(tmpFile), "UTF8");
        out.write(text);
        out.close();

        // run TextPro
        String[] CONFIG = {"TEXTPRO=" + TEXTPRO_PATH, "PATH=" + "/usr/bin/" + ":."};
        String[] cmd = {
          "/bin/tcsh",
          "-c",
          "perl " + TEXTPRO_PATH + "/textpro.pl -l eng -c token+pos+lemma+sentence -y " + tmpFile
        };
        Process process = run(cmd, CONFIG);
        process.waitFor();

        // read the TextPro's output
        BufferedReader txpFile =
            new BufferedReader(
                new InputStreamReader(new FileInputStream(tmpFile.getCanonicalPath() + ".txp")));
        StringBuilder result = new StringBuilder();
        String line;
        while ((line = txpFile.readLine()) != null) {
          if (!line.startsWith("# FILE:")) {
            result.append(line).append("\n");
          }
        }
        txpFile.close();

        return result.toString();
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    return "";
  }
示例#13
0
文件: Q2.java 项目: rlishtaba/jPOS
  protected Document encrypt(Document doc) throws GeneralSecurityException, IOException {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    OutputStreamWriter writer = new OutputStreamWriter(os);
    XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
    out.output(doc, writer);
    writer.close();

    byte[] crypt = dodes(os.toByteArray(), Cipher.ENCRYPT_MODE);

    Document secureDoc = new Document();
    Element root = new Element(PROTECTED_QBEAN);
    secureDoc.setRootElement(root);
    Element secureData = new Element("data");
    root.addContent(secureData);

    secureData.setText(ISOUtil.hexString(crypt));
    return secureDoc;
  }
示例#14
0
 /**
  * Create the directory path for the file to be generated, construct FileOutputStream and
  * OutputStreamWriter depending upon docencoding.
  *
  * @param path The directory path to be created for this file.
  * @param filename File Name to which the PrintWriter will do the Output.
  * @param docencoding Encoding to be used for this file.
  * @exception IOException Exception raised by the FileWriter is passed on to next level.
  * @exception UnSupportedEncodingException Exception raised by the OutputStreamWriter is passed on
  *     to next level.
  * @return Writer Writer for the file getting generated.
  * @see java.io.FileOutputStream
  * @see java.io.OutputStreamWriter
  */
 public static Writer genWriter(
     Configuration configuration, String path, String filename, String docencoding)
     throws IOException, UnsupportedEncodingException {
   FileOutputStream fos;
   if (path != null) {
     DirectoryManager.createDirectory(configuration, path);
     fos = new FileOutputStream(((path.length() > 0) ? path + File.separator : "") + filename);
   } else {
     fos = new FileOutputStream(filename);
   }
   if (docencoding == null) {
     OutputStreamWriter oswriter = new OutputStreamWriter(fos);
     docencoding = oswriter.getEncoding();
     return oswriter;
   } else {
     return new OutputStreamWriter(fos, docencoding);
   }
 }
 /** Utility method to write a migrations file */
 public static void writeMigrationsFile(ConfigManagerMigrations m, File f) {
   OutputStreamWriter r = null;
   try {
     r = new OutputStreamWriter(new FileOutputStream(f));
     XStream x = createXStream();
     String config = x.toXML(m);
     r.write(config);
   } catch (Exception ex) {
     ex.printStackTrace();
   } finally {
     if (r != null) {
       try {
         r.flush();
         r.close();
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
   }
 }
  public void replaceVariable() throws IOException {
    Closer closer = Closer.create();
    try {
      FileReader fReader = new FileReader();
      List<String> content = fReader.getContent(FictionURL);
      Properties indexOrderProperties = getIndexOrder();
      List<String> natureOrderList = getNatureOrder(propertiesURL);
      List<String> charOrderList = getCharOrder(natureOrderList);
      Pattern p = Pattern.compile("\\$(\\w+)\\((\\d+)\\)");
      OutputStreamWriter streamWriter =
          closer.register(new OutputStreamWriter(new FileOutputStream("result.txt"), "UTF-8"));

      for (String tempStr : content) {
        Matcher m = p.matcher(tempStr);
        while (m.find()) {
          String orderName = m.group(1);
          String num = m.group(2);
          int listSize = natureOrderList.size();
          if (orderName.equals("natureOrder"))
            tempStr = tempStr.replace(m.group(), natureOrderList.get(Integer.parseInt(num)));
          else if (orderName.equals("charOrder"))
            tempStr = tempStr.replace(m.group(), charOrderList.get(Integer.parseInt(num)));
          else if (orderName.equals("charOrderDESC"))
            // 倒序为正序下标为:下标位置(集合总数-1)-倒序位置
            tempStr =
                tempStr.replace(m.group(), charOrderList.get(listSize - 1 - Integer.parseInt(num)));
          else if (orderName.equals("indexOrder")) {
            if (indexOrderProperties.getProperty(num) != null)
              tempStr = tempStr.replace(m.group(), indexOrderProperties.getProperty(num));
            else tempStr = tempStr.replace(m.group(), "null");
          }
        }
        streamWriter.write(tempStr + "\n");
        System.out.println(tempStr);
      }
    } finally {
      closer.close();
    }
  }
 private static void writeToFile(@NotNull final String path, @NotNull final String json) {
   final File file = new File(path);
   try {
     final FileOutputStream fileOutputStream = new FileOutputStream(file);
     final OutputStreamWriter writer =
         new OutputStreamWriter(fileOutputStream, Charset.forName("UTF-8").newEncoder());
     try {
       writer.write(json);
     } catch (IOException e) {
       LOG.error(e);
     } finally {
       try {
         writer.close();
         fileOutputStream.close();
       } catch (IOException e) {
         LOG.error(e);
       }
     }
   } catch (FileNotFoundException e) {
     LOG.error(e);
   }
 }
示例#18
0
  /**
   * Executes a command as {@code user}. Saves the stdout/stderr in the corresponding fields and
   * returns the return code of the child process.
   *
   * @param cmd The command to execute
   * @param data The data to send to the stdin of the process
   * @param timelimt How many seconds the command can run
   * @param memlimit How many megabytes the command can use
   */
  private int exec(String cmdS, String data, int timelimit, int memlimit) throws Exception {
    ArrayList<String> cmd = new ArrayList<String>(cmdPrefix);
    cmd.add("-m");
    cmd.add("" + memlimit);
    cmd.add("-c");
    cmd.add("" + timelimit);
    cmd.add("-w");
    cmd.add("" + (3 * timelimit + 1));
    cmd.add("-x");
    cmd.add(cmdS);
    String tmp = "";
    for (String cs : cmd) tmp += " \"" + cs + "\"";
    log.fine("exec " + tmp);
    ProcessBuilder pb = new ProcessBuilder(cmd);
    pb.directory(workDir);
    Process p = pb.start();
    OutputStreamWriter writer = new OutputStreamWriter(p.getOutputStream());
    StreamReader rOut = new StreamReader(p.getInputStream());
    StreamReader rErr = new StreamReader(p.getErrorStream());
    rOut.start();
    rErr.start();

    // TODO I think this may block for big tests. Check and Fix.
    // send and receive data "in parallel"
    writer.write(data);
    writer.flush();
    writer.close();
    rOut.join();
    rErr.join();
    stdout = rOut.result;
    stderr = rErr.result;
    if (rOut.exception != null) throw rOut.exception;
    if (rErr.exception != null) throw rErr.exception;

    // log.finer("out: " + stdout);
    // log.finer("err: " + stderr);
    // log.finer("done exec");
    return p.waitFor();
  }
示例#19
0
    private static void writePost(Collection<Connection.KeyVal> data, OutputStream outputStream)
        throws IOException {
      OutputStreamWriter w = new OutputStreamWriter(outputStream, DataUtil.defaultCharset);
      boolean first = true;
      for (Connection.KeyVal keyVal : data) {
        if (!first) w.append('&');
        else first = false;

        w.write(URLEncoder.encode(keyVal.key(), DataUtil.defaultCharset));
        w.write('=');
        w.write(URLEncoder.encode(keyVal.value(), DataUtil.defaultCharset));
      }
      w.close();
    }
示例#20
0
 @Override
 public void write(OutputStream out) throws IOException {
   OutputStreamWriter writer = new OutputStreamWriter(out, UTF8);
   this.write(writer);
   writer.flush();
 }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    // set the response

    Shepherd myShepherd = new Shepherd();

    Vector rEncounters = new Vector();

    // setup data dir
    String rootWebappPath = getServletContext().getRealPath("/");
    File webappsDir = new File(rootWebappPath).getParentFile();
    File shepherdDataDir = new File(webappsDir, CommonConfiguration.getDataDirectoryName());
    // if(!shepherdDataDir.exists()){shepherdDataDir.mkdir();}
    File encountersDir = new File(shepherdDataDir.getAbsolutePath() + "/encounters");
    // if(!encountersDir.exists()){encountersDir.mkdir();}

    // set up the files
    String gisFilename = "geneGIS_export_" + request.getRemoteUser() + ".csv";
    File gisFile = new File(encountersDir.getAbsolutePath() + "/" + gisFilename);

    myShepherd.beginDBTransaction();

    try {

      // set up the output stream
      FileOutputStream fos = new FileOutputStream(gisFile);
      OutputStreamWriter outp = new OutputStreamWriter(fos);

      try {

        EncounterQueryResult queryResult =
            EncounterQueryProcessor.processQuery(
                myShepherd, request, "year descending, month descending, day descending");
        rEncounters = queryResult.getResult();

        int numMatchingEncounters = rEncounters.size();

        // build the CSV file header
        StringBuffer locusString = new StringBuffer("");
        int numLoci = 2; // most covered species will be loci
        try {
          numLoci = (new Integer(CommonConfiguration.getProperty("numLoci"))).intValue();
        } catch (Exception e) {
          System.out.println("numPloids configuration value did not resolve to an integer.");
          e.printStackTrace();
        }

        for (int j = 0; j < numLoci; j++) {
          locusString.append(",Locus" + (j + 1) + " A1,Locus" + (j + 1) + " A2");
        }
        // out.println("<html><body>");
        // out.println("Individual ID,Other ID 1,Date,Time,Latitude,Longitude,Area,Sub
        // Area,Sex,Haplotype"+locusString.toString());

        outp.write(
            "Individual ID,Other ID 1,Date,Time,Latitude,Longitude,Area,Sub Area,Sex,Haplotype"
                + locusString.toString()
                + "\n");

        for (int i = 0; i < numMatchingEncounters; i++) {

          Encounter enc = (Encounter) rEncounters.get(i);
          String assembledString = "";
          if (enc.getIndividualID() != null) {
            assembledString += enc.getIndividualID();
          }
          if (enc.getAlternateID() != null) {
            assembledString += "," + enc.getAlternateID();
          } else {
            assembledString += ",";
          }

          String dateString = ",";
          if (enc.getYear() > 0) {
            dateString += enc.getYear();
            if (enc.getMonth() > 0) {
              dateString += ("-" + enc.getMonth());
              if (enc.getDay() > 0) {
                dateString += ("-" + enc.getDay());
              }
            }
          }
          assembledString += dateString;

          String timeString = ",";
          if (enc.getHour() > -1) {
            timeString += enc.getHour() + ":" + enc.getMinutes();
          }
          assembledString += timeString;

          if ((enc.getDecimalLatitude() != null) && (enc.getDecimalLongitude() != null)) {
            assembledString += "," + enc.getDecimalLatitude();
            assembledString += "," + enc.getDecimalLongitude();
          } else {
            assembledString += ",,";
          }

          assembledString += "," + enc.getVerbatimLocality();
          assembledString += "," + enc.getLocationID();
          assembledString += "," + enc.getSex();

          // find and print the haplotype
          String haplotypeString = ",";
          if (enc.getHaplotype() != null) {
            haplotypeString += enc.getHaplotype();
          }

          // find and print the ms markers
          String msMarkerString = "";
          List<TissueSample> samples = enc.getTissueSamples();
          int numSamples = samples.size();
          boolean foundMsMarkers = false;
          for (int k = 0; k < numSamples; k++) {
            if (!foundMsMarkers) {
              TissueSample t = samples.get(k);
              List<GeneticAnalysis> analyses = t.getGeneticAnalyses();
              int aSize = analyses.size();
              for (int l = 0; l < aSize; l++) {
                GeneticAnalysis ga = analyses.get(l);
                if (ga.getAnalysisType().equals("MicrosatelliteMarkers")) {
                  foundMsMarkers = true;
                  MicrosatelliteMarkersAnalysis ga2 = (MicrosatelliteMarkersAnalysis) ga;
                  List<Locus> loci = ga2.getLoci();
                  int localLoci = loci.size();
                  for (int m = 0; m < localLoci; m++) {
                    Locus locus = loci.get(m);
                    if (locus.getAllele0() != null) {
                      msMarkerString += "," + locus.getAllele0();
                    } else {
                      msMarkerString += ",";
                    }
                    if (locus.getAllele1() != null) {
                      msMarkerString += "," + locus.getAllele1();
                    } else {
                      msMarkerString += ",";
                    }
                  }
                }
              }
            }
          }

          // out.println("<p>"+assembledString+haplotypeString+msMarkerString+"</p>");
          outp.write(assembledString + haplotypeString + msMarkerString + "\n");
        }
        outp.close();
        outp = null;

        // now write out the file
        response.setContentType("text/csv");
        response.setHeader("Content-Disposition", "attachment;filename=" + gisFilename);
        ServletContext ctx = getServletContext();
        // InputStream is = ctx.getResourceAsStream("/encounters/"+gisFilename);
        InputStream is = new FileInputStream(gisFile);

        int read = 0;
        byte[] bytes = new byte[BYTES_DOWNLOAD];
        OutputStream os = response.getOutputStream();

        while ((read = is.read(bytes)) != -1) {
          os.write(bytes, 0, read);
        }
        os.flush();
        os.close();

      } catch (Exception ioe) {
        ioe.printStackTrace();
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println(ServletUtilities.getHeader(request));
        out.println(
            "<html><body><p><strong>Error encountered</strong> with file writing. Check the relevant log.</p>");
        out.println(
            "<p>Please let the webmaster know you encountered an error at: EncounterSearchExportGeneGISFormat servlet</p></body></html>");
        out.println(ServletUtilities.getFooter());
        out.close();
        outp.close();
        outp = null;
      }

    } catch (Exception e) {
      e.printStackTrace();
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      out.println(ServletUtilities.getHeader(request));
      out.println("<html><body><p><strong>Error encountered</strong></p>");
      out.println(
          "<p>Please let the webmaster know you encountered an error at: EncounterSearchExportGeneGISFormat servlet</p></body></html>");
      out.println(ServletUtilities.getFooter());
      out.close();
    }
    myShepherd.rollbackDBTransaction();
    myShepherd.closeDBTransaction();
  }
示例#22
0
  public static void main(String... args) throws IOException {

    OutputStreamWriter osw = new OutputStreamWriter(System.out);

    osw.write("hello world\n");
  }
示例#23
0
  public static void main(String[] args) {
    /** Define a host server */
    String host = "localhost";
    /** Define a port */
    int port = 19999;
    int port2 = 19990;
    // int port3 = 19980;
    StringBuffer instr = new StringBuffer();
    String TimeStamp;
    Parser parser = new Parser();
    System.out.println("SocketClient initialized");

    try {

      // parsing
      // DataStream ds =
      // new PlainTextByLineDataStream(
      // new FileReader(new File("input.txt")));
      BufferedReader inputReader = new BufferedReader(new FileReader("input.txt"));
      String sent;
      while ((sent = inputReader.readLine()) != null) {
        // String sentence = (String)ds.nextToken() + (char) 13;
        String sentence = sent + (char) 13;
        // System.out.println(str);
        System.out.println("Parsing....");

        Tree tree = parser.parse(sentence);
        System.out.println(tree);

        System.out.println("Extracting features...");
        String srlIdentifier = "python srl-identifier.py " + '"' + tree + '"';
        // System.out.println(srlIdentifier);
        Runtime rr = Runtime.getRuntime();
        Process pp = rr.exec(srlIdentifier);
        BufferedReader brr = new BufferedReader(new InputStreamReader(pp.getInputStream()));
        pp.waitFor();

        BufferedReader reader = new BufferedReader(new FileReader("identifier.test"));
        BufferedReader classifier = new BufferedReader(new FileReader("classifier.test"));
        String line;
        PrintWriter identifierOutput = new PrintWriter("identifier-output.txt");
        PrintWriter classifierOutput = new PrintWriter("classifier-output.txt");
        BufferedReader preds = new BufferedReader(new FileReader("pred.test"));

        while ((line = reader.readLine()) != null) {

          String pred = preds.readLine();
          String features = line + (char) 13;
          String classifierFeature = classifier.readLine() + (char) 13;

          InetAddress address = InetAddress.getByName(host);
          // Establish a socket connetion
          Socket connection = new Socket(address, port);
          Socket connection2 = new Socket(address, port2);

          // Instantiate a BufferedOutputStream object
          BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream());

          // Instantiate an OutputStreamWriter object with the optional character
          // encoding.
          //

          OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");

          BufferedReader fromServer =
              new BufferedReader(new InputStreamReader(connection.getInputStream()));

          // Write across the socket connection and flush the buffer

          osw.write(features);
          osw.flush();
          String identifierResponse = fromServer.readLine();
          identifierOutput.println(identifierResponse);

          BufferedOutputStream bos2 = new BufferedOutputStream(connection2.getOutputStream());

          // Instantiate an OutputStreamWriter object with the optional character
          // encoding.
          //
          OutputStreamWriter osw2 = new OutputStreamWriter(bos2, "US-ASCII");

          BufferedReader fromServer2 =
              new BufferedReader(new InputStreamReader(connection2.getInputStream()));

          osw2.write(classifierFeature);
          osw2.flush();
          String ClassifierResponse = fromServer2.readLine();
          classifierOutput.println(pred + ' ' + ClassifierResponse);
        }
        identifierOutput.close();
        classifierOutput.close();

        Runtime rlabeler = Runtime.getRuntime();
        String srlClassifier = "python concept-formulator.py";
        Process p = rlabeler.exec(srlClassifier);
        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
        p.waitFor();
        // System.out.println("here i am");
        String line2;
        while ((line2 = br.readLine()) != null) {
          System.out.println(line2);
          // while (br.ready())
          // System.out.println(br.readLine());
        }
      }

    } catch (Exception e) {
      String cause = e.getMessage();
      if (cause.equals("python: not found")) System.out.println("No python interpreter found.");
    }
  }