Ejemplo n.º 1
1
  public static String submitPostData(String pos, String data) throws IOException {
    Log.v("req", data);

    URL url = new URL(urlPre + pos);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    configConnection(connection);
    if (sCookie != null && sCookie.length() > 0) {
      connection.setRequestProperty("Cookie", sCookie);
    }
    connection.connect();

    // Send data
    DataOutputStream output = new DataOutputStream(connection.getOutputStream());
    output.write(data.getBytes());
    output.flush();
    output.close();

    // check Cookie
    String cookie = connection.getHeaderField("set-cookie");
    if (cookie != null && !cookie.equals(sCookie)) {
      sCookie = cookie;
    }

    // Respond
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
      sb.append(line + "\n");
    }
    connection.disconnect();
    String res = sb.toString();
    Log.v("res", res);
    return res;
  }
Ejemplo n.º 2
0
  public void testLease() throws Exception {
    Configuration conf = new Configuration();
    MiniDFSCluster cluster = new MiniDFSCluster(conf, 2, true, null);
    try {
      FileSystem fs = cluster.getFileSystem();
      assertTrue(fs.mkdirs(dir));

      Path a = new Path(dir, "a");
      Path b = new Path(dir, "b");

      DataOutputStream a_out = fs.create(a);
      a_out.writeBytes("something");

      assertTrue(hasLease(cluster, a));
      assertTrue(!hasLease(cluster, b));

      DataOutputStream b_out = fs.create(b);
      b_out.writeBytes("something");

      assertTrue(hasLease(cluster, a));
      assertTrue(hasLease(cluster, b));

      a_out.close();
      b_out.close();

      assertTrue(!hasLease(cluster, a));
      assertTrue(!hasLease(cluster, b));

      fs.delete(dir, true);
    } finally {
      if (cluster != null) {
        cluster.shutdown();
      }
    }
  }
    @Override
    public void close() {
      System.err.println(
          "Target: " + vocE.size() + " types. Writing to " + job_.get("root", null) + "/vocab.E");
      System.err.println(
          "Source: " + vocF.size() + " types .Writing to " + job_.get("root", null) + "/vocab.F");

      // write out vocabulary to file
      try {
        FileSystem fs = FileSystem.get(job_);

        DataOutputStream dos =
            new DataOutputStream(
                new BufferedOutputStream(fs.create(new Path(job_.get("root", null) + "/vocab.E"))));
        ((VocabularyWritable) vocE).write(dos);
        dos.close();
        DataOutputStream dos2 =
            new DataOutputStream(
                new BufferedOutputStream(fs.create(new Path(job_.get("root", null) + "/vocab.F"))));
        ((VocabularyWritable) vocF).write(dos2);
        dos2.close();

      } catch (IOException e) {
        throw new RuntimeException("Vocab couldn't be written to disk.\n" + e.toString());
      }
    }
  /* Save generated parameters in a binary file */
  public void saveParam(String fileName, HTSPStream par, HMMData.FeatureType type) {
    int t, m, i;
    try {

      if (type == HMMData.FeatureType.LF0) {
        fileName += ".f0";
        DataOutputStream data_out = new DataOutputStream(new FileOutputStream(fileName));
        i = 0;
        for (t = 0; t < voiced.length; t++) {
            /* here par.getT are just the voiced!!! */
          if (voiced[t]) {
            data_out.writeFloat((float) Math.exp(par.getPar(i, 0)));
            i++;
          } else data_out.writeFloat((float) 0.0);
        }
        data_out.close();

      } else if (type == HMMData.FeatureType.MGC) {
        fileName += ".mgc";
        DataOutputStream data_out = new DataOutputStream(new FileOutputStream(fileName));
        for (t = 0; t < par.getT(); t++)
          for (m = 0; m < par.getOrder(); m++) data_out.writeFloat((float) par.getPar(t, m));
        data_out.close();
      }

      logger.info("saveParam in file: " + fileName);

    } catch (IOException e) {
      logger.info("IO exception = " + e);
    }
  }
Ejemplo n.º 5
0
 private String getString(PublicKey key) throws FailedLoginException {
   try {
     if (key instanceof DSAPublicKey) {
       DSAPublicKey dsa = (DSAPublicKey) key;
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       DataOutputStream dos = new DataOutputStream(baos);
       write(dos, "ssh-dss");
       write(dos, dsa.getParams().getP());
       write(dos, dsa.getParams().getQ());
       write(dos, dsa.getParams().getG());
       write(dos, dsa.getY());
       dos.close();
       return base64Encode(baos.toByteArray());
     } else if (key instanceof RSAKey) {
       RSAPublicKey rsa = (RSAPublicKey) key;
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       DataOutputStream dos = new DataOutputStream(baos);
       write(dos, "ssh-rsa");
       write(dos, rsa.getPublicExponent());
       write(dos, rsa.getModulus());
       dos.close();
       return base64Encode(baos.toByteArray());
     } else {
       throw new FailedLoginException("Unsupported key type " + key.getClass().toString());
     }
   } catch (IOException e) {
     throw new FailedLoginException("Unable to check public key");
   }
 }
Ejemplo n.º 6
0
 private void writeVersion() throws IOException {
   DataOutputStream out = this.writer.prepareAppendKey(-1);
   VERSION_KEY.write(out);
   out.close();
   out = this.writer.prepareAppendValue(-1);
   out.writeInt(VERSION);
   out.close();
 }
Ejemplo n.º 7
0
 public void writeApplicationOwner(String user) throws IOException {
   DataOutputStream out = this.writer.prepareAppendKey(-1);
   APPLICATION_OWNER_KEY.write(out);
   out.close();
   out = this.writer.prepareAppendValue(-1);
   out.writeUTF(user);
   out.close();
 }
Ejemplo n.º 8
0
 public void append(LogKey logKey, LogValue logValue) throws IOException {
   DataOutputStream out = this.writer.prepareAppendKey(-1);
   logKey.write(out);
   out.close();
   out = this.writer.prepareAppendValue(-1);
   logValue.write(out);
   out.close();
 }
Ejemplo n.º 9
0
  void removeEntry(String entry, boolean first) {
    String[] params = entry.split(",");
    entry = params[0] + " " + params[1];
    List<String> hosts = new ArrayList<String>();
    try {
      Process proc = Runtime.getRuntime().exec("cat /etc/hosts");
      BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
      String line = null;
      while ((line = reader.readLine()) != null) {
        if (!line.equals("") && line != null) {
          if (line.contains(entry) && first) {
            first = false;
          } else if (line.contains(entry) && !first) {
            hosts.add(line);
          } else if (!line.contains(entry)) {
            hosts.add(line);
          }
        }
      }
    } catch (Exception e) {

    }
    if (hosts.size() > 0) {
      try {
        Process proc = Runtime.getRuntime().exec("su");
        DataOutputStream os = new DataOutputStream(proc.getOutputStream());
        os.writeBytes("mount -o rw,remount -t " + fs + " " + block + " /system\n");
        os.writeBytes("echo '' > /etc/hosts\n");
        for (String s : hosts) {
          os.writeBytes("echo '" + s + "' >> /etc/hosts\n");
        }
        os.writeBytes("mount -o ro,remount -t " + fs + " " + block + " /system\n");
        os.writeBytes("exit\n");
        os.flush();
        os.close();
        proc.waitFor();
      } catch (Exception e) {

      }
    } else {
      try {
        Process proc = Runtime.getRuntime().exec("su");
        DataOutputStream os = new DataOutputStream(proc.getOutputStream());
        os.writeBytes("mount -o rw,remount -t " + fs + " " + block + " /system\n");
        os.writeBytes("echo '' > /etc/hosts\n");
        os.writeBytes("mount -o ro,remount -t " + fs + " " + block + " /system\n");
        os.writeBytes("exit\n");
        os.flush();
        os.close();
        proc.waitFor();
      } catch (Exception e) {

      }
    }
  }
Ejemplo n.º 10
0
 public void writeApplicationACLs(Map<ApplicationAccessType, String> appAcls)
     throws IOException {
   DataOutputStream out = this.writer.prepareAppendKey(-1);
   APPLICATION_ACL_KEY.write(out);
   out.close();
   out = this.writer.prepareAppendValue(-1);
   for (Entry<ApplicationAccessType, String> entry : appAcls.entrySet()) {
     out.writeUTF(entry.getKey().toString());
     out.writeUTF(entry.getValue());
   }
   out.close();
 }
  @Override
  protected void populateObject(Object object) throws Exception {
    super.populateObject(object);
    Message info = (Message) object;

    info.setProducerId(createProducerId("ProducerId:1"));
    info.setDestination(createActiveMQDestination("Destination:2"));
    info.setTransactionId(createTransactionId("TransactionId:3"));
    info.setOriginalDestination(createActiveMQDestination("OriginalDestination:4"));
    info.setMessageId(createMessageId("MessageId:5"));
    info.setOriginalTransactionId(createTransactionId("OriginalTransactionId:6"));
    info.setGroupID("GroupID:7");
    info.setGroupSequence(1);
    info.setCorrelationId("CorrelationId:8");
    info.setPersistent(true);
    info.setExpiration(1);
    info.setPriority((byte) 1);
    info.setReplyTo(createActiveMQDestination("ReplyTo:9"));
    info.setTimestamp(2);
    info.setType("Type:10");
    {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      DataOutputStream dataOut = new DataOutputStream(baos);
      MarshallingSupport.writeUTF8(dataOut, "Content:11");
      dataOut.close();
      info.setContent(baos.toByteSequence());
    }
    {
      Map map = new HashMap();
      map.put("MarshalledProperties", 12);
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      DataOutputStream os = new DataOutputStream(baos);
      MarshallingSupport.marshalPrimitiveMap(map, os);
      os.close();
      info.setMarshalledProperties(baos.toByteSequence());
    }
    info.setDataStructure(createDataStructure("DataStructure:13"));
    info.setTargetConsumerId(createConsumerId("TargetConsumerId:14"));
    info.setCompressed(false);
    info.setRedeliveryCounter(2);
    {
      BrokerId value[] = new BrokerId[2];
      for (int i = 0; i < 2; i++) {
        value[i] = createBrokerId("BrokerPath:15");
      }
      info.setBrokerPath(value);
    }
    info.setArrival(3);
    info.setUserID("UserID:16");
    info.setRecievedByDFBridge(true);
    info.setDroppable(false);
  }
 public ActiveMQMessage convertFrame(StompProtocolConverter converter, StompFrame command)
     throws JMSException, ProtocolException {
   final Map<?, ?> headers = command.getHeaders();
   final ActiveMQMessage msg;
   /*
    * To reduce the complexity of this method perhaps a Chain of Responsibility
    * would be a better implementation
    */
   if (headers.containsKey(Stomp.Headers.AMQ_MESSAGE_TYPE)) {
     String intendedType = (String) headers.get(Stomp.Headers.AMQ_MESSAGE_TYPE);
     if (intendedType.equalsIgnoreCase("text")) {
       ActiveMQTextMessage text = new ActiveMQTextMessage();
       try {
         ByteArrayOutputStream bytes = new ByteArrayOutputStream(command.getContent().length + 4);
         DataOutputStream data = new DataOutputStream(bytes);
         data.writeInt(command.getContent().length);
         data.write(command.getContent());
         text.setContent(bytes.toByteSequence());
         data.close();
       } catch (Throwable e) {
         throw new ProtocolException("Text could not bet set: " + e, false, e);
       }
       msg = text;
     } else if (intendedType.equalsIgnoreCase("bytes")) {
       ActiveMQBytesMessage byteMessage = new ActiveMQBytesMessage();
       byteMessage.writeBytes(command.getContent());
       msg = byteMessage;
     } else {
       throw new ProtocolException("Unsupported message type '" + intendedType + "'", false);
     }
   } else if (headers.containsKey(Stomp.Headers.CONTENT_LENGTH)) {
     headers.remove(Stomp.Headers.CONTENT_LENGTH);
     ActiveMQBytesMessage bm = new ActiveMQBytesMessage();
     bm.writeBytes(command.getContent());
     msg = bm;
   } else {
     ActiveMQTextMessage text = new ActiveMQTextMessage();
     try {
       ByteArrayOutputStream bytes = new ByteArrayOutputStream(command.getContent().length + 4);
       DataOutputStream data = new DataOutputStream(bytes);
       data.writeInt(command.getContent().length);
       data.write(command.getContent());
       text.setContent(bytes.toByteSequence());
       data.close();
     } catch (Throwable e) {
       throw new ProtocolException("Text could not bet set: " + e, false, e);
     }
     msg = text;
   }
   Helper.copyStandardHeadersFromFrameToMessage(converter, command, msg, this);
   return msg;
 }
 /**
  * Collect all column values for the same Row. RowKey may be different if indexes are involved, so
  * it writes a separate record for each unique RowKey
  *
  * @param context Current mapper context
  * @param tableName Table index in tableNames list
  * @param lkv List of KV values that will be combined in a single ImmutableBytesWritable
  * @throws IOException
  * @throws InterruptedException
  */
 private void writeAggregatedRow(Context context, String tableName, List<KeyValue> lkv)
     throws IOException, InterruptedException {
   ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
   DataOutputStream outputStream = new DataOutputStream(bos);
   ImmutableBytesWritable outputKey = null;
   if (!lkv.isEmpty()) {
     for (KeyValue cell : lkv) {
       if (outputKey == null
           || Bytes.compareTo(
                   outputKey.get(),
                   outputKey.getOffset(),
                   outputKey.getLength(),
                   cell.getRowArray(),
                   cell.getRowOffset(),
                   cell.getRowLength())
               != 0) {
         // This a the first RowKey or a different from previous
         if (outputKey != null) { // It's a different RowKey, so we need to write it
           ImmutableBytesWritable aggregatedArray = new ImmutableBytesWritable(bos.toByteArray());
           outputStream.close();
           context.write(new TableRowkeyPair(tableName, outputKey), aggregatedArray);
         }
         outputKey =
             new ImmutableBytesWritable(
                 cell.getRowArray(), cell.getRowOffset(), cell.getRowLength());
         bos = new ByteArrayOutputStream(1024);
         outputStream = new DataOutputStream(bos);
       }
       /*
       The order of aggregation: type, index of column, length of value, value itself
        */
       int i = findIndex(cell);
       if (i == -1) {
         // That may happen when we load only local indexes. Since KV pairs for both
         // table and local index are going to the same physical table at that point
         // we skip those KVs that are not belongs to loca index
         continue;
       }
       outputStream.writeByte(cell.getTypeByte());
       WritableUtils.writeVInt(outputStream, i);
       WritableUtils.writeVInt(outputStream, cell.getValueLength());
       outputStream.write(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength());
     }
     ImmutableBytesWritable aggregatedArray = new ImmutableBytesWritable(bos.toByteArray());
     outputStream.close();
     context.write(new TableRowkeyPair(tableName, outputKey), aggregatedArray);
   }
 }
Ejemplo n.º 14
0
  public int a(String var1) {
    Short var2 = (Short) d.get(var1);
    if (var2 == null) {
      var2 = Short.valueOf((short) 0);
    } else {
      var2 = Short.valueOf((short) (var2.shortValue() + 1));
    }

    d.put(var1, var2);
    if (b == null) {
      return var2.shortValue();
    } else {
      try {
        File var3 = b.a("idcounts");
        if (var3 != null) {
          class_dn var4 = new class_dn();
          Iterator var5 = d.keySet().iterator();

          while (var5.hasNext()) {
            String var6 = (String) var5.next();
            short var7 = ((Short) d.get(var6)).shortValue();
            var4.a(var6, var7);
          }

          DataOutputStream var9 = new DataOutputStream(new FileOutputStream(var3));
          class_dx.a(var4, (DataOutput) var9);
          var9.close();
        }
      } catch (Exception var8) {
        var8.printStackTrace();
      }

      return var2.shortValue();
    }
  }
  /**
   * DO NOT call symbolTable.addReference in writeObject as this (may) result in a
   * concurrentModificationException.
   *
   * <p>All references should be created in the constructor
   */
  public void writeObject(DataOutput out) throws IOException {
    boolean sgIO = node instanceof com.sun.j3d.utils.scenegraph.io.SceneGraphIO;
    out.writeBoolean(sgIO);
    out.writeInt(symbol.nodeID);

    int nodeClassID = control.getNodeClassID(node);

    out.writeShort(nodeClassID);

    if (nodeClassID == -1) out.writeUTF(nodeClassName);

    writeConstructorParams(out);

    if (sgIO) {
      ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
      DataOutputStream tmpOut = new DataOutputStream(byteStream);
      ((com.sun.j3d.utils.scenegraph.io.SceneGraphIO) node).writeSceneGraphObject(tmpOut);
      tmpOut.close();
      out.writeInt(byteStream.size());
      out.write(byteStream.toByteArray());
    }

    writeUserData(out);
    writeString(node.getName(), out);

    writeCapabilities(out);
  }
Ejemplo n.º 16
0
  public void update(Observable source, Object object) {
    if (source instanceof Users) {
      if (!this.isDisabled()) {
        try {
          Operations.sendUserNamesList(users.getUserNames(), out);
        } catch (IOException io) {
          logger.error("IO Exception", io);
        }
      }
    }

    if (source instanceof Messages) {
      try {
        Operations.sendMessage((MessageType) object, out);
      } catch (IOException io) {
        if (out != null) {
          try {
            out.close();
          } catch (Exception ioe) {
            logger.error("Failed to close the output stream", ioe);
          }
        }

        logger.error("Impossible to send messages", io);
      }
    }
  }
Ejemplo n.º 17
0
 @Test
 public void dataRoundTrip() throws IOException {
   dos.writeUTF("Hello, world!");
   dos.writeInt(0xCAFEBABE);
   dos.writeUTF("Over & out.");
   dos.close();
   //    aos.close(); // important?
   byte[] bs = bos.toByteArray();
   if (verbose) {
     for (int i = 0; i < bs.length; i++) {
       System.out.printf("%02x ", bs[i]);
       if (i % 16 == 15) System.out.println();
     }
     System.out.println();
   }
   PPMModel pi = new PPMModel(4);
   ByteArrayInputStream bis = new ByteArrayInputStream(bs);
   ArithCodeInputStream ais = new ArithCodeInputStream(bis, pi);
   DataInputStream dis = new DataInputStream(ais);
   String s1 = dis.readUTF();
   assert s1.equals("Hello, world!") : s1;
   int i1 = dis.readInt();
   assert 0xCAFEBABE == i1 : i1;
   String s2 = dis.readUTF();
   assert s2.equals("Over & out.") : s2;
   int i2 = dis.read();
   assert -1 == i2 : i2;
 }
  public PacketSelectionUpdate(PlayerInfo info) {
    packet = new Packet250CustomPayload();

    ByteArrayOutputStream streambyte = new ByteArrayOutputStream();
    DataOutputStream stream = new DataOutputStream(streambyte);

    try {
      stream.write(packetID);

      if (info != null && info.getPoint1() != null) {
        Point p1 = info.getPoint1();
        stream.writeBoolean(true);
        stream.writeInt(p1.x);
        stream.writeInt(p1.y);
        stream.writeInt(p1.z);
      } else stream.writeBoolean(false);

      if (info != null && info.getPoint2() != null) {
        Point p2 = info.getPoint2();
        stream.writeBoolean(true);
        stream.writeInt(p2.x);
        stream.writeInt(p2.y);
        stream.writeInt(p2.z);
      } else stream.writeBoolean(false);

      stream.close();
      streambyte.close();

      packet.channel = FECHANNEL;
      packet.data = streambyte.toByteArray();
      packet.length = packet.data.length;
    } catch (Exception e) {
      OutputHandler.SOP("Error creating packet >> " + this.getClass());
    }
  }
Ejemplo n.º 19
0
  private void configBody(String params) throws IOException {
    try {
      byte[] postData = params.getBytes(ENCODING_UTF);
      int postDataLength = postData.length;
      connection.setDoOutput(true);
      connection.setRequestProperty("charset", ENCODING_UTF);
      connection.setRequestProperty("Content-Length", Integer.toString(postDataLength));
      connection.setUseCaches(false);
      wr = new DataOutputStream(connection.getOutputStream());
      wr.write(postData);
    } catch (IOException e) {
      if (e instanceof ConnectException)
        throw new IOException("Problemas ao tentar conectar com o servidor.");

      throw new IOException("Problemas ao processar dados para envio.");
    } finally {
      if (wr != null) {
        try {
          wr.flush();
          wr.close();
        } catch (IOException e) {
          L.output(e.getMessage());
        }
      }
    }
  }
    protected JSONObject doInBackground(String... params) {
      try {
        URL url = new URL(params[0]);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");

        JSONObject parameters = new JSONObject();
        parameters.put("hash", "274ffe280ad2956ea85f35986958095d");
        parameters.put("seed", "10");

        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());

        wr.writeBytes(parameters.toString());
        wr.flush();
        wr.close();

        BufferedReader r = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder result = new StringBuilder();
        String line;
        while ((line = r.readLine()) != null) {
          result.append(line);
        }

        JSONObject obj = new JSONObject(result.toString());
        return obj;
      } catch (Exception e) {
        this.exception = e;
        return null;
      }
    }
Ejemplo n.º 21
0
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    DataInputStream input = new DataInputStream(request.getInputStream());

    byte buff[];
    int leido = input.readByte();
    int tamano = leido;
    buff = new byte[tamano];
    leido = input.read(buff, 0, tamano);
    if (leido < tamano) {
      log.error("final inesperado");
      throw new IOException("Se leyo menos de los esperado");
    }
    input.close();
    String login = new String(buff);
    UsuarioDao dao = new UsuarioDao();
    BeanUsuario usuario = dao.getUsuarioByLogin(login);
    DataOutputStream output = new DataOutputStream(response.getOutputStream());
    if (usuario != null) {
      output.writeByte(1);
      usuario.write(output);
    } else {
      output.writeByte(0);
    }
    output.close();
  }
Ejemplo n.º 22
0
  public void run() {
    try {
      DataInputStream in = new DataInputStream(sockd.getInputStream());
      DataOutputStream out = new DataOutputStream(sockd.getOutputStream());

      BufferedReader br = new BufferedReader(new InputStreamReader(in));
      BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
      vdb.setBw(bw);

      String name;

      while ((name = br.readLine()) != null) {
        System.out.println("graph for " + name);
        vdb.buildGraph(name, max_depth, peers_only);
        vdb.convertGraph();
        System.out.println("graph for " + name + " is ready");
        break;
      }

      br.close();
      in.close();
      bw.close();
      out.close();

      sockd.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
  public ActionForward createClassifications(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws FenixFilterException, FenixServiceException, IOException {

    IUserView userView = UserView.getUser();

    DynaActionForm dynaActionForm = (DynaActionForm) form;
    Integer degreeCurricularPlanID = (Integer) dynaActionForm.get("degreeCurricularPlanID");
    Integer[] entryGradeLimits = (Integer[]) dynaActionForm.get("entryGradeLimits");
    Integer[] approvationRatioLimits = (Integer[]) dynaActionForm.get("approvationRatioLimits");
    Integer[] arithmeticMeanLimits = (Integer[]) dynaActionForm.get("arithmeticMeanLimits");

    Object[] args = {
      entryGradeLimits, approvationRatioLimits, arithmeticMeanLimits, degreeCurricularPlanID
    };
    ByteArrayOutputStream resultStream =
        (ByteArrayOutputStream)
            ServiceUtils.executeService("CreateClassificationsForStudents", args);

    String currentDate = new SimpleDateFormat("dd-MMM-yy.HH-mm").format(new Date());
    response.setHeader(
        "Content-disposition",
        "attachment;filename=" + degreeCurricularPlanID + "_" + currentDate + ".zip");
    response.setContentType("application/zip");
    DataOutputStream dos = new DataOutputStream(response.getOutputStream());
    dos.write(resultStream.toByteArray());
    dos.close();

    return null;
  }
  public String execSu(String cmd) {
    Log.d(TAG, "^ Executing as SU '" + cmd + "'");
    try {
      Process process = Runtime.getRuntime().exec("su");
      DataInputStream is = new DataInputStream(process.getInputStream());
      DataOutputStream os = new DataOutputStream(process.getOutputStream());
      os.writeBytes(cmd + "\n");
      os.writeBytes("exit\n");
      os.flush();
      os.close();

      BufferedReader reader = new BufferedReader(new InputStreamReader(is));

      try {
        String fullOutput = "";
        String line;
        while ((line = reader.readLine()) != null) {
          fullOutput = fullOutput + line + "\n";
        }
        return fullOutput;
      } catch (IOException e) { // It seems IOException is thrown when it reaches EOF.
        e.printStackTrace();
        Log.e(TAG, "^ execSU, IOException 1");
      }
      process.waitFor();

    } catch (IOException e) {
      e.printStackTrace();
      Log.e(TAG, "^ execSU, IOException 2");
    } catch (InterruptedException e) {
      e.printStackTrace();
      Log.e(TAG, "^ execSU, InterruptedException");
    }
    return "";
  }
Ejemplo n.º 25
0
  @Override
  public void close() {
    if (debug)
      OLogManager.instance()
          .info(
              this,
              "%s - Closing socket...",
              socket != null ? " null possible previous close" : socket.getRemoteSocketAddress());

    try {
      if (in != null) {
        in.close();
        // in = null;
      }
    } catch (IOException e) {
      OLogManager.instance().debug(this, "Error during closing of input stream", e);
    }

    try {
      if (out != null) {
        out.close();
        // out = null;
      }
    } catch (IOException e) {
      OLogManager.instance().debug(this, "Error during closing of output stream", e);
    }

    super.close();
  }
Ejemplo n.º 26
0
  public static void main(String[] args) {
    try {
      Socket s1 = new Socket("127.0.0.1", 57643);

      InputStream is = s1.getInputStream();
      DataInputStream dis = new DataInputStream(is);
      System.out.println(dis.readUTF());

      OutputStream os = s1.getOutputStream();
      DataOutputStream dos = new DataOutputStream(os);
      dos.writeUTF("Oh my gosh...");

      dis.close();
      is.close();
      dos.close();
      os.close();

      s1.close();
    } catch (ConnectException connExc) {
      connExc.printStackTrace();
      System.out.println("Server connection failed");
    } catch (IOException ioExc) {
      ioExc.printStackTrace();
    }
  }
Ejemplo n.º 27
0
 /** Closes open files. */
 private void close() throws IOException {
   sync();
   oos.close();
   fos.close();
   oos = null;
   fos = null;
 }
Ejemplo n.º 28
0
    public void run() {
      try {
        // 读取客户端数据
        DataInputStream input = new DataInputStream(socket.getInputStream());
        String clientInputStr = input.readUTF(); // 这里要注意和客户端输出流的写方法对应,否则会抛 EOFException
        // 处理客户端数据
        System.out.println("客户端发过来的内容:" + clientInputStr);

        // 向客户端回复信息
        DataOutputStream out = new DataOutputStream(socket.getOutputStream());
        System.out.print("请输入:\t");
        // 发送键盘输入的一行
        String s = new BufferedReader(new InputStreamReader(System.in)).readLine();
        out.writeUTF(s);

        out.close();
        input.close();
      } catch (Exception e) {
        System.out.println("服务器 run 异常: " + e.getMessage());
      } finally {
        if (socket != null) {
          try {
            socket.close();
          } catch (Exception e) {
            socket = null;
            System.out.println("服务端 finally 异常:" + e.getMessage());
          }
        }
      }
    }
Ejemplo n.º 29
0
 public synchronized List<Sample> getSamples() {
   if (samples == null) {
     samples = new ArrayList<Sample>();
     long lastEnd = 0;
     for (Line sub : subs) {
       long silentTime = sub.from - lastEnd;
       if (silentTime > 0) {
         samples.add(new SampleImpl(ByteBuffer.wrap(new byte[] {0, 0})));
       } else if (silentTime < 0) {
         throw new Error("Subtitle display times may not intersect");
       }
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       DataOutputStream dos = new DataOutputStream(baos);
       try {
         dos.writeShort(sub.text.getBytes("UTF-8").length);
         dos.write(sub.text.getBytes("UTF-8"));
         dos.close();
       } catch (IOException e) {
         throw new Error("VM is broken. Does not support UTF-8");
       }
       samples.add(new SampleImpl(ByteBuffer.wrap(baos.toByteArray())));
       lastEnd = sub.to;
     }
   }
   return samples;
 }
Ejemplo n.º 30
0
  private static TwitterAuthenticated getTwitterAuthentication(String base64Encoded)
      throws Exception {
    // Create a HTTP Post to twitter platform
    final HttpURLConnection conn = getHTTPUrlConnection(Constants.Twitter.URL_TOKEN);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("User-Agent", "Mozilla/5.0");
    conn.setRequestProperty("Authorization", "Basic " + base64Encoded);
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

    // Send post request
    conn.setDoOutput(true);
    final DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes("grant_type=client_credentials");
    wr.flush();
    wr.close();

    final int responseCode = conn.getResponseCode();
    // If success
    if (responseCode == 200) {
      // Read the response, and build the TwitterAuthenticated object
      final TwitterAuthenticated authenticated =
          new Gson()
              .fromJson(
                  new JsonReader(new InputStreamReader(conn.getInputStream(), "UTF-8")),
                  TwitterAuthenticated.class);
      return authenticated;
    }

    return null;
  }