/**
   * Connects to the remote machine by establishing a tunnel through a HTTP proxy with Basic
   * authentication. It issues a CONNECT request and authenticates with the HTTP proxy with Basic
   * protocol.
   *
   * @param address remote machine to connect to
   * @return a TCP/IP socket connected to the remote machine
   * @throws IOException if an I/O error occurs during handshake (a network problem)
   */
  private Socket authenticateBasic(InetSocketAddress address, ConnectivitySettings cs)
      throws IOException {
    Socket proxy = new Socket(cs.getProxyHost(), cs.getProxyPort());
    BufferedReader r =
        new BufferedReader(
            new InputStreamReader(new InterruptibleInputStream(proxy.getInputStream())));
    DataOutputStream dos = new DataOutputStream(proxy.getOutputStream());

    String username = cs.getProxyUsername() == null ? "" : cs.getProxyUsername();
    String password = cs.getProxyPassword() == null ? "" : String.valueOf(cs.getProxyPassword());
    String credentials = username + ":" + password;
    String basicCookie = Base64Encoder.encode(credentials.getBytes("US-ASCII"));

    dos.writeBytes("CONNECT ");
    dos.writeBytes(address.getHostName() + ":" + address.getPort());
    dos.writeBytes(" HTTP/1.0\r\n");
    dos.writeBytes("Connection: Keep-Alive\r\n");
    dos.writeBytes("Proxy-Authorization: Basic " + basicCookie + "\r\n");
    dos.writeBytes("\r\n");
    dos.flush();

    String line = r.readLine();
    if (sConnectionEstablishedPattern.matcher(line).find()) {
      for (; ; ) {
        line = r.readLine();
        if (line.length() == 0) break;
      }
      return proxy;
    }
    throw new IOException("Basic authentication failed: " + line);
  }
Example #2
0
 @Override
 public int commit() {
   String key;
   String value;
   rm();
   try {
     for (Map.Entry<String, String> i : map.entrySet()) {
       key = i.getKey();
       value = i.getValue();
       Integer ndirectory = Math.abs(key.getBytes("UTF-8")[0] % N);
       Integer nfile = Math.abs((key.getBytes("UTF-8")[0] / N) % N);
       String pathToDir = path + File.separator + ndirectory.toString() + ".dir";
       File file = new File(pathToDir);
       if (!file.exists()) {
         file.mkdir();
       }
       String pathToFile =
           path
               + File.separator
               + ndirectory.toString()
               + ".dir"
               + File.separator
               + nfile.toString()
               + ".dat";
       file = new File(pathToFile);
       if (!file.exists()) {
         file.createNewFile();
       }
       DataOutputStream outStream = new DataOutputStream(new FileOutputStream(pathToFile, true));
       byte[] byteWord = key.getBytes("UTF-8");
       outStream.writeInt(byteWord.length);
       outStream.write(byteWord);
       outStream.flush();
       byteWord = value.getBytes("UTF-8");
       outStream.writeInt(byteWord.length);
       outStream.write(byteWord);
       outStream.flush();
       outStream.close();
     }
   } catch (IOException e) {
     System.err.println(e.getMessage());
     System.exit(-1);
   }
   TableState ts = new TableState(map, unsavedChanges, numberOfElements);
   tableStates.put(++numberOfState, ts);
   int n = unsavedChanges;
   unsavedChanges = 0;
   return n;
 }
Example #3
0
 public static void main(String[] args) throws IOException, NoSuchAlgorithmException {
   DataOutputStream output = new DataOutputStream(new BufferedOutputStream(System.out));
   LRC lrc = new LRC(output);
   DataInputStream input = new DataInputStream(new BufferedInputStream(System.in));
   lrc.writeStream(input);
   output.flush();
 }
Example #4
0
 /** @param args the command line arguments */
 public static void main(String[] args) throws Exception {
   BufferedReader br =
       new BufferedReader(new InputStreamReader(new FileInputStream("/var/song.txt"), "UTF-8"));
   Map map = new TreeMap();
   String line = null;
   while ((line = br.readLine()) != null) {
     System.out.println("line:" + line);
     try {
       String[] strs = line.split("\t");
       String str = " ";
       if (strs != null && strs.length >= 2) str = strs[1];
       map.put(new Integer(strs[0]), str);
     } catch (Exception e) {
       System.out.println("Opuszczam linie " + e.toString());
     }
   }
   DataOutputStream dos = new DataOutputStream(new FileOutputStream("/var/song.bin"));
   dos.writeInt(map.size());
   for (Iterator it = map.keySet().iterator(); it.hasNext(); ) {
     Integer pos = (Integer) it.next();
     String txt = (String) map.get(pos);
     dos.writeInt(pos.intValue());
     dos.writeUTF(txt);
   }
   dos.flush();
   dos.close();
 }
Example #5
0
 public static boolean HTTPRequestToFile(
     File file, String inUrl, String method, String data, List headers) {
   boolean success = false;
   try {
     if (file.exists()) file.delete();
   } catch (Exception e) {
     Logger.getLogger(com.bombdiggity.util.HTTPUtils.class)
         .error(
             (new StringBuilder("HTTPUtils.HTTPRequestToFile delete ("))
                 .append(file)
                 .append("): ")
                 .append(e.toString())
                 .toString());
   }
   try {
     DataOutputStream printout = null;
     DataInputStream input = null;
     URL url = new URL(inUrl);
     URLConnection urlConn = url.openConnection();
     urlConn.setDoInput(true);
     urlConn.setDoOutput(true);
     urlConn.setUseCaches(false);
     if (headers != null) {
       for (Iterator iter = headers.iterator(); iter.hasNext(); ) {
         Map nameValuePair = (Map) iter.next();
         String key;
         String value;
         for (Iterator iter2 = nameValuePair.keySet().iterator();
             iter2.hasNext();
             urlConn.setRequestProperty(key, value)) {
           key = (String) iter2.next();
           value = (String) nameValuePair.get(key);
         }
       }
     }
     if (data != null) {
       byte inData[] = data.getBytes("UTF-8");
       printout = new DataOutputStream(urlConn.getOutputStream());
       printout.write(inData);
       printout.flush();
       printout.close();
       printout = null;
     }
     input = new DataInputStream(urlConn.getInputStream());
     DataOutputStream dataOut = new DataOutputStream(new FileOutputStream(file, false));
     int rChunk = 0x10000;
     byte myData[] = new byte[rChunk];
     do {
       int bytesRead = input.read(myData, 0, rChunk);
       if (bytesRead == -1) break;
       dataOut.write(myData, 0, bytesRead);
       Thread.sleep(1L);
     } while (true);
     input.close();
     input = null;
     success = true;
   } catch (Exception exception) {
   }
   return success;
 }
Example #6
0
  public static void reset() {
    // network@ip:10002
    String address = source.substring(8, source.length() - 6);

    try {
      Socket server = new Socket(address, 9999);
      DataOutputStream out = new DataOutputStream(server.getOutputStream());
      out.writeBytes("\r\n");
      out.flush();
      out.writeBytes("9\r\n");
      out.flush();
    } catch (Exception e) {
      System.out.println("Sorry I can't reset the device fro some reason: " + e);
      System.exit(1);
    }
    System.out.println("Issued reset command to " + address);
  }
Example #7
0
 public static void httpWrite(HttpURLConnection cx, String data)
     throws IOException, ProtocolException {
   cx.setDoOutput(true);
   DataOutputStream wr = new DataOutputStream(cx.getOutputStream());
   wr.writeBytes(data);
   wr.flush();
   wr.close();
 }
Example #8
0
 public void cutScore(String whom) {
   try {
     out88.writeUTF("减分");
     out88.flush();
     out88.writeUTF("");
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Example #9
0
  /**
   * Generates a byte array representing the contents of this page. Used to serialize this page to
   * disk.
   *
   * <p>The invariant here is that it should be possible to pass the byte array generated by
   * getPageData to the HeapPage constructor and have it produce an identical HeapPage object.
   *
   * @see #HeapPage
   * @return A byte array correspond to the bytes of this page.
   */
  public byte[] getPageData() {
    // int len = header.length*4 + BufferPool.PAGE_SIZE;
    int len = BufferPool.PAGE_SIZE;
    ByteArrayOutputStream baos = new ByteArrayOutputStream(len);
    DataOutputStream dos = new DataOutputStream(baos);

    // create the header of the page
    try {
      dos.write(header.getHeader());
    } catch (IOException e) {
      // this really shouldn't happen
      e.printStackTrace();
    }

    // create the tuples
    for (int i = 0; i < numSlots; i++) {

      // empty slot
      if (!getSlot(i)) {
        for (int j = 0; j < td.getSize(); j++) {
          try {
            dos.writeByte(0);
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
        continue;
      }

      // non-empty slot
      for (int j = 0; j < td.numFields(); j++) {
        Field f = tuples[i].getField(j);
        try {
          f.serialize(dos);
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }

    // padding
    int zerolen = BufferPool.PAGE_SIZE - numSlots * td.getSize() - header.length();
    byte[] zeroes = new byte[zerolen];
    try {
      dos.write(zeroes, 0, zerolen);
    } catch (IOException e) {
      e.printStackTrace();
    }

    try {
      dos.flush();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return baos.toByteArray();
  }
Example #10
0
 private void sendRequest(long objectId, long requestId, Request r) throws IOException {
   DataOutputStream out = newFlusher();
   out.writeByte(REQUEST);
   out.writeLong(objectId);
   out.writeLong(requestId);
   r.serialize(out);
   out.writeBoolean(false);
   out.flush();
 }
Example #11
0
 public void addScore() {
   try {
     out88.writeUTF("加分");
     out88.flush();
     out88.writeUTF("");
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Example #12
0
  /** Sends a GET_MBR_REQ to *all* GossipRouters, merges responses. */
  private List _getMembers(String group) {
    List ret = new LinkedList();
    Socket sock = null;
    SocketAddress destAddr;
    DataOutputStream out = null;
    DataInputStream in = null;
    IpAddress entry;
    GossipData gossip_req, gossip_rsp;
    Address mbr;

    for (int i = 0; i < gossip_servers.size(); i++) {
      entry = (IpAddress) gossip_servers.elementAt(i);
      if (entry.getIpAddress() == null || entry.getPort() == 0) {
        if (log.isErrorEnabled()) log.error("entry.host or entry.port is null");
        continue;
      }

      try {
        // sock=new Socket(entry.getIpAddress(), entry.getPort());
        sock = new Socket();
        destAddr = new InetSocketAddress(entry.getIpAddress(), entry.getPort());
        sock.connect(destAddr, SOCKET_TIMEOUT);
        out = new DataOutputStream(sock.getOutputStream());

        gossip_req = new GossipData(GossipRouter.GOSSIP_GET, group, null, null);
        // must send GossipData as fast as possible, otherwise the
        // request might be rejected
        gossip_req.writeTo(out);
        out.flush();

        in = new DataInputStream(sock.getInputStream());
        gossip_rsp = new GossipData();
        gossip_rsp.readFrom(in);
        if (gossip_rsp.mbrs != null) { // merge with ret
          for (Iterator it = gossip_rsp.mbrs.iterator(); it.hasNext(); ) {
            mbr = (Address) it.next();
            if (!ret.contains(mbr)) ret.add(mbr);
          }
        }
      } catch (Exception ex) {
        if (log.isErrorEnabled()) log.error("exception connecting to host " + entry);
      } finally {
        Util.close(out);
        Util.close(in);
        if (sock != null) {
          try {
            sock.close();
          } catch (IOException e) {
          }
        }
      }
    }

    return ret;
  }
Example #13
0
  /**
   * Connect to searchd server and update given attributes on given documents in given indexes.
   * Sample code that will set group_id=123 where id=1 and group_id=456 where id=3:
   *
   * <pre>
   * String[] attrs = new String[1];
   *
   * attrs[0] = "group_id";
   * long[][] values = new long[2][2];
   *
   * values[0] = new long[2]; values[0][0] = 1; values[0][1] = 123;
   * values[1] = new long[2]; values[1][0] = 3; values[1][1] = 456;
   *
   * int res = cl.UpdateAttributes ( "test1", attrs, values );
   * </pre>
   *
   * @param index index name(s) to update; might be distributed
   * @param attrs array with the names of the attributes to update
   * @param values array of updates; each long[] entry must contains document ID in the first
   *     element, and all new attribute values in the following ones
   * @param ignorenonexistent the flag whether to silently ignore non existent columns up update
   *     request
   * @return -1 on failure, amount of actually found and updated documents (might be 0) on success
   * @throws SphinxException on invalid parameters
   */
  public int UpdateAttributes(
      String index, String[] attrs, long[][] values, boolean ignorenonexistent)
      throws SphinxException {
    /* check args */
    myAssert(index != null && index.length() > 0, "no index name provided");
    myAssert(attrs != null && attrs.length > 0, "no attribute names provided");
    myAssert(values != null && values.length > 0, "no update entries provided");
    for (int i = 0; i < values.length; i++) {
      myAssert(values[i] != null, "update entry #" + i + " is null");
      myAssert(values[i].length == 1 + attrs.length, "update entry #" + i + " has wrong length");
    }

    /* build and send request */
    ByteArrayOutputStream reqBuf = new ByteArrayOutputStream();
    DataOutputStream req = new DataOutputStream(reqBuf);
    try {
      writeNetUTF8(req, index);

      req.writeInt(attrs.length);
      req.writeInt(ignorenonexistent ? 1 : 0);
      for (int i = 0; i < attrs.length; i++) {
        writeNetUTF8(req, attrs[i]);
        req.writeInt(0); // not MVA attr
      }

      req.writeInt(values.length);
      for (int i = 0; i < values.length; i++) {
        req.writeLong(values[i][0]); /* send docid as 64bit value */
        for (int j = 1; j < values[i].length; j++)
          req.writeInt(
              (int)
                  values[i][
                      j]); /* send values as 32bit values; FIXME! what happens when they are over 2^31? */
      }

      req.flush();

    } catch (Exception e) {
      _error = "internal error: failed to build request: " + e;
      return -1;
    }

    /* get and parse response */
    DataInputStream in = _DoRequest(SEARCHD_COMMAND_UPDATE, VER_COMMAND_UPDATE, reqBuf);
    if (in == null) return -1;

    try {
      return in.readInt();
    } catch (Exception e) {
      _error = "incomplete reply";
      return -1;
    }
  }
Example #14
0
  public void doGetDAP2Data(ReqState rs) throws Exception {
    HttpServletResponse response = rs.getResponse();

    GuardedDataset ds = null;
    try {
      ds = getDataset(rs);
      if (null == ds) return;

      response.setContentType("application/octet-stream");
      response.setHeader("XDODS-Server", getServerVersion());
      response.setHeader("Content-Description", "dods-data");

      ServletOutputStream sOut = response.getOutputStream();
      OutputStream bOut;
      DeflaterOutputStream dOut = null;
      if (rs.getAcceptsCompressed() && allowDeflate) {
        response.setHeader("Content-Encoding", "deflate");
        dOut = new DeflaterOutputStream(sOut);
        bOut = new BufferedOutputStream(dOut);

      } else {
        bOut = new BufferedOutputStream(sOut);
      }

      ServerDDS myDDS = ds.getDDS();
      CEEvaluator ce = new CEEvaluator(myDDS);
      ce.parseConstraint(rs);
      checkSize(myDDS, false);

      // Send the constrained DDS back to the client
      PrintWriter pw = new PrintWriter(new OutputStreamWriter(bOut));
      myDDS.printConstrained(pw);

      // Send the Data delimiter back to the client
      pw.flush();
      bOut.write("\nData:\n".getBytes());
      bOut.flush();

      // Send the binary data back to the client
      DataOutputStream sink = new DataOutputStream(bOut);
      ce.send(myDDS.getEncodedName(), sink, ds);
      sink.flush();

      // Finish up sending the compressed stuff, but don't
      // close the stream (who knows what the Servlet may expect!)
      if (null != dOut) dOut.finish();
      bOut.flush();

    } finally { // release lock if needed
      if (ds != null) ds.release();
    }
  }
Example #15
0
 public static byte[] HTTPRequestToByteArray(
     String inUrl, String method, String data, List headers) {
   byte ret[] = (byte[]) null;
   ByteArrayOutputStream byteOut = null;
   try {
     DataOutputStream printout = null;
     DataInputStream input = null;
     URL url = new URL(inUrl);
     URLConnection urlConn = url.openConnection();
     urlConn.setDoInput(true);
     urlConn.setDoOutput(true);
     urlConn.setUseCaches(false);
     if (headers != null) {
       for (Iterator iter = headers.iterator(); iter.hasNext(); ) {
         Map nameValuePair = (Map) iter.next();
         String key;
         String value;
         for (Iterator iter2 = nameValuePair.keySet().iterator();
             iter2.hasNext();
             urlConn.setRequestProperty(key, value)) {
           key = (String) iter2.next();
           value = (String) nameValuePair.get(key);
         }
       }
     }
     if (data != null) {
       byte inData[] = data.getBytes("UTF-8");
       printout = new DataOutputStream(urlConn.getOutputStream());
       printout.write(inData);
       printout.flush();
       printout.close();
       printout = null;
     }
     input = new DataInputStream(urlConn.getInputStream());
     byteOut = new ByteArrayOutputStream();
     DataOutputStream dataOut = new DataOutputStream(byteOut);
     int rChunk = 0x10000;
     byte myData[] = new byte[rChunk];
     do {
       int bytesRead = input.read(myData, 0, rChunk);
       if (bytesRead == -1) break;
       dataOut.write(myData, 0, bytesRead);
       Thread.sleep(1L);
     } while (true);
     input.close();
     input = null;
     ret = byteOut.toByteArray();
   } catch (Exception exception) {
   }
   return ret;
 }
 private byte[] getBytes(short[] array) {
   try {
     ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
     DataOutputStream datastream = new DataOutputStream(bytestream);
     for (short n : array) {
       datastream.writeShort(n);
     }
     datastream.flush();
     return bytestream.toByteArray();
   } catch (IOException ioe) {
     Logging.logger().finest(ioe.getMessage());
   }
   return null;
 }
  /**
   * Connects to the remote machine by establishing a tunnel through a HTTP proxy. It issues a
   * CONNECT request and eventually authenticates with the HTTP proxy. Supported authentication
   * methods include: Basic.
   *
   * @param address remote machine to connect to
   * @return a TCP/IP socket connected to the remote machine
   * @throws UnknownHostException if the proxy host name cannot be resolved
   * @throws IOException if an I/O error occurs during handshake (a network problem)
   */
  private Socket getHttpsTunnelSocket(
      InetSocketAddress address, ConnectivitySettings cs, int timeout) throws IOException {
    Socket proxy = new Socket();
    proxy.connect(new InetSocketAddress(cs.getProxyHost(), cs.getProxyPort()), timeout);
    BufferedReader r =
        new BufferedReader(
            new InputStreamReader(new InterruptibleInputStream(proxy.getInputStream())));
    DataOutputStream dos = new DataOutputStream(proxy.getOutputStream());

    dos.writeBytes("CONNECT ");
    dos.writeBytes(address.getHostName() + ":" + address.getPort());
    dos.writeBytes(" HTTP/1.0\r\n");
    dos.writeBytes("Connection: Keep-Alive\r\n\r\n");
    dos.flush();

    String line;
    line = r.readLine();

    if (sConnectionEstablishedPattern.matcher(line).find()) {
      for (; ; ) {
        line = r.readLine();
        if (line.length() == 0) break;
      }
      return proxy;
    } else if (sProxyAuthRequiredPattern.matcher(line).find()) {
      boolean authMethodSelected = false;
      String authMethod = AUTH_NONE;
      for (; ; ) {
        line = r.readLine();
        if (line.length() == 0) break;
        if (line.startsWith("Proxy-Authenticate:") && !authMethodSelected) {
          authMethod = line.substring(19).trim();
          if (authMethod.equals(AUTH_BASIC)) {
            authMethodSelected = true;
          }
        }
      }
      // TODO: need to read full response before closing connection?
      proxy.close();

      if (authMethod.startsWith(AUTH_BASIC)) {
        return authenticateBasic(address, cs);
      } else {
        throw new IOException("Unsupported authentication method: " + authMethod);
      }
    } else {
      proxy.close();
      throw new IOException("HTTP proxy does not support CONNECT command. Received reply: " + line);
    }
  }
  /**
   * Send request for more data on connection to remote endpoint.
   *
   * @param info connection information structure
   * @param len number of more bytes that can be received
   */
  void sendRequest(MultiplexConnectionInfo info, int len) throws IOException {
    synchronized (dataOut) {
      if (alive && !info.closed)
        try {
          dataOut.writeByte(REQUEST);
          dataOut.writeShort(info.id);
          dataOut.writeInt(len);
          dataOut.flush();
        } catch (IOException e) {
          multiplexLog.log(Log.BRIEF, "exception: ", e);

          shutDown();
          throw e;
        }
    }
  }
  /**
   * Acknowledge remote endpoint's closing of connection.
   *
   * @param info connection information structure
   */
  void sendCloseAck(MultiplexConnectionInfo info) throws IOException {
    synchronized (dataOut) {
      if (alive && !info.closed)
        try {
          dataOut.writeByte(CLOSEACK);
          dataOut.writeShort(info.id);
          dataOut.flush();
          info.closed = true;
        } catch (IOException e) {
          multiplexLog.log(Log.BRIEF, "exception: ", e);

          shutDown();
          throw e;
        }
    }
  }
Example #20
0
 private void sendResponse(long requestId, Object value, Class<?> declaredType)
     throws IOException {
   DataOutputStream out = newFlusher();
   out.writeByte(RESPONSE);
   out.writeLong(requestId);
   if (value == null) {
     out.writeBoolean(false);
   } else {
     out.writeBoolean(true);
     Class<?> clazz = value.getClass();
     out.writeUTF(clazz.getName());
     Serializer<Object> s = serializerFor(clazz, declaredType);
     s.serialize(out, value);
   }
   out.writeBoolean(false);
   out.flush();
 }
  /** Initiate a new multiplexed connection through the underlying connection. */
  public synchronized TCPConnection openConnection() throws IOException {
    // generate ID that should not be already used
    // If all possible 32768 IDs are used,
    // this method will block searching for a new ID forever.
    int id;
    do {
      lastID = (++lastID) & 0x7FFF;
      id = lastID;

      // The orig flag (copied to the high bit of the ID) is used
      // to have two distinct ranges to choose IDs from for the
      // two endpoints.
      if (orig) id |= 0x8000;
    } while (connectionTable.get(id) != null);

    // create multiplexing streams and bookkeeping information
    MultiplexConnectionInfo info = new MultiplexConnectionInfo(id);
    info.in = new MultiplexInputStream(this, info, 2048);
    info.out = new MultiplexOutputStream(this, info, 2048);

    // add to connection table if multiplexer has not died
    synchronized (connectionTable) {
      if (!alive) throw new IOException("Multiplexer connection dead");
      if (numConnections >= maxConnections)
        throw new IOException(
            "Cannot exceed " + maxConnections + " simultaneous multiplexed connections");
      connectionTable.put(id, info);
      ++numConnections;
    }

    // inform remote endpoint of new connection
    synchronized (dataOut) {
      try {
        dataOut.writeByte(OPEN);
        dataOut.writeShort(id);
        dataOut.flush();
      } catch (IOException e) {
        multiplexLog.log(Log.BRIEF, "exception: ", e);

        shutDown();
        throw e;
      }
    }

    return new TCPConnection(channel, info.in, info.out);
  }
  public synchronized void writeProgress(int current_file, int total_files) {
    try {

      DataOutputStream out =
          new DataOutputStream(new BufferedOutputStream(new FileOutputStream(resume_file, false)));
      out.writeInt(current_file);
      out.writeInt(total_files);
      out.flush();
      out.close();

    } catch (FileNotFoundException e) {
      e.printStackTrace();
      Log.e(TAG, "writeProgress resume.txt not found.");
    } catch (IOException ex) {
      Log.e(TAG, "Unable to create resume.txt.");
    }
  }
  /**
   * Send packet of requested data on connection to remote endpoint.
   *
   * @param info connection information structure
   * @param buf array containing bytes to send
   * @param off offset of first array index of packet
   * @param len number of bytes in packet to send
   */
  void sendTransmit(MultiplexConnectionInfo info, byte buf[], int off, int len) throws IOException {
    synchronized (dataOut) {
      if (alive && !info.closed)
        try {
          dataOut.writeByte(TRANSMIT);
          dataOut.writeShort(info.id);
          dataOut.writeInt(len);
          dataOut.write(buf, off, len);
          dataOut.flush();
        } catch (IOException e) {
          multiplexLog.log(Log.BRIEF, "exception: ", e);

          shutDown();
          throw e;
        }
    }
  }
Example #24
0
 /**
  * \ Draw saved State (color dots on panel) on WhiteBoard
  *
  * @param outstream
  * @throws IOException
  */
 public void writeState(OutputStream outstream) throws IOException {
   if (state == null) return;
   synchronized (state) {
     DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(outstream));
     // DataOutputStream dos=new DataOutputStream(outstream);
     dos.writeInt(state.size());
     for (Map.Entry<Point, Color> entry : state.entrySet()) {
       Point point = entry.getKey();
       Color col = entry.getValue();
       dos.writeInt(point.x);
       dos.writeInt(point.x);
       dos.writeInt(col.getRGB());
     }
     dos.flush();
     System.out.println("wrote " + state.size() + " elements");
   }
 }
Example #25
0
  void _unregister(String group, Address mbr) {
    Socket sock = null;
    DataOutputStream out = null;
    IpAddress entry;
    GossipData gossip_req;

    for (int i = 0; i < gossip_servers.size(); i++) {
      entry = (IpAddress) gossip_servers.elementAt(i);
      if (entry.getIpAddress() == null || entry.getPort() == 0) {
        if (log.isErrorEnabled()) log.error("entry.host or entry.port is null");
        continue;
      }
      try {
        if (log.isTraceEnabled())
          log.trace(
              "UNREGISTER("
                  + group
                  + ", "
                  + mbr
                  + ") with GossipRouter at "
                  + entry.getIpAddress()
                  + ':'
                  + entry.getPort());
        sock = new Socket(entry.getIpAddress(), entry.getPort());
        out = new DataOutputStream(sock.getOutputStream());
        gossip_req = new GossipData(GossipRouter.UNREGISTER, group, mbr, null);
        // must send GossipData as fast as possible, otherwise the
        // request might be rejected
        gossip_req.writeTo(out);
        out.flush();
      } catch (Exception ex) {
        if (log.isErrorEnabled()) log.error("exception connecting to host " + entry);
      } finally {
        Util.close(out);
        if (sock != null) {
          try {
            sock.close();
          } catch (IOException e) {
          }
        }
      }
    }
  }
Example #26
0
  public void run() {
    String objRouter = applet.getParameter("name");
    // No Internationalisation
    try {
      ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
      DataOutputStream outp = new DataOutputStream(byteStream);
      outp.writeInt(GenericConstants.ROUTER_PROPERTIES);
      outp.writeUTF(objRouter);
      outp.flush();

      byte[] bytes = byteStream.toByteArray();
      outp.close();
      byteStream.reset();
      byteStream.close();
      byte[] data = GenericSession.getInstance().syncSend(bytes);
      if (data != null) {
        DataInputStream inp = new DataInputStream(new ByteArrayInputStream(data));
        int reqId = inp.readInt();
        if (reqId == GenericConstants.ROUTER_PROPERTIES) {
          int length = inp.readInt();
          byte serverData[] = new byte[length];
          inp.readFully(serverData);
          routerobject = NmsClientUtil.deSerializeVector(serverData);
        }

        init();
        refresh();
        super.setVisible(true);
      }
      /*init();
      refresh();
      super.setVisible(true);*/

      else close();

    } catch (Exception e) {
      // NmsClientUtil.err(NmsClientUtil.getFrame(app),"IO Error sending request to server.
      // "+e);//No Internationalisation
    }
  }
Example #27
0
  /** Writes the set data to the OutputStream. */
  public void write(OutputStream out) throws DBFException {

    try {

      if (this.raf == null) {

        DataOutputStream outStream = new DataOutputStream(out);

        this.header.numberOfRecords = v_records.size();
        this.header.write(outStream);

        /* Now write all the records */
        int t_recCount = v_records.size();
        for (int i = 0; i < t_recCount; i++) {
          /* iterate through records */

          Object[] t_values = (Object[]) v_records.elementAt(i);

          writeRecord(outStream, t_values);
        }

        outStream.write(END_OF_DATA);
        outStream.flush();
      } else {

        /* everything is written already. just update the header for record count and the END_OF_DATA mark */
        this.header.numberOfRecords = this.recordCount;
        this.raf.seek(0);
        this.header.write(this.raf);
        this.raf.seek(raf.length());
        this.raf.writeByte(END_OF_DATA);
        this.raf.close();
      }

    } catch (IOException e) {

      throw new DBFException(e.getMessage());
    }
  }
    protected Void doInBackground(Void... params) {
      String outString;
      HttpURLConnection c = null;
      DataOutputStream os = null;

      outString = scanData.getOwnBSSID();
      outString = outString + "\nL\tX\t" + lastLat + "\t" + lastLon + "\n";

      try {
        URL connectURL = new URL("http://www.openwlanmap.org/android/upload.php");
        c = (HttpURLConnection) connectURL.openConnection();
        if (c == null) {
          return null;
        }

        c.setDoOutput(true); // enable POST
        c.setRequestMethod("POST");
        c.addRequestProperty("Content-Type", "application/x-www-form-urlencoded, *.*");
        c.addRequestProperty("Content-Length", "" + outString.length());
        os = new DataOutputStream(c.getOutputStream());
        os.write(outString.getBytes());
        os.flush();
        c.getResponseCode();
        os.close();
        outString = null;
        os = null;
      } catch (IOException ioe) {
      } finally {
        try {
          if (os != null) os.close();
          if (c != null) c.disconnect();
        } catch (IOException ioe) {
          ioe.printStackTrace();
        }
      }
      return null;
    }
  void ReceiveFile() throws Exception {
    String fileName;
    System.out.print("Enter File Name :");
    fileName = br.readLine();
    dout.writeUTF(fileName);
    String msgFromServer = din.readUTF();

    if (msgFromServer.compareTo("File Not Found") == 0) {
      System.out.println("File not found on Server ...");
      return;
    } else if (msgFromServer.compareTo("READY") == 0) {
      System.out.println("Receiving File ...");
      File f = new File(fileName);
      if (f.exists()) {
        String Option;
        System.out.println("File Already Exists. Want to OverWrite (Y/N) ?");
        Option = br.readLine();
        if (Option == "N") {
          dout.flush();
          return;
        }
      }
      FileOutputStream fout = new FileOutputStream(f);
      int ch;
      String temp;
      do {
        temp = din.readUTF();
        ch = Integer.parseInt(temp);
        if (ch != -1) {
          fout.write(ch);
        }
      } while (ch != -1);
      fout.close();
      System.out.println(din.readUTF());
    }
  }
Example #30
0
  /**
   * When you call this, you post the data, after which it is gone. The post is synchronous. The
   * function returns after posting and receiving a reply. Get a new data stream with
   * startDataStream() to make a new post. (You could hold on to the writer, but using it will have
   * no effect after calling this method.)
   *
   * @return HTTP response code, 200 means successful.
   */
  public int postToCDB() throws IOException, ProtocolException, UnsupportedEncodingException {
    cdbId = -1;
    if (dataWriter == null) {
      throw new IllegalStateException("call startDataStream() and write something first");
    }
    HttpURLConnection connection = (HttpURLConnection) postURL.openConnection();
    connection.setRequestMethod("POST");

    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    dataWriter.flush();
    String data = JASPER_DATA_PARAM + "=" + URLEncoder.encode(dataWriter.toString(), "UTF-8");
    dataWriter = null;

    connection.setRequestProperty("Content-Length", "" + Integer.toString(data.getBytes().length));
    connection.setUseCaches(false);
    connection.setDoInput(true);
    connection.setDoOutput(true);

    DataOutputStream out = new DataOutputStream(connection.getOutputStream());
    out.writeBytes(data);
    out.flush();
    out.close();

    int responseCode = connection.getResponseCode();
    wasSuccessful = (200 == responseCode);
    InputStream response;
    if (wasSuccessful) {
      response = connection.getInputStream();
    } else {
      response = connection.getErrorStream();
    }
    if (response != null) processResponse(response);
    connection.disconnect();

    return responseCode;
  }