示例#1
1
  /**
   * Load a system library from a stream. Copies the library to a temp file and loads from there.
   *
   * @param libname name of the library (just used in constructing the library name)
   * @param is InputStream pointing to the library
   */
  private void loadLibraryFromStream(String libname, InputStream is) {
    try {
      File tempfile = createTempFile(libname);
      OutputStream os = new FileOutputStream(tempfile);

      logger.debug("tempfile.getPath() = " + tempfile.getPath());

      long savedTime = System.currentTimeMillis();

      // Leo says 8k block size is STANDARD ;)
      byte buf[] = new byte[8192];
      int len;
      while ((len = is.read(buf)) > 0) {
        os.write(buf, 0, len);
      }

      os.flush();
      InputStream lock = new FileInputStream(tempfile);
      os.close();

      double seconds = (double) (System.currentTimeMillis() - savedTime) / 1e3;
      logger.debug("Copying took " + seconds + " seconds.");

      logger.debug("Loading library from " + tempfile.getPath() + ".");
      System.load(tempfile.getPath());

      lock.close();
    } catch (IOException io) {
      logger.error("Could not create the temp file: " + io.toString() + ".\n");
    } catch (UnsatisfiedLinkError ule) {
      logger.error("Couldn't load copied link file: " + ule.toString() + ".\n");
      throw ule;
    }
  }
示例#2
0
  /*
  	Show context number lines of string before and after target line.
  	Add HTML formatting to bold the target line.
  */
  String showScriptContextHTML(String s, int lineNo, int context) {
    StringBuffer sb = new StringBuffer();
    BufferedReader br = new BufferedReader(new StringReader(s));

    int beginLine = Math.max(1, lineNo - context);
    int endLine = lineNo + context;
    for (int i = 1; i <= lineNo + context + 1; i++) {
      if (i < beginLine) {
        try {
          br.readLine();
        } catch (IOException e) {
          throw new RuntimeException(e.toString());
        }
        continue;
      }
      if (i > endLine) break;

      String line;
      try {
        line = br.readLine();
      } catch (IOException e) {
        throw new RuntimeException(e.toString());
      }

      if (line == null) break;
      if (i == lineNo) sb.append("<font color=\"red\">" + i + ": " + line + "</font><br/>");
      else sb.append(i + ": " + line + "<br/>");
    }

    return sb.toString();
  }
示例#3
0
  public static void main(String[] args) // throws Exception
      {
    /*
    FileWriter fw =new FileWriter("demo.txt");//调用windows底层的创建文件命令,会抛出IO异常
    //并且会对同名文件进行覆盖,可以创建到指定盘符。

    fw.writer("asdfasdgasg");//将数据写入流中。

    fw.flush();//刷新流,并将流中数据写入文件。

    fw.close();//关闭流,会作一次刷新操作。
    */

    FileWriter fw = null; // 由于close处于另一代码块中调用fw,因此fw必须定义在外面。
    try {
      fw = new FileWriter("demo.txt");
      fw.write("asdfasdgasg");
    } catch (IOException e) {
      System.out.println(e.toString());
    } finally {
      try {
        if (fw != null) fw.close();
      } catch (IOException e) {
        System.out.println(e.toString());
      }
    }
  }
示例#4
0
 public void run() {
   try {
     theInputStream = new BufferedReader(new InputStreamReader(client.getInputStream()));
     theOutputStream = new PrintStream(client.getOutputStream());
     while (true) {
       readin = theInputStream.readLine();
       chat.ta.append(readin + "\n");
     }
   } catch (SocketException e) {
     chat.ta.append("连接中断!\n");
     chat.clientBtn.setEnabled(true);
     chat.serverBtn.setEnabled(true);
     chat.tfaddress.setEnabled(true);
     chat.tfport.setEnabled(true);
     try {
       i--;
       skt.close();
       client.close();
     } catch (IOException err) {
       chat.ta.append(err.toString());
     }
   } catch (IOException e) {
     chat.ta.append(e.toString());
   }
 }
  /**
   * Test method for {@link
   * org.alfresco.deployment.transformers.EncryptionTransformer#addFilter(java.io.OutputStream,
   * org.alfresco.deployment.DeploymentTransportTransformer.Direction, java.lang.String)}. This test
   * compresses a message with one transformation. Then sends the results through another instance
   * to give us plain text again.
   */
  public void testAddFilter() {
    SampleEncryptionTransformer transformer = new SampleEncryptionTransformer();
    transformer.setPassword("Welcome To Hades");
    transformer.setCipherName("PBEWithMD5AndDES");

    String path = "wibble";

    ByteArrayOutputStream compressed = new ByteArrayOutputStream();

    // A sender should encrypt the stream
    OutputStream out = null;
    // out = (OutputStream)transformer.addFilter(compressed, Direction.SENDER, path);
    out = (OutputStream) transformer.addFilter(compressed, path, null, null);

    assertNotNull("null output stream returned", compressed);

    String clearText = "hello world";

    try {
      out.write(clearText.getBytes());
    } catch (IOException ie) {
      fail("unexpected exception thrown" + ie.toString());
    }

    try {
      out.flush();
      out.close();
    } catch (IOException ie) {
      fail("unexpected exception thrown, " + ie.toString());
    }

    assert (compressed.size() > 0);

    // Now set up another instance to decrypt the message
    InputStream decompress = null;

    ByteArrayInputStream compressedStream = new ByteArrayInputStream(compressed.toByteArray());

    ByteArrayOutputStream result = new ByteArrayOutputStream();

    decompress = (InputStream) transformer.addFilter(compressedStream, "wibble", null, null);

    try {
      byte[] readBuffer = new byte[1002];
      while (true) {
        int readLen = decompress.read(readBuffer);
        if (readLen > 0) {
          result.write(readBuffer, 0, readLen);
        } else {
          break;
        }
      }

    } catch (IOException ie) {
      fail("unexpected exception thrown, " + ie.toString());
    }

    // now uncompress should equal clearText
    assertTrue(result.toString().equalsIgnoreCase(clearText));
  }
示例#6
0
  /**
   * When data is available on the socket, this method is called to run the command or throw an
   * error if it can't.
   *
   * @throws SocketServerException
   */
  private void handleClientData() throws SocketServerException {
    try {
      input.setLength(0); // clear

      String res;
      int a;
      // (char) -1 is not equal to -1.
      // ready is checked to ensure the read call doesn't block.
      while ((a = in.read()) != -1 && in.ready()) {
        input.append((char) a);
      }
      String inputString = input.toString();
      Logger.debug("Got data from client: " + inputString);
      try {
        AndroidCommand cmd = getCommand(inputString);
        Logger.debug("Got command of type " + cmd.commandType().toString());
        res = runCommand(cmd);
        Logger.debug("Returning result: " + res);
      } catch (final CommandTypeException e) {
        res = new AndroidCommandResult(WDStatus.UNKNOWN_ERROR, e.getMessage()).toString();
      } catch (final JSONException e) {
        res =
            new AndroidCommandResult(WDStatus.UNKNOWN_ERROR, "Error running and parsing command")
                .toString();
      }
      out.write(res);
      out.flush();
    } catch (final IOException e) {
      throw new SocketServerException(
          "Error processing data to/from socket (" + e.toString() + ")");
    }
  }
示例#7
0
 private static void printBytes(OutputStream stream, byte[] bytes) {
   try {
     stream.write(bytes);
   } catch (IOException e) {
     System.err.println(e.toString());
   }
 }
示例#8
0
		void runTask() {
			status(su, StatusUpdate.LEVEL_GENERIC, GRI18n.getString(MODULE, "newAlbm", new Object[] { album.getName(), g.toString() }));

			try {
				List<NameValuePair> formparams = new ArrayList<NameValuePair>();
				JSONObject jsonEntity = new JSONObject();
				jsonEntity.put("type", "album");
				if (album.getName() != null)
					jsonEntity.put("name", album.getName());
				if (album.getTitle() != null)
					jsonEntity.put("title", album.getTitle());
				if (album.getDescription() != null)
					jsonEntity.put("description", album.getDescription());
				formparams.add(new BasicNameValuePair("entity", jsonEntity.toJSONString()));

				BufferedReader entityReader = sendRequest(album.getParentAlbum().getUrl(), "post", formparams);

				String url = ((JSONObject) JSONValue.parse(entityReader)).get("url").toString();
				status(su, StatusUpdate.LEVEL_GENERIC, GRI18n.getString(MODULE, "crateAlbmOk"));
				album.setUrl(url);

				Log.log(Log.LEVEL_INFO, "Created album " + album.toString());
			} catch (IOException ioe) {
				Log.logException(Log.LEVEL_ERROR, MODULE, ioe);
				Object[] params2 = {ioe.toString()};
				error(su, GRI18n.getString(MODULE, "error", params2));
			}
		}
示例#9
0
  /**
   * Method to send an ACK containing the filename (could actually be a directory) just taken back
   * to the client, and to ensure the client connection is kept open.
   *
   * @param multRunCommand The MULTRUN command we are implementing.
   * @param multRunDone The MULTRUN_DONE command object that will be returned to the client. We set
   *     a sensible error message in this object if this method fails.
   * @return We return true if the method succeeds, and false if an error occurs.
   * @see #lotus
   * @see #serverConnectionThread
   * @see ngat.lotus.LOTUS#log
   * @see ngat.lotus.LOTUS#error
   * @see ngat.message.ISS_INST.MULTRUN_ACK
   */
  protected boolean sendMultrunACK(
      MULTRUN multRunCommand, MULTRUN_DONE multRunDone, String filename) {
    MULTRUN_ACK multRunAck = null;

    // send acknowledge to say frames are completed.
    // diddly 4000
    lotus.log(
        Logging.VERBOSITY_INTERMEDIATE,
        this.getClass().getName()
            + ":sendMultrunACK:Sending ACK with exposure time "
            + multRunCommand.getExposureTime()
            + " plus ramp overhead "
            + 4000
            + " plus default ACK time "
            + serverConnectionThread.getDefaultAcknowledgeTime()
            + ".");
    multRunAck = new MULTRUN_ACK(multRunCommand.getId());
    multRunAck.setTimeToComplete(
        multRunCommand.getExposureTime()
            + 4000
            + serverConnectionThread.getDefaultAcknowledgeTime());
    multRunAck.setFilename(filename);
    try {
      serverConnectionThread.sendAcknowledge(multRunAck);
    } catch (IOException e) {
      lotus.error(this.getClass().getName() + ":sendMultrunACK:sendAcknowledge:", e);
      multRunDone.setErrorNum(LOTUSConstants.LOTUS_ERROR_CODE_BASE + 1202);
      multRunDone.setErrorString("sendMultrunACK:sendAcknowledge:" + e.toString());
      multRunDone.setSuccessful(false);
      return false;
    }
    return true;
  }
示例#10
0
  public int doEndTag() throws JspException {
    if ((jspFile.indexOf("..") >= 0)
        || (jspFile.toUpperCase().indexOf("/WEB-INF/") != 0)
        || (jspFile.toUpperCase().indexOf("/META-INF/") != 0))
      throw new JspTagException("Invalid JSP file " + jspFile);

    InputStream in = pageContext.getServletContext().getResourceAsStream(jspFile);

    if (in == null) throw new JspTagException("Unable to find JSP file: " + jspFile);

    InputStreamReader reader = new InputStreamReader(in);
    JspWriter out = pageContext.getOut();

    try {
      out.println("<body>");
      out.println("<pre>");
      for (int ch = in.read(); ch != -1; ch = in.read())
        if (ch == '<') out.print("&lt;");
        else out.print((char) ch);
      out.println("</pre>");
      out.println("</body>");
    } catch (IOException ex) {
      throw new JspTagException("IOException: " + ex.toString());
    }
    return super.doEndTag();
  }
示例#11
0
  public static String CreateZip(String[] filesToZip, String zipFileName) {

    byte[] buffer = new byte[18024];

    try {

      ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
      out.setLevel(Deflater.BEST_COMPRESSION);
      for (int i = 0; i < filesToZip.length; i++) {
        FileInputStream in = new FileInputStream(filesToZip[i]);
        String fileName = null;
        for (int X = filesToZip[i].length() - 1; X >= 0; X--) {
          if (filesToZip[i].charAt(X) == '\\' || filesToZip[i].charAt(X) == '/') {
            fileName = filesToZip[i].substring(X + 1);
            break;
          } else if (X == 0) fileName = filesToZip[i];
        }
        out.putNextEntry(new ZipEntry(fileName));
        int len;
        while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len);
        out.closeEntry();
        in.close();
      }
      out.close();
    } catch (IllegalArgumentException e) {
      return "Failed to create zip: " + e.toString();
    } catch (FileNotFoundException e) {
      return "Failed to create zip: " + e.toString();
    } catch (IOException e) {
      return "Failed to create zip: " + e.toString();
    }
    return "Success";
  }
示例#12
0
  private int Load_Edges(DataInputStream inStream, int num) {
    String line;
    String item1, item2, item3;
    int source_node;
    int dest_node;
    int value;
    int n_nodes, edge_cnt;
    // Node nodes_array[] = new Node[num]; // Wil
    Edge edge;
    n_nodes = num;
    Node nodes_array[];
    nodes_array = new Node[n_nodes];
    nodes_array = this.Node_Array(); // Wil
    edge_cnt = 0;

    try {
      while ((line = inStream.readLine()) != null) {
        StringTokenizer Data = new StringTokenizer(line, " ");
        item1 = Data.nextToken();
        item2 = Data.nextToken();
        item3 = Data.nextToken();
        source_node = Integer.parseInt(item1);
        dest_node = Integer.parseInt(item2);
        value = Integer.parseInt(item3);
        edge = new Edge(nodes_array[source_node - 1], nodes_array[dest_node - 1], value);
        this.Add_Edge(edge);
        edge_cnt++;
      }
      // inFile.close();
    } catch (IOException e) {
      System.err.println("Error in accessing URL: " + e.toString());
      System.exit(1);
    }
    return edge_cnt;
  }
 // post: input is closed
 public void close() {
   try {
     input.close();
   } catch (IOException e) {
     throw new RuntimeException(e.toString());
   }
 }
  private InputStream getUrlStream(String url, DefaultHttpClient httpClient)
      throws NotFoundException, ReportableError {
    try {
      HttpResponse res = httpClient.execute(new HttpGet(url));
      StatusLine status = res.getStatusLine();
      if (status.getStatusCode() == 401) {
        throw new ReportableError(
            r.getString(R.string.error_url_fetch_detail, url, "Invalid username or password"),
            null);
      }
      if (status.getStatusCode() == 404) {
        return null;
      }

      if (status.getStatusCode() < 200 || status.getStatusCode() > 299) {
        throw new ReportableError(
            r.getString(R.string.error_url_fetch_detail, url, status.getReasonPhrase()), null);
      }
      return res.getEntity().getContent();
    } catch (IOException e) {
      Log.e(LT, e.toString());
      Log.w(LT, "Failed to get URL");
      throw new ReportableError(
          r.getString(R.string.error_url_fetch_detail, url, e.getMessage()), e);
    }
  }
  public String readFromFile() {

    String ret = "";

    try {
      InputStream inputStream = context.openFileInput("locations.json");

      if (inputStream != null) {
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String receiveString = "";
        StringBuilder stringBuilder = new StringBuilder();

        while ((receiveString = bufferedReader.readLine()) != null) {
          stringBuilder.append(receiveString);
        }

        inputStream.close();
        ret = stringBuilder.toString();
      }
    } catch (FileNotFoundException ex) {
      Log.e("login activity", "File not found: " + ex.toString());
    } catch (IOException ex) {
      Log.e("login activity", "Can not read file: " + ex.toString());
    }
    return ret;
  }
示例#16
0
 /**
  * Read match data from a file. Format should be: sourceRelation TAB instanceID TAB field1 TAB ...
  * fieldn LF
  */
 public MatchData(String filename) throws InputFormatException {
   this.filename = filename;
   sourceNames = new ArrayList();
   sourceLists = new HashMap();
   try {
     BufferedReader in = new BufferedReader(new FileReader(filename));
     String line;
     int lineNum = 0;
     while ((line = in.readLine()) != null) {
       lineNum++;
       String tok[] = line.split("\t", -1);
       int toklen = tok.length;
       if (toklen < 1) throw new InputFormatException(filename, lineNum, "no source");
       String src = tok[0];
       if (toklen < 2) throw new InputFormatException(filename, lineNum, "no id");
       String id = tok[1];
       if (toklen < 3) throw new InputFormatException(filename, lineNum, "no text fields");
       String text = tok[2];
       for (int i = 3; i < toklen; i++) {
         text += "\t" + tok[i];
       }
       addInstance(src, id, text);
     }
     in.close();
   } catch (IOException e) {
     throw new InputFormatException(filename, 0, e.toString());
   }
 }
示例#17
0
  public BuffBitstream(byte[] in, int offset, int length) {
    type = BS_INPUT;
    int _buf_len = in.length;

    ibuf_len = _buf_len;
    icur_bit = 0;
    itot_bits = 0;
    ibuf = new byte[_buf_len];

    dbuf_len = _buf_len;
    dcur_bit = 0;
    dtot_bits = 0;
    dsize = 0;
    dbuf = new byte[_buf_len];

    cur_buf = 0; // Current buffer is i/o buffer
    buf = ibuf;
    buf_len = ibuf_len;
    cur_bit = icur_bit;
    tot_bits = itot_bits;

    try {
      this.in = new ByteArrayInputStream(in, offset, length);
      cur_bit = BUF_LEN << 3; // Fake we are at the eof of buffer
      fill_buf();
    } catch (IOException e) {
      throw new IllegalStateException(e.toString());
    }
    close_fd = true;
  }
 private String getIPAndroid() {
   String host = "localhost";
   try {
     ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", "adb shell netcfg");
     builder.redirectErrorStream(true);
     Process p = builder.start();
     BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
     String line;
     while (true) {
       line = r.readLine();
       if (line == null) {
         break;
       }
       if (line.contains("0x00001043")) {
         //                    wlan0    UP                                192.168.1.79/24
         // 0x00001043 b4:52:7d:c5:8b:69
         int index = line.indexOf("/24");
         line = line.substring(0, index);
         index = line.lastIndexOf(" ");
         host = line.substring(index + 1);
         break;
       }
     }
   } catch (IOException e) {
     e.printStackTrace();
     Notifications.Bus.notify(
         new Notification(
             Constant.GROUND_ID, "Error getIPAndroid", e.toString(), NotificationType.ERROR));
   }
   return host;
 }
  public String getText() {
    String S = null;
    FileReader fr = null;
    BufferedReader br;
    try {
      fr = new FileReader(path);
      br = new BufferedReader(fr);

      // Textzeilen der Datei einlesen und auf Konsole ausgeben:
      String zeile;
      zeile = br.readLine();

      while (zeile != null) {
        S += zeile;
        zeile = br.readLine();
      }
      br.close();

    } catch (IOException e) {
      System.out.println("Fehler beim Lesen der Datei " + path);
      System.out.println(e.toString());
    }

    return S;
  }
示例#20
0
  public static void main(String[] args) {
    try {
      InferenceGraph G = new InferenceGraph("hw5.bif");
      Vector nodes = G.get_nodes();
      InferenceGraphNode n = ((InferenceGraphNode) nodes.elementAt(0));
      System.out.println(n.get_name());
      n.get_Prob().print();

      // Create string of variable-value pairs for probability table at node 0*/
      String[][] s = new String[1][2];
      s[0][0] = "B";
      s[0][1] = "False";
      // Compute probability with given variable-value pairs;
      System.out.println(n.get_function_value(s));

      Vector children = n.get_children(); // get_parents() works too;
      for (Enumeration e = children.elements(); e.hasMoreElements(); ) {
        InferenceGraphNode no = (InferenceGraphNode) (e.nextElement());
        System.out.println("\t" + no.get_name());
        no.get_Prob().print(); // Get the probability table object for the node -> Look at
        // ProbabilityFunction.java for info
      }

    } catch (IFException e) {
      System.out.println("Formatting Incorrect " + e.toString());
    } catch (FileNotFoundException e) {
      System.out.println("File not found " + e.toString());
    } catch (IOException e) {
      System.out.println("File not found " + e.toString());
    }
  }
示例#21
0
 /**
  * Generates an X.509 certificate object and initializes it with the data read from the input
  * stream <code>is</code>.
  *
  * @param is an input stream with the certificate data.
  * @return an X.509 certificate object initialized with the data from the input stream.
  * @exception CertificateException on parsing errors.
  */
 public Certificate engineGenerateCertificate(InputStream is) throws CertificateException {
   if (is == null) {
     // clear the caches (for debugging)
     certCache.clear();
     X509CertificatePair.clearCache();
     throw new CertificateException("Missing input stream");
   }
   try {
     byte[] encoding = readOneBlock(is);
     if (encoding != null) {
       X509CertImpl cert = getFromCache(certCache, encoding);
       if (cert != null) {
         return cert;
       }
       cert = new X509CertImpl(encoding);
       addToCache(certCache, cert.getEncodedInternal(), cert);
       return cert;
     } else {
       throw new IOException("Empty input");
     }
   } catch (IOException ioe) {
     throw (CertificateException)
         new CertificateException("Could not parse certificate: " + ioe.toString()).initCause(ioe);
   }
 }
示例#22
0
 public void call() {
   BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
   PrintStream out = System.out;
   SSLSocketFactory f = (SSLSocketFactory) SSLSocketFactory.getDefault();
   try {
     SSLSocket c = (SSLSocket) f.createSocket("localhost", 8888);
     printSocketInfo(c);
     c.startHandshake();
     BufferedWriter w = new BufferedWriter(new OutputStreamWriter(c.getOutputStream()));
     BufferedReader r = new BufferedReader(new InputStreamReader(c.getInputStream()));
     String m = null;
     while ((m = r.readLine()) != null) {
       out.println(m);
       m = in.readLine();
       w.write(m, 0, m.length());
       w.newLine();
       w.flush();
     }
     w.close();
     r.close();
     c.close();
   } catch (IOException e) {
     System.err.println(e.toString());
   }
 }
  public static BufferedImage encodeImage(String filename, int[] primes) {
    /* encodes a and b in the image using a sequence.
     * We are assuming that the image would be big enough
     * to hold the 16 bits
     */

    BufferedImage img, newimg = null;
    int[] a = convertToBinary(primes[0], 8);
    int[] b = convertToBinary(primes[1], 8);
    int[] a_b = copyBits(a, b); // copy all bits into one array

    try {
      img = ImageIO.read(new File(imagePath + filename));
      for (int i = 0; i < a_b.length; i++) {
        int p = img.getRGB(i, i);
        int[] bin = convertToBinary(p, 32);
        bin[0] = a_b[i];
        int d = convertToDigit(bin, 32);
        img.setRGB(i, i, d);
      }
      ImageIO.write(img, "png", new File(imagePath + "new_" + filename));
      newimg = ImageIO.read(new File(imagePath + "new_" + filename));
    } catch (IOException e) {
      System.out.println("ERROR WRITING IMAGE...\n" + e.toString());
      System.exit(1);
    }

    return newimg;
  }
示例#24
0
 static void writeWav() {
   try {
     writeWav(data.toByteArray());
   } catch (IOException e) {
     Log.e("blow", "blew it : " + e.toString());
   }
 }
示例#25
0
 // TODO: Near as I can tell NanoHTTPD has a single input stream for all requests so you have to
 // just know when
 // to stop reading or you'll block until a new request comes in. So I use this function to read
 // exactly the
 // number of bytes in the stream which only works because currently NanoHTTPD doesn't support
 // chunked encoding
 // on requests.
 protected static String InputStreamOfCharsToString(int contentLength, InputStream inputStream) {
   String requestBody = null;
   // TODO: This is wrong on so many levels. First, we should validate that
   // we want to deal with the content we have given. Second, this
   // doesn't deal with chunked content. Third, we don't check that
   // the content is actually UTF-8. Fourth, we don't check the MIME
   // type. Fifth, we actually store everything in memory rather than
   // processing it as a stream so we can use RAM better. Etc.
   if (contentLength > 0) {
     byte[] byteArray = new byte[contentLength];
     try {
       int bytesRead = 0;
       while (bytesRead < contentLength) {
         int currentBytesRead = inputStream.read(byteArray, bytesRead, contentLength - bytesRead);
         if (currentBytesRead == -1) {
           break;
         }
         bytesRead += currentBytesRead;
       }
       if (bytesRead != contentLength) {
         throw new RuntimeException(
             "Expected " + contentLength + "bytes but got " + bytesRead + "bytes.");
       }
       requestBody = new String(byteArray, "UTF-8");
     } catch (IOException ioe) {
       throw new RuntimeException(ioe.toString());
     }
   }
   return requestBody;
 }
示例#26
0
    public void actionPerformed(ActionEvent e) {
      int index = list.getSelectedIndex();
      if (index == -1) {
        return;
      }
      int returnVal = fc.showOpenDialog(fileBackupProgram.this);

      if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        Path directory = file.toPath();

        try {
          destination.setText("Destination Directory: " + directory.toRealPath());
          // destField.setValue(directory.toRealPath());
        } catch (IOException x) {
          printer.printError(x.toString());
        }

        directoryList.getDirectory(index).setDestination(directory);
        startButton.setEnabled(true);
      } else {
        log.append("Open command cancelled by user." + newline);
      }
      log.setCaretPosition(log.getDocument().getLength());
    }
示例#27
0
    public void run() {
      // run this first, ie shutdown the container before closing jarFiles to avoid errors with
      // classes missing
      if (callMethod != null) {
        try {
          callMethod.invoke(callObject);
        } catch (Exception e) {
          System.out.println("Error in shutdown: " + e.toString());
        }
      }

      // give things a couple seconds to destroy; this way of running is mostly for dev/test where
      // this should be sufficient
      try {
        synchronized (this) {
          this.wait(2000);
        }
      } catch (Exception e) {
        System.out.println("Shutdown wait interrupted");
      }
      System.out.println(
          "========== Shutting down Moqui Executable (closing jars, etc) ==========");

      // close all jarFiles so they will "deleteOnExit"
      for (JarFile jarFile : jarFileList) {
        try {
          jarFile.close();
        } catch (IOException e) {
          System.out.println("Error closing jar [" + jarFile + "]: " + e.toString());
        }
      }
    }
示例#28
0
  public void run() {
    String capitalizedSentence;

    System.out.println("TCP Server Thread " + name + " is running until QUIT is received!");

    try {
      /* Socket-Basisstreams durch spezielle Streams filtern */
      inFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      outToClient = new DataOutputStream(socket.getOutputStream());

      while (serviceRequested) {
        /* String vom Client empfangen und in Gro�buchstaben umwandeln */
        capitalizedSentence = readFromClient().toUpperCase();

        /* Modifizierten String an Client senden */
        writeToClient(capitalizedSentence);

        /* Test, ob Arbeitsthread beendet werden soll */
        if (capitalizedSentence.indexOf("QUIT") > -1) {
          serviceRequested = false;
        }
      }

      /* Socket-Streams schlie�en --> Verbindungsabbau */
      socket.close();
    } catch (IOException e) {
      System.err.println(e.toString());
      System.exit(1);
    }

    System.out.println("TCP Server Thread " + name + " stopped!");
  }
示例#29
0
  public static void main(String[] args) {
    ServerSocket welcomeSocket; // TCP-Server-Socketklasse
    Socket connectionSocket; // TCP-Standard-Socketklasse

    int counter = 0; // Z�hlt die erzeugten Bearbeitungs-Threads

    try {
      /* Server-Socket erzeugen */
      welcomeSocket = new ServerSocket(SERVER_PORT);

      while (true) { // Server laufen IMMER
        System.out.println(
            "TCP Server: Waiting for connection - listening TCP port " + SERVER_PORT);
        /*
         * Blockiert auf Verbindungsanfrage warten --> nach
         * Verbindungsaufbau Standard-Socket erzeugen und
         * connectionSocket zuweisen
         */
        connectionSocket = welcomeSocket.accept();

        /* Neuen Arbeits-Thread erzeugen und den Socket �bergeben */
        (new TCPServerThread(++counter, connectionSocket)).start();
      }
    } catch (IOException e) {
      System.err.println(e.toString());
    }
  }
示例#30
0
  public SSLResult fingerprint() throws IOException, FingerprintError {

    SSLConfigCollector scc;

    scc = new SSLConfigCollector(host, port, si);
    scc.setCertValidator(cv);

    startDate = new Date();

    sslSupport = SSLResult.UNKNOWN;

    // If a delay is set, wait some time, except for
    // the first request
    if (!initial && (delay > 0)) {
      if (Debug.get(Debug.Delay)) {
        System.err.println("Delaying request.");
      }
      try {
        Thread.sleep(delay);
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
      }
    }
    initial = false;

    try {
      scc.probe();
      sslSupport = SSLResult.SUPPORTED;
      sslSupportReason = null;
    } catch (NoSSLException e) {
      // This exception is thrown when the protocol support
      // for ssl is not available
      sslSupport = SSLResult.UNSUPPORTED;
      sslSupportReason = e.toString();
    } catch (FingerprintException e) {
      sslSupport = SSLResult.UNSUPPORTED;
      sslSupportReason = e.toString();
    } catch (IOException e) {
      sslSupport = SSLResult.UNKNOWN;
      sslSupportReason = e.toString();
    }
    endDate = new Date();

    protos = scc.getSupportedProtos();

    ProbeResult pres =
        new ProbeResult(
            host,
            port,
            startDate,
            endDate,
            sslSupport,
            sslSupportReason,
            scc.getServerCertificates(),
            scc.serverCertificateVerifies(),
            scc.serverCertNameMatch());

    pres.setProtosResult(protos);
    return pres;
  }