public static String postStream2(String url, String data) {
   InputStream is = null;
   String flag = "";
   try {
     DefaultHttpClient httpClient = new DefaultHttpClient();
     HttpPost httpPost = new HttpPost(url);
     httpPost.setEntity(new StringEntity(data));
     httpPost.setHeader("Accept", "application/json");
     httpPost.setHeader("Content-type", "application/json");
     HttpResponse httpResponse = httpClient.execute(httpPost);
     Log.i("Httpresponse:", httpResponse.toString());
     Log.i("Http Response:", String.valueOf(httpResponse.getStatusLine().getStatusCode()));
     if (String.valueOf(httpResponse.getStatusLine().getStatusCode()).trim().equals("404")) {
       flag = "false";
     } else {
       flag = "true";
     }
     HttpEntity httpEntity = httpResponse.getEntity();
     is = httpEntity.getContent();
   } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
     Log.e("JSON post error:", e.toString());
   } catch (ClientProtocolException e) {
     e.printStackTrace();
     Log.e("JSON post error:", e.toString());
   } catch (IOException e) {
     e.printStackTrace();
     Log.e("JSON post error:", e.toString());
   }
   Log.e("is:", is.toString());
   return flag;
 }
 public static String postStream(String url, String data) {
   InputStream is = null;
   try {
     DefaultHttpClient httpClient = new DefaultHttpClient();
     HttpPost httpPost = new HttpPost(url);
     httpPost.setEntity(new StringEntity(data));
     httpPost.setHeader("Accept", "application/json");
     httpPost.setHeader("Content-type", "application/json");
     HttpResponse httpResponse = httpClient.execute(httpPost);
     Log.i("Httpresponse:", httpResponse.toString());
     HttpEntity httpEntity = httpResponse.getEntity();
     is = httpEntity.getContent();
   } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
     Log.e("JSON post error:", e.toString());
   } catch (ClientProtocolException e) {
     e.printStackTrace();
     Log.e("JSON post error:", e.toString());
   } catch (IOException e) {
     e.printStackTrace();
     Log.e("JSON post error:", e.toString());
   }
   Log.e("is:", is.toString());
   return readStream(is);
 }
    @Override
    protected DatosUsuario doInBackground(Void... voids) {

      DatosUsuario du = new DatosUsuario();
      SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
      String username = settings.getString("username", "");
      String password = settings.getString("password", "");

      Euri euri = new Euri(username, password);
      String imageUrl = "http://www.eurielec.etsit.upm.es/images/miembro.php?m=" + username;
      URL url;
      try {
        url = new URL(imageUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        InputStream is = connection.getInputStream();
        Log.d("image", is.toString());
        Bitmap img = BitmapFactory.decodeStream(is);
        du.setFoto(img);
        PictUtil.saveToCacheFile(img);

      } catch (Exception e) {
        e.printStackTrace();
      }

      du.setDatos(euri.get("userinfo"));
      du.setDeuda(euri.get("deuda"));

      return du;
    }
 public String toString() {
   StringBuilder sb = new StringBuilder();
   sb.append(super.toString());
   sb.append(", orig: ");
   if (originalInputKeptSolelyForDebugging == null) sb.append("null");
   else sb.append(originalInputKeptSolelyForDebugging.toString());
   return sb.toString();
 }
Exemple #5
1
  /**
   * Create a new sound on request to load
   *
   * @param ref The location of the sound to load
   * @param type The type of sound to load
   * @param in The input stream to load from
   */
  public DeferredSound(String ref, InputStream in, int type) {
    this.ref = ref;
    this.type = type;

    if (ref.equals(in.toString()))
      this.in = in; // nasty hack to detect when we're loading from a stream

    LoadingList.get().add(this);
  }
 // Essentially links an InputStream to the proper channels in the log box.
 private static void printOutput(InputStream in, SimpleAttributeSet set) {
   int i = 0;
   String s = "";
   try {
     while ((i = in.read()) != -1) {
       s += (char) i;
       // print(, set);
     }
   } catch (IOException io) {
     println("Error: IOException when reading InputStream " + in.toString(), progErr);
   }
   println(s);
 }
 @Override
 protected String doInBackground(Void... voids) {
   try {
     URL url = new URL(SERVER_ADDRESS);
     InputStream is = url.openStream();
     Log.d(TAG, "HttpUrlConnection : " + is.toString());
     String result = CharStreams.toString(new InputStreamReader(is));
     return result;
   } catch (Exception e) {
     Log.e(TAG, "Error : " + e.getMessage());
     e.printStackTrace();
   }
   return null;
 }
Exemple #8
1
  /**
   * @param filename the
   * @param is
   * @return
   */
  AudioInputStream getAudioInputStream(String filename) {
    AudioInputStream ais = null;
    BufferedInputStream bis = null;
    if (filename.startsWith("http")) {
      try {
        ais = getAudioInputStream(new URL(filename));
      } catch (MalformedURLException e) {
        error("Bad URL: " + e.getMessage());
      } catch (UnsupportedAudioFileException e) {
        error("URL is in an unsupported audio file format: " + e.getMessage());
      } catch (IOException e) {
        Sound.error("Error reading the URL: " + e.getMessage());
      }
    } else {
      try {
        // InputStream is = createInput(filename);
        InputStream is =
            new FileInputStream(filename) {

              @Override
              public int read() throws IOException {
                // TODO Auto-generated method stub
                return 0;
              }
            };

        debug("Base input stream is: " + is.toString());
        bis = new BufferedInputStream(is);
        ais = getAudioInputStream(bis);
        // don't mark it like this because it means the entire
        // file will be loaded into memory as it plays. this
        // will cause out-of-memory problems with very large files.
        // ais.mark((int)ais.available());
        debug(
            "Acquired AudioInputStream.\n"
                + "It is "
                + ais.getFrameLength()
                + " frames long.\n"
                + "Marking support: "
                + ais.markSupported());
      } catch (IOException ioe) {
        error("IOException: " + ioe.getMessage());
      } catch (UnsupportedAudioFileException uafe) {
        error("Unsupported Audio File: " + uafe.getMessage());
      }
    }
    return ais;
  }
Exemple #9
1
  /** This method is a hack. I really want another constructor. */
  public static Obj3d parseFile(InputStream is, ModelViewer modelViewer, boolean register)
      throws IOException, FileFormatException {

    StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(is)));
    st.eolIsSignificant(true);
    st.commentChar('#');

    Obj3d obj3d = new Obj3d(st, modelViewer, register);

    // should be at end of file
    is.close();
    if (st.ttype != StreamTokenizer.TT_EOF) {
      throw new FileFormatException(is.toString());
    }
    return obj3d;
  }
Exemple #10
1
 /**
  * Parse the XML document coming from the specified input stream, using the specified system ID as
  * a reference URI.
  *
  * @param ios The XML document input stream.
  * @param systemID The system ID is the base for resolving relative URIs.
  * @return The DOM Document.
  */
 public Document parse(InputStream ios, String systemID) {
   Document doc = null;
   try {
     m_messages = new ArrayList<String>();
     m_errors = false;
     if (systemID == null) {
       doc = m_parser.parse(ios);
     } else {
       doc = m_parser.parse(ios, systemID);
     }
     if (m_errors) {
       doc = null; // the errors are in the m_messages
     }
   } catch (Exception ex) {
     throw new MdmiException(ex, "Unexpected exception while parsing " + ios.toString());
   }
   return doc;
 }
  public DBaseFile(InputStream is) {
    if (is == null) {
      String message = Logging.getMessage("nullValue.InputStreamIsNull");
      Logging.logger().severe(message);
      throw new IllegalArgumentException(message);
    }

    this.file = null;
    try {
      this.header = this.readHeaderFromStream(is);
      this.fields = this.readFieldsFromBuffer(this.header.fieldsHeaderBuffer);
      this.records = this.readRecordsFromStream(is);
    } catch (Exception e) {
      String message = Logging.getMessage("generic.ExceptionAttemptingToReadFrom", is.toString());
      Logging.logger().log(java.util.logging.Level.SEVERE, message, e);
      throw new WWRuntimeException(message, e);
    }
  }
Exemple #12
1
  /**
   * The doPost method of the servlet. <br>
   * This method is called when a form has its tag value method equals to post.
   *
   * @param request the request send by the client to the server
   * @param response the response send by the server to the client
   * @throws ServletException if an error occurred
   * @throws IOException if an error occurred
   */
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/xml;charset=UTF-8");
    request.setCharacterEncoding("UTF-8");
    System.out.println("doPost");
    PrintWriter out = response.getWriter();
    String signature =
        request.getParameter("signature") == null ? "" : request.getParameter("signature");
    String timestamp =
        request.getParameter("timestamp") == null ? "" : request.getParameter("timestamp");
    String nonce = request.getParameter("nonce") == null ? "" : request.getParameter("nonce");
    String url = request.getQueryString();
    TestData.url = url;
    TestData.signature = signature;
    TestData.timestamp = timestamp;
    TestData.nonce = nonce;

    String tipStr = request.getParameter("tip");
    System.out.println("tipStr:");
    System.out.println(tipStr);
    if ("loading...".equals(tipStr)) {
      System.out.println("createMenu()");
      MenuManager menuManager = new MenuManager();
      menuManager.createMenu();
    }
    // diy code here
    Authen au = new Authen(signature, timestamp, nonce);
    boolean fromWX = au.checkSignature();
    if (fromWX) {
      InputStream xmlData = request.getInputStream();
      TestData.step = xmlData.toString();
      // TestData.step = "msgHandler前";
      MsgHandler msg = new MsgHandler(xmlData);
      // TestData.step = "msgHandler";
      // saveAsFileWriter(msg.getResult());
      out.print(msg.getResult());
    } else {
      out.println("");
    }
    // end here
    out.flush();
    out.close();
  }
Exemple #13
1
    @Override
    public void run() {
      // TODO Auto-generated method stub
      int l4port = 5757;
      try {
        ServerSocket ServerSocket = new ServerSocket(l4port);
        Socket socket = null;
        do {
          socket = ServerSocket.accept();
          InetAddress remoteIP = socket.getInetAddress();
          InputStream is = socket.getInputStream();
          Log.v("Deamon", remoteIP.toString());
          Log.v("Deamon", is.toString());
        } while (socket != null);

      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
Exemple #14
1
  // Loads configuration file and
  // sets configuration to properties
  private static Properties loadProperties() throws IOException {
    // get location where program is run
    URL url = Stomp.class.getProtectionDomain().getCodeSource().getLocation();

    String path = url.getPath();

    if (path.contains("jar")) {
      // remove filename to get directory
      path = path.substring(0, path.lastIndexOf("/"));
    }
    // when running from eclipse
    else {
      path = ".";
    }

    path += CONF_PATH;

    // Load logger settings from conf path
    InputStream logPropFile = Stomp.class.getResourceAsStream("/logger.properties");

    System.out.println("logprop " + logPropFile.toString());

    LogManager.getLogManager().readConfiguration(logPropFile);

    path += CONF_FILE;

    Properties properties = new Properties();

    try {
      File propertiesFile = new File(path);
      path = propertiesFile.getAbsolutePath();
      properties.load(new FileInputStream(propertiesFile));
    } catch (IOException ioe) {
      log.severe("Failed to read configuration file " + path);
      throw ioe;
    }
    return properties;
  }
Exemple #15
1
 public String toString() {
   return delegate.toString();
 }
 protected String getReaderURI() {
   if (inputURI != null) return inputURI;
   if (filename != null) return filename.toURI().toString();
   return schemaIn.toString();
 }
 @Override
 public String toString() {
   return String.format(
       "PeekableInputStream(in=%s, peeked=%b, peekedByte=%d)",
       mIn.toString(), mPeeked, mPeekedByte);
 }
  /**
   * 下载服务器文件
   *
   * @param serverUrl 服务器地址
   * @param localUrl 本地存储地址
   * @return
   */
  public static boolean downloadFile(
      String serverUrl, String localUrl, Handler mHandler, AttachListHolder mholder) {
    InputStream input = null;
    OutputStream output = null;
    HttpURLConnection conn = null;
    try {

      File file = new File(localUrl);
      if (file.exists()) {
        Log.i(tag = "AttachListAdapter", localUrl + "is exist");
        return true;
      } else {

        // httpGet连接对象
        HttpGet httpRequest = new HttpGet(serverUrl);
        // 取得HttpClient 对象
        HttpClient httpclient = new DefaultHttpClient();
        // 请求httpClient ,取得HttpRestponse
        HttpResponse httpResponse = httpclient.execute(httpRequest);
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
          // 取得相关信息 取得HttpEntiy
          HttpEntity httpEntity = httpResponse.getEntity();
          // 获得一个输入流
          input = httpEntity.getContent();
          int fileSize = 0;
          if (input != null) {
            fileSize = input.toString().length();
          }

          String dir = localUrl.substring(0, localUrl.lastIndexOf("/") + 1);
          new File(dir).mkdirs(); // 新建文件夹
          file.createNewFile(); // 新建文件
          output = new FileOutputStream(file);
          byte[] buffer = new byte[1024];
          int len = 0;
          int lentemp = 0;
          while ((len = input.read(buffer)) != -1) {
            output.write(buffer, 0, len);
            if (mHandler != null) {
              Message msg = new Message();
              msg.what = 2014;
              msg.obj = mholder;
              lentemp = lentemp + len;
              msg.arg1 = (lentemp * 100) / fileSize;
              mHandler.sendMessage(msg);
            }
          }
          if (mHandler != null) {
            Message msg = new Message();
            msg.what = 2014;
            msg.obj = mholder;
            msg.arg1 = 100;
            mHandler.sendMessage(msg);
          }

          // 读取大文件
          // byte[] buffer = new byte[4 * 1024];
          // while (input.read(buffer) != -1) {
          // output.write(buffer);
          // }
          output.flush();
        }

        // URL url = new URL(serverUrl);
        // conn = (HttpURLConnection) url
        // .openConnection();
        // input = conn.getInputStream();

      }
      Log.i(tag, localUrl + "download success");
    } catch (Exception e) {
      e.printStackTrace();
      Log.i(tag, localUrl + "download fail");
      return false;
    } finally {
      if (input != null) {
        try {
          input.close();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
      try {
        if (output != null) output.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
      if (conn != null) {
        conn.disconnect();
      }
    }
    return true;
  }
 @Override
 public String toString() {
   return inputStream.toString();
 }
Exemple #20
1
 /**
  * Get the Sound based on a specified OGG file
  *
  * @param in The stream to the OGG to load
  * @return The Sound read from the OGG file
  * @throws IOException Indicates a failure to load the OGG
  */
 public Audio getOgg(InputStream in) throws IOException {
   return getOgg(in.toString(), in);
 }