Beispiel #1
0
  private void processResponse(RubyValue res) {
    if (res != null && res != RubyConstant.QNIL && res instanceof RubyHash) {
      RubyHash resHash = (RubyHash) res;
      RubyValue resBody = null;

      RubyArray arKeys = resHash.keys();
      RubyArray arValues = resHash.values();
      for (int i = 0; i < arKeys.size(); i++) {
        String strKey = arKeys.get(i).toString();
        if (strKey.equals("request-body")) resBody = arValues.get(i);
        else if (strKey.equals("status")) responseCode = arValues.get(i).toInt();
        else if (strKey.equals("message")) responseMsg = arValues.get(i).toString();
        else resHeaders.addProperty(strKey, arValues.get(i).toString());
      }
      String strBody = "";

      if (resBody != null && resBody != RubyConstant.QNIL)
        strBody = resBody.toRubyString().toString();

      if (!RHOCONF().getBool("log_skip_post")) LOG.TRACE(strBody);

      try {
        responseData = new ByteArrayInputStream(strBody.getBytes("UTF-8"));
      } catch (java.io.UnsupportedEncodingException exc) {
        LOG.ERROR("Error getting utf-8 body :", exc);
      }

      if (responseData != null)
        contentLength = Integer.parseInt(resHeaders.getPropertyIgnoreCase("Content-Length"));
    }
  }
Beispiel #2
0
  public void closeConnection() {
    if (m_connection != null) {
      try {
        m_connection.close();
      } catch (IOException exc) {
        LOG.ERROR("There was an error close connection", exc);
      }
    }

    m_connection = null;
  }
Beispiel #3
0
  public void processConnection(HttpConnection connection, Object e) {
    try {
      if (connection.getResponseCode() == HttpConnection.HTTP_NOT_MODIFIED) return;
    } catch (java.io.IOException exc) {
      LOG.ERROR("processConnection - getResponseCode failed.", exc);
    }

    synchronized (Application.getEventLock()) {
      createBrowserField();
      m_oBrowserField.displayContent(connection, (e != null ? (String) e : ""));
    }
  }
Beispiel #4
0
  void processMultipartItems(Vector /*Ptr<CMultipartItem*>&*/ arItems) throws Exception {
    for (int i = 0; i < (int) arItems.size(); i++) {
      MultipartItem oItem = (MultipartItem) arItems.elementAt(i);

      if (oItem.m_strName.length() == 0) oItem.m_strName = "blob";

      if (oItem.m_strFileName.length() == 0) {
        if (oItem.m_strFilePath.length() > 0) {
          FilePath oPath = new FilePath(oItem.m_strFilePath);
          oItem.m_strFileName = oPath.getBaseName();
        }
        // else
        //    oItem.m_strFileName = "doesnotmatter.txt";
      }

      oItem.m_strDataPrefix = i > 0 ? "\r\n" : "";
      oItem.m_strDataPrefix +=
          "------------A6174410D6AD474183FDE48F5662FCC5\r\n"
              + "Content-Disposition: form-data; name=\"";
      oItem.m_strDataPrefix += oItem.m_strName + "\"";
      if (oItem.m_strFileName.length() > 0)
        oItem.m_strDataPrefix += "; filename=\"" + oItem.m_strFileName + "\"";
      oItem.m_strDataPrefix += "\r\n";
      if (oItem.m_strContentType != null && oItem.m_strContentType.length() > 0)
        oItem.m_strDataPrefix += "Content-Type: " + oItem.m_strContentType + "\r\n";

      long nContentSize = 0;
      if (oItem.m_strFilePath.length() > 0) {
        SimpleFile file = null;
        try {
          file = RhoClassFactory.createFile();
          file.open(oItem.m_strFilePath, true, true);
          nContentSize = file.length();
          if (!file.isOpened()) {
            LOG.ERROR("File not found: " + oItem.m_strFilePath);
            throw new RuntimeException("File not found:" + oItem.m_strFilePath);
          }
        } finally {
          if (file != null)
            try {
              file.close();
            } catch (IOException e) {
            }
        }
      } else nContentSize = oItem.m_strBody.length();

      if (oItem.m_strContentType != null && oItem.m_strContentType.length() > 0)
        oItem.m_strDataPrefix += "Content-Length: " + nContentSize + "\r\n";

      oItem.m_strDataPrefix += "\r\n";
    }
  }
Beispiel #5
0
  void showGeoLocation() {
    String location = "";
    try {
      IRhoRubyHelper helper = RhoClassFactory.createRhoRubyHelper();
      location = helper.getGeoLocationText();
    } catch (Exception exc) {
      LOG.ERROR("getGeoLocationText failed", exc);
    }
    respondOK();

    contentLength = location.length();
    responseData = new ByteArrayInputStream(location.getBytes());
    resHeaders.addProperty("Content-Type", "text/html");
    resHeaders.addProperty("Content-Length", Integer.toString(contentLength));
  }
Beispiel #6
0
  void callLoginCallback(SyncNotification oNotify, int nErrCode, String strMessage) {
    try {
      if (getSync().isStoppedByUser()) return;

      String strBody = "error_code=" + nErrCode;
      strBody += "&error_message=" + URI.urlEncode(strMessage != null ? strMessage : "");
      strBody += "&rho_callback=1";

      LOG.INFO("Login callback: " + oNotify.toString() + ". Body: " + strBody);

      callNotify(oNotify, strBody);
    } catch (Exception exc) {
      LOG.ERROR("Call Login callback failed.", exc);
    }
  }
Beispiel #7
0
  public NetResponse pullFile(
      String strUrl, String strFileName, IRhoSession oSession, Hashtable headers) throws Exception {
    IRAFile file = null;
    NetResponse resp = null;

    m_nMaxPacketSize = RhoClassFactory.getNetworkAccess().getMaxPacketSize();
    m_bFlushFileAfterWrite = RhoConf.getInstance().getBool("use_persistent_storage");
    m_bCancel = false;

    try {

      if (!strFileName.startsWith("file:")) {
        try {
          strFileName = FilePath.join(RhoClassFactory.createFile().getDirPath(""), strFileName);
        } catch (IOException x) {
          LOG.ERROR("getDirPath failed.", x);
          throw x;
        }
      }

      file = RhoClassFactory.createFSRAFile();
      file.open(strFileName, "rw");
      file.seek(file.size());

      do {
        resp = pullFile1(strUrl, file, file.size(), oSession, headers);
      } while (!m_bCancel
          && (resp == null || resp.isOK())
          && m_nCurDownloadSize > 0
          && m_nMaxPacketSize > 0);

    } finally {
      if (file != null) {
        file.close();
        file = null;
      }
    }

    copyHashtable(m_OutHeaders, headers);

    return resp != null && !m_bCancel
        ? resp
        : makeResponse("", IHttpConnection.HTTP_INTERNAL_ERROR);
  }
Beispiel #8
0
  public void resetUrl(String url) {
    url_external = url;
    uri = new URI(url_external);

    if (!uri.getPath().startsWith("/apps")) uri.setPath("/apps" + uri.getPath());
    else uri.setPath(uri.getPath());

    method = "";
    responseCode = 200;
    responseMsg = "OK";
    contentLength = -1;
    reqHeaders.clear();
    resHeaders.clear();
    requestProcessed = false;

    try {
      clean();
    } catch (IOException exc) {
      LOG.ERROR("clean failed.", exc);
    }
  }
Beispiel #9
0
  public int getLastPollInterval() {
    try {
      long nowTime = (TimeInterval.getCurrentTime().toULong()) / 1000;
      long latestTimeUpdated = 0;

      Vector /*<String>*/ arPartNames = DBAdapter.getDBAllPartitionNames();
      for (int i = 0; i < (int) arPartNames.size(); i++) {
        DBAdapter dbPart = DBAdapter.getDB((String) arPartNames.elementAt(i));
        IDBResult res = dbPart.executeSQL("SELECT last_updated from sources");
        for (; !res.isEnd(); res.next()) {
          long timeUpdated = res.getLongByIdx(0);
          if (latestTimeUpdated < timeUpdated) latestTimeUpdated = timeUpdated;
        }
      }

      return latestTimeUpdated > 0 ? (int) (nowTime - latestTimeUpdated) : 0;
    } catch (Exception exc) {
      LOG.ERROR("isStartSyncNow failed.", exc);
    }
    return 0;
  }
Beispiel #10
0
  boolean callNotify(SyncNotification oNotify, String strBody) throws Exception {
    if (getSync().isNoThreadedMode()) {
      m_strNotifyBody = strBody;
      return false;
    }

    if (oNotify.m_strUrl.length() == 0) return true;

    NetResponse resp = getNet().pushData(oNotify.m_strUrl, strBody, null);
    if (!resp.isOK())
      LOG.ERROR(
          "Fire object notification failed. Code: "
              + resp.getRespCode()
              + "; Error body: "
              + resp.getCharData());
    else {
      String szData = resp.getCharData();
      return szData != null && szData.equals("stop");
    }

    return false;
  }
Beispiel #11
0
  void doFireSyncNotification(
      SyncSource src,
      boolean bFinish,
      int nErrCode,
      String strError,
      String strParams,
      String strServerError) {
    if (getSync().isStoppedByUser()) return;

    try {
      SyncNotification pSN = null;

      String strBody = "";
      boolean bRemoveAfterFire = bFinish;
      {
        synchronized (m_mxSyncNotifications) {
          pSN = getSyncNotifyBySrc(src);
          if (pSN == null) return;

          strBody = "";

          if (src != null) {
            strBody += "total_count=" + src.getTotalCount();
            strBody += "&processed_count=" + src.getCurPageCount();
            strBody += "&processed_objects_count=" + getLastSyncObjectCount(src.getID());
            strBody += "&cumulative_count=" + src.getServerObjectsCount();
            strBody += "&source_id=" + src.getID();
            strBody += "&source_name=" + src.getName();
          }

          if (strParams.length() > 0) strBody += (strBody.length() > 0 ? "&" : "") + strParams;
          else strBody += (strBody.length() > 0 ? "&" : "") + "sync_type=incremental";

          strBody += "&status=";
          if (bFinish) {
            if (nErrCode == RhoAppAdapter.ERR_NONE) {
              if (getSync().isSchemaChanged()) strBody += "schema_changed";
              else strBody += (src == null && strParams.length() == 0) ? "complete" : "ok";
            } else {
              if (getSync().isStoppedByUser()) nErrCode = RhoAppAdapter.ERR_CANCELBYUSER;

              strBody += "error";
              strBody += "&error_code=" + nErrCode;

              if (strError != null && strError.length() > 0)
                strBody += "&error_message=" + URI.urlEncode(strError);
              else if (src != null) strBody += "&error_message=" + URI.urlEncode(src.m_strError);

              if (strServerError != null && strServerError.length() > 0)
                strBody += "&" + strServerError;
              else if (src != null
                  && src.m_strServerError != null
                  && src.m_strServerError.length() > 0) strBody += "&" + src.m_strServerError;
            }

            if (src != null) strBody += makeCreateObjectErrorBody(src.getID());
          } else strBody += "in_progress";

          strBody += "&rho_callback=1";
          if (pSN.m_strParams != null && pSN.m_strParams.length() > 0) {
            if (!pSN.m_strParams.startsWith("&")) strBody += "&";

            strBody += pSN.m_strParams;
          }

          bRemoveAfterFire = bRemoveAfterFire && pSN.m_bRemoveAfterFire;
        }
      }
      if (bRemoveAfterFire) clearNotification(src);

      LOG.INFO(
          "Fire notification. Source : "
              + (src != null ? (src).getName() : "")
              + "; "
              + pSN.toString());

      if (callNotify(pSN, strBody)) clearNotification(src);
    } catch (Exception exc) {
      LOG.ERROR("Fire notification failed.", exc);
    }
  }
Beispiel #12
0
 public static void rhoLogError(String msg) {
   LOG.ERROR(msg);
 }
Beispiel #13
0
  NetResponse pullFile1(
      String strUrl, IRAFile file, long nStartPos, IRhoSession oSession, Hashtable headers)
      throws Exception {
    String strRespBody = null;
    InputStream is = null;
    int code = -1;

    try {
      closeConnection();
      m_connection = RhoClassFactory.getNetworkAccess().connect(strUrl, true);

      if (oSession != null) {
        String strSession = oSession.getSession();
        if (strSession != null && strSession.length() > 0)
          m_connection.setRequestProperty("Cookie", strSession);
      }

      m_connection.setRequestProperty("Connection", "keep-alive");

      if (nStartPos > 0 || m_nMaxPacketSize > 0) {
        if (m_nMaxPacketSize > 0)
          m_connection.setRequestProperty(
              "Range", "bytes=" + nStartPos + "-" + (nStartPos + m_nMaxPacketSize - 1));
        else m_connection.setRequestProperty("Range", "bytes=" + nStartPos + "-");
      }
      writeHeaders(headers);

      m_connection.setRequestMethod(IHttpConnection.GET);

      code = m_connection.getResponseCode();

      LOG.INFO("getResponseCode : " + code);

      m_nCurDownloadSize = 0;
      readHeaders(headers);

      if (code == IHttpConnection.HTTP_RANGENOTSATISFY) code = IHttpConnection.HTTP_PARTIAL_CONTENT;
      else {
        if (code != IHttpConnection.HTTP_OK && code != IHttpConnection.HTTP_PARTIAL_CONTENT) {
          LOG.ERROR("Error retrieving data: " + code);
          if (code == IHttpConnection.HTTP_UNAUTHORIZED) oSession.logout();

          if (code != IHttpConnection.HTTP_INTERNAL_ERROR) {
            is = m_connection.openInputStream();
            strRespBody = readFully(is, getResponseEncoding());
          }
        } else {
          int nRead = 0;

          is = m_connection.openInputStream();
          byte[] byteBuffer = new byte[1024 * 20];

          do {
            nRead = /*bufferedReadByByte(m_byteBuffer, is);*/ is.read(byteBuffer);
            if (nRead > 0) {
              file.write(byteBuffer, 0, nRead);

              if (m_bFlushFileAfterWrite) file.sync();

              m_nCurDownloadSize += nRead;
            }
          } while (!m_bCancel && nRead >= 0);

          if (code == IHttpConnection.HTTP_OK
              || (code == IHttpConnection.HTTP_PARTIAL_CONTENT && isFinishDownload()))
            m_nCurDownloadSize = 0;
        }
      }
    } finally {
      if (is != null)
        try {
          is.close();
        } catch (IOException exc) {
        }

      closeConnection();
    }

    return makeResponse(strRespBody != null ? strRespBody : "", code);
  }
Beispiel #14
0
  public NetResponse pushMultipartData(
      String strUrl,
      Vector /*Ptr<CMultipartItem*>&*/ arItems,
      IRhoSession oSession,
      Hashtable /*<String,String>**/ headers)
      throws Exception {
    String strRespBody = null;
    InputStream is = null;
    OutputStream os = null;
    int code = -1;

    m_bCancel = false;

    try {
      closeConnection();
      m_connection = RhoClassFactory.getNetworkAccess().connect(strUrl, false);

      if (oSession != null) {
        String strSession = oSession.getSession();
        if (strSession != null && strSession.length() > 0)
          m_connection.setRequestProperty("Cookie", strSession);
      }

      m_connection.setRequestProperty("Connection", "keep-alive");
      m_connection.setRequestProperty("content-type", szMultipartContType);
      writeHeaders(headers);
      m_connection.setRequestMethod(IHttpConnection.POST);

      // PUSH specific
      processMultipartItems(arItems);
      os = m_connection.openOutputStream();
      // write all items
      for (int i = 0; i < (int) arItems.size(); i++) {
        MultipartItem oItem = (MultipartItem) arItems.elementAt(i);
        os.write(oItem.m_strDataPrefix.getBytes(), 0, oItem.m_strDataPrefix.length());

        if (oItem.m_strFilePath.length() > 0) {

          SimpleFile file = null;
          InputStream fis = null;

          try {
            file = RhoClassFactory.createFile();
            file.open(oItem.m_strFilePath, true, true);

            if (!file.isOpened()) {
              LOG.ERROR("File not found: " + oItem.m_strFilePath);
              throw new RuntimeException("File not found:" + oItem.m_strFilePath);
            }

            fis = file.getInputStream();
            byte[] byteBuffer = new byte[1024 * 4];
            int nRead = 0;
            do {
              nRead = fis.read(byteBuffer);
              if (nRead > 0) os.write(byteBuffer, 0, nRead);
            } while (nRead > 0);
          } finally {
            if (fis != null)
              try {
                fis.close();
              } catch (IOException e) {
              }

            if (file != null)
              try {
                file.close();
              } catch (IOException e) {
              }
          }

        } else {
          os.write(oItem.m_strBody.getBytes(), 0, oItem.m_strBody.length());
        }
      }
      os.write(szMultipartPostfix.getBytes(), 0, szMultipartPostfix.length());
      // os.flush();
      // PUSH specific

      is = m_connection.openInputStream();
      code = m_connection.getResponseCode();

      LOG.INFO("getResponseCode : " + code);

      readHeaders(headers);
      copyHashtable(m_OutHeaders, headers);

      if (code != IHttpConnection.HTTP_OK) {
        LOG.ERROR("Error retrieving data: " + code);
        if (code == IHttpConnection.HTTP_UNAUTHORIZED) oSession.logout();

        if (code != IHttpConnection.HTTP_INTERNAL_ERROR)
          strRespBody = readFully(is, getResponseEncoding());

      } else {
        long len = m_connection.getLength();
        LOG.INFO("fetchRemoteData data size:" + len);

        strRespBody = readFully(is, getResponseEncoding());

        LOG.INFO("fetchRemoteData data readFully.");
      }

    } finally {
      try {
        if (is != null) is.close();
        if (os != null) os.close();

        closeConnection();

      } catch (IOException exc2) {
      }
    }

    return makeResponse(strRespBody, code);
  }
Beispiel #15
0
  public NetResponse doRequest(
      String strMethod, String strUrl, String strBody, IRhoSession oSession, Hashtable headers)
      throws Exception {
    String strRespBody = null;
    InputStream is = null;
    OutputStream os = null;
    int code = -1;

    m_bCancel = false;
    try {
      closeConnection();
      m_connection = RhoClassFactory.getNetworkAccess().connect(strUrl, m_bIgnoreSuffixOnSim);
      LOG.INFO("connection done");

      if (oSession != null) {
        String strSession = oSession.getSession();
        LOG.INFO("Cookie : " + (strSession != null ? strSession : ""));
        if (strSession != null && strSession.length() > 0)
          m_connection.setRequestProperty("Cookie", strSession);
      }

      // m_connection.setRequestProperty("Connection", "keep-alive");
      // m_connection.setRequestProperty("Accept",
      // "application/x-www-form-urlencoded,application/json,text/html");

      if (strBody != null && strBody.length() > 0) {
        if (oSession != null)
          m_connection.setRequestProperty("Content-Type", oSession.getContentType());
        else m_connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        writeHeaders(headers);
        LOG.INFO("writeHeaders done");
        m_connection.setRequestMethod(IHttpConnection.POST);

        os = m_connection.openOutputStream();
        os.write(strBody.getBytes(), 0, strBody.length());
        LOG.INFO("write body done");
      } else {
        writeHeaders(headers);
        m_connection.setRequestMethod(strMethod);
      }

      code = m_connection.getResponseCode();
      LOG.INFO("getResponseCode : " + code);

      is = m_connection.openInputStream();
      LOG.INFO("openInputStream done");

      readHeaders(headers);
      copyHashtable(m_OutHeaders, headers);

      if (code != IHttpConnection.HTTP_OK) {
        LOG.ERROR("Error retrieving data: " + code);
        if (code == IHttpConnection.HTTP_UNAUTHORIZED && oSession != null) oSession.logout();

        // if ( code != IHttpConnection.HTTP_INTERNAL_ERROR )
        {
          strRespBody = readFully(is, getResponseEncoding());

          if (code == IHttpConnection.HTTP_MOVED_TEMPORARILY
              || code == IHttpConnection.HTTP_MOVED_PERMANENTLY)
            LOG.INFO("Response body: " + strRespBody);
          else LOG.TRACE("Response body: " + strRespBody);
        }
      } else {
        long len = m_connection.getLength();
        LOG.INFO("fetchRemoteData data size:" + len);

        strRespBody = readFully(is, getResponseEncoding());

        LOG.INFO("fetchRemoteData data readFully.");
      }

    } finally {
      if (is != null)
        try {
          is.close();
        } catch (IOException exc) {
        }
      if (os != null)
        try {
          os.close();
        } catch (IOException exc) {
        }

      closeConnection();

      m_bIgnoreSuffixOnSim = true;
    }

    return makeResponse(strRespBody, code);
  }