@Override
  protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result = null;

    /// download will be performed to a temporal file, then moved to the final location
    File tmpFile = new File(getTmpPath());

    /// perform the download
    try {
      tmpFile.getParentFile().mkdirs();
      int status = downloadFile(client, tmpFile);
      result =
          new RemoteOperationResult(
              isSuccess(status), status, (mGet != null ? mGet.getResponseHeaders() : null));
      Log_OC.i(
          TAG,
          "Download of " + mRemotePath + " to " + getTmpPath() + ": " + result.getLogMessage());

    } catch (Exception e) {
      result = new RemoteOperationResult(e);
      Log_OC.e(
          TAG,
          "Download of " + mRemotePath + " to " + getTmpPath() + ": " + result.getLogMessage(),
          e);
    }

    return result;
  }
  private boolean tryConnection(WebdavClient wc, String urlSt) {
    boolean retval = false;
    GetMethod get = null;
    try {
      get = new GetMethod(urlSt);
      int status = wc.executeMethod(get, TRY_CONNECTION_TIMEOUT, TRY_CONNECTION_TIMEOUT);
      String response = get.getResponseBodyAsString();
      if (status == HttpStatus.SC_OK) {
        JSONObject json = new JSONObject(response);
        if (!json.getBoolean("installed")) {
          mLatestResult =
              new RemoteOperationResult(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED);
        } else {
          mOCVersion = new OwnCloudVersion(json.getString("version"));
          if (!mOCVersion.isVersionValid()) {
            mLatestResult =
                new RemoteOperationResult(RemoteOperationResult.ResultCode.BAD_OC_VERSION);

          } else {
            mLatestResult =
                new RemoteOperationResult(
                    urlSt.startsWith("https://")
                        ? RemoteOperationResult.ResultCode.OK_SSL
                        : RemoteOperationResult.ResultCode.OK_NO_SSL);

            retval = true;
          }
        }

      } else {
        mLatestResult = new RemoteOperationResult(false, status, get.getResponseHeaders());
      }

    } catch (JSONException e) {
      mLatestResult =
          new RemoteOperationResult(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED);

    } catch (Exception e) {
      mLatestResult = new RemoteOperationResult(e);

    } finally {
      if (get != null) get.releaseConnection();
    }

    if (mLatestResult.isSuccess()) {
      Log_OC.i(TAG, "Connection check at " + urlSt + ": " + mLatestResult.getLogMessage());

    } else if (mLatestResult.getException() != null) {
      Log_OC.e(
          TAG,
          "Connection check at " + urlSt + ": " + mLatestResult.getLogMessage(),
          mLatestResult.getException());

    } else {
      Log_OC.e(TAG, "Connection check at " + urlSt + ": " + mLatestResult.getLogMessage());
    }

    return retval;
  }
  @Override
  protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result = null;
    int status = -1;

    GetMethod get = null;

    try {
      // Get Method
      get = new GetMethod(client.getBaseUri() + ShareUtils.SHARING_API_PATH);

      // Add Parameters to Get Method
      get.setQueryString(
          new NameValuePair[] {
            new NameValuePair(PARAM_PATH, mRemoteFilePath),
            new NameValuePair(PARAM_RESHARES, String.valueOf(mReshares)),
            new NameValuePair(PARAM_SUBFILES, String.valueOf(mSubfiles))
          });

      get.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE);

      status = client.executeMethod(get);

      if (isSuccess(status)) {
        String response = get.getResponseBodyAsString();

        // Parse xml response and obtain the list of shares
        ShareToRemoteOperationResultParser parser =
            new ShareToRemoteOperationResultParser(new ShareXMLParser());
        parser.setOwnCloudVersion(client.getOwnCloudVersion());
        parser.setServerBaseUri(client.getBaseUri());
        result = parser.parse(response);

        if (result.isSuccess()) {
          Log_OC.d(TAG, "Got " + result.getData().size() + " shares");
        }

      } else {
        result = new RemoteOperationResult(false, status, get.getResponseHeaders());
      }

    } catch (Exception e) {
      result = new RemoteOperationResult(e);
      Log_OC.e(TAG, "Exception while getting shares", e);

    } finally {
      if (get != null) {
        get.releaseConnection();
      }
    }
    return result;
  }
  /*
   * Tests default status and response headers
   */
  @Test
  public void defaults() throws Exception {
    onRequest().respond();

    final GetMethod method = new GetMethod("http://localhost:" + port());
    int status = client.executeMethod(method);
    assertThat(status, is(DEFAULT_STATUS));

    final Header[] responseHeaders = method.getResponseHeaders(DEFAULT_HEADER1_NAME);
    assertThat(responseHeaders.length, is(2));
    assertThat(responseHeaders[0].getName(), is(equalToIgnoringCase(DEFAULT_HEADER1_NAME)));
    assertThat(responseHeaders[0].getValue(), is(DEFAULT_HEADER1_VALUE1));

    assertThat(responseHeaders[1].getName(), is(equalToIgnoringCase(DEFAULT_HEADER1_NAME)));
    assertThat(responseHeaders[1].getValue(), is(DEFAULT_HEADER1_VALUE2));
  }
Esempio n. 5
0
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String sitemapName = request.getParameter("sitemap");
    String widgetId = request.getParameter("widgetId");

    if (sitemapName == null) {
      throw new ServletException("Parameter 'sitemap' must be provided!");
    }
    if (widgetId == null) {
      throw new ServletException("Parameter 'widget' must be provided!");
    }

    String uriString = null;

    Sitemap sitemap = (Sitemap) modelRepository.getModel(sitemapName);
    if (sitemap != null) {
      Widget widget = itemUIRegistry.getWidget(sitemap, widgetId);
      if (widget instanceof Image) {
        Image image = (Image) widget;
        uriString = image.getUrl();
      } else if (widget instanceof Video) {
        Video video = (Video) widget;
        uriString = video.getUrl();
      } else {
        if (widget == null) {
          throw new ServletException("Widget '" + widgetId + "' could not be found!");
        } else {
          throw new ServletException(
              "Widget type '" + widget.getClass().getName() + "' is not supported!");
        }
      }
    } else {
      throw new ServletException("Sitemap '" + sitemapName + "' could not be found!");
    }

    HttpClient httpClient = new HttpClient();

    try {
      // check if the uri uses credentials and configure the http client accordingly
      URI uri = URI.create(uriString);

      if (uri.getUserInfo() != null) {
        String[] userInfo = uri.getUserInfo().split(":");
        httpClient.getParams().setAuthenticationPreemptive(true);
        Credentials creds = new UsernamePasswordCredentials(userInfo[0], userInfo[1]);
        httpClient
            .getState()
            .setCredentials(
                new AuthScope(uri.getHost(), uri.getPort(), AuthScope.ANY_REALM), creds);
      }
    } catch (IllegalArgumentException e) {
      throw new ServletException("URI '" + uriString + "' is not valid: " + e.getMessage());
    }

    // do the client request
    GetMethod method = new GetMethod(uriString);
    httpClient.executeMethod(method);

    // copy all headers
    for (Header header : method.getResponseHeaders()) {
      response.setHeader(header.getName(), header.getValue());
    }

    // now copy/stream the body content
    IOUtils.copy(method.getResponseBodyAsStream(), response.getOutputStream());
    method.releaseConnection();
  }
Esempio n. 6
0
  /** Run method of the thread */
  public void run() {

    queue = manager.workQueue;
    while (manager.hasWorkLeft()) {

      working = false;
      // code to make the worker pause, if the pause button has been presed

      // if the stop signal has been given stop the thread
      if (stop) {
        return;
      }

      // this pasuses the thread
      synchronized (this) {
        while (pleaseWait) {
          try {
            wait();
          } catch (InterruptedException e) {
            return;
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }

      GetMethod httpget = null;
      HeadMethod httphead = null;

      try {

        work = (WorkUnit) queue.take();
        working = true;
        url = work.getWork();
        int code = 0;

        String responce = "";
        String rawResponce = "";

        // if the work is a head request
        if (work.getMethod().equalsIgnoreCase("HEAD")) {
          if (Config.debug) {
            System.out.println("DEBUG Worker[" + threadId + "]: HEAD " + url.toString());
          }

          httphead = new HeadMethod(url.toString());

          // set the custom HTTP headers
          Vector HTTPheaders = manager.getHTTPHeaders();
          for (int a = 0; a < HTTPheaders.size(); a++) {
            HTTPHeader httpHeader = (HTTPHeader) HTTPheaders.elementAt(a);
            /*
             * Host header has to be set in a different way!
             */
            if (httpHeader.getHeader().startsWith("Host")) {
              httphead.getParams().setVirtualHost(httpHeader.getValue());
            } else {
              httphead.setRequestHeader(httpHeader.getHeader(), httpHeader.getValue());
            }
          }
          httphead.setFollowRedirects(Config.followRedirects);

          /*
           * this code is used to limit the number of request/sec
           */
          if (manager.isLimitRequests()) {
            while (manager.getTotalDone()
                    / ((System.currentTimeMillis() - manager.getTimestarted()) / 1000.0)
                > manager.getLimitRequestsTo()) {
              Thread.sleep(100);
            }
          }
          /*
           * Send the head request
           */
          code = httpclient.executeMethod(httphead);
          if (Config.debug) {
            System.out.println("DEBUG Worker[" + threadId + "]: " + code + " " + url.toString());
          }
          httphead.releaseConnection();

        }
        // if we are doing a get request
        else if (work.getMethod().equalsIgnoreCase("GET")) {
          // make the request;
          if (Config.debug) {
            System.out.println("DEBUG Worker[" + threadId + "]: GET " + url.toString());
          }
          httpget = new GetMethod(url.toString());

          // set the custom HTTP headers
          Vector HTTPheaders = manager.getHTTPHeaders();
          for (int a = 0; a < HTTPheaders.size(); a++) {

            HTTPHeader httpHeader = (HTTPHeader) HTTPheaders.elementAt(a);
            /*
             * Host header has to be set in a different way!
             */
            if (httpHeader.getHeader().startsWith("Host")) {
              httpget.getParams().setVirtualHost(httpHeader.getValue());
            } else {
              httpget.setRequestHeader(httpHeader.getHeader(), httpHeader.getValue());
            }
          }
          httpget.setFollowRedirects(Config.followRedirects);

          /*
           * this code is used to limit the number of request/sec
           */
          if (manager.isLimitRequests()) {
            while (manager.getTotalDone()
                    / ((System.currentTimeMillis() - manager.getTimestarted()) / 1000.0)
                > manager.getLimitRequestsTo()) {
              Thread.sleep(100);
            }
          }

          code = httpclient.executeMethod(httpget);

          if (Config.debug) {
            System.out.println("DEBUG Worker[" + threadId + "]: " + code + " " + url.toString());
          }

          // set up the input stream
          BufferedReader input =
              new BufferedReader(new InputStreamReader(httpget.getResponseBodyAsStream()));

          // save the headers into a string, used in viewing raw responce
          String rawHeader;
          rawHeader = httpget.getStatusLine() + "\r\n";
          Header headers[] = httpget.getResponseHeaders();

          StringBuffer buf = new StringBuffer();
          for (int a = 0; a < headers.length; a++) {
            buf.append(headers[a].getName() + ": " + headers[a].getValue() + "\r\n");
          }

          rawHeader = rawHeader + buf.toString();

          buf = new StringBuffer();
          // read in the responce body
          String line;
          while ((line = input.readLine()) != null) {
            buf.append("\r\n" + line);
          }
          responce = buf.toString();
          input.close();

          rawResponce = rawHeader + responce;
          // clean the responce

          // parse the html of what we have found

          if (Config.parseHTML && !work.getBaseCaseObj().isUseRegexInstead()) {
            Header contentType = httpget.getResponseHeader("Content-Type");

            if (contentType != null) {
              if (contentType.getValue().startsWith("text")) {
                manager.addHTMLToParseQueue(new HTMLparseWorkUnit(responce, work));
              }
            }
          }

          responce = FilterResponce.CleanResponce(responce, work);

          Thread.sleep(10);
          httpget.releaseConnection();
        } else {
          // There is no need to deal with requests other than HEAD or GET
        }

        // if we need to check the against the base case
        if (work.getMethod().equalsIgnoreCase("GET")
            && work.getBaseCaseObj().useContentAnalysisMode()) {
          if (code == 200) {
            if (Config.debug) {
              System.out.println(
                  "DEBUG Worker[" + threadId + "]: Base Case Check " + url.toString());
            }

            // TODO move this option to the Adv options
            // if the responce does not match the base case
            Pattern regexFindFile = Pattern.compile(".*file not found.*", Pattern.CASE_INSENSITIVE);

            Matcher m = regexFindFile.matcher(responce);

            // need to clean the base case of the item we are looking for
            String basecase =
                FilterResponce.removeItemCheckedFor(
                    work.getBaseCaseObj().getBaseCase(), work.getItemToCheck());

            if (m.find()) {
              // do nothing as we have a 404
            } else if (!responce.equalsIgnoreCase(basecase)) {
              if (work.isDir()) {
                if (Config.debug) {
                  System.out.println(
                      "DEBUG Worker[" + threadId + "]: Found Dir (base case)" + url.toString());
                }
                // we found a dir
                manager.foundDir(url, code, responce, basecase, rawResponce, work.getBaseCaseObj());
              } else {
                // found a file
                if (Config.debug) {
                  System.out.println(
                      "DEBUG Worker[" + threadId + "]: Found File (base case)" + url.toString());
                }
                manager.foundFile(
                    url,
                    code,
                    responce,
                    work.getBaseCaseObj().getBaseCase(),
                    rawResponce,
                    work.getBaseCaseObj());
              }
            }
          } else if (code == 404 || code == 400) {
            // again do nothing as it is not there
          } else {
            if (work.isDir()) {
              if (Config.debug) {
                System.out.println(
                    "DEBUG Worker[" + threadId + "]: Found Dir (base case)" + url.toString());
              }
              // we found a dir
              manager.foundDir(
                  url,
                  code,
                  responce,
                  work.getBaseCaseObj().getBaseCase(),
                  rawResponce,
                  work.getBaseCaseObj());
            } else {
              // found a file
              if (Config.debug) {
                System.out.println(
                    "DEBUG Worker[" + threadId + "]: Found File (base case)" + url.toString());
              }
              manager.foundFile(
                  url,
                  code,
                  responce,
                  work.getBaseCaseObj().getBaseCase(),
                  rawResponce,
                  work.getBaseCaseObj());
            }
            // manager.foundError(url, "Base Case Mode Error - Responce code came back as " + code +
            // " it should have been 200");
            // manager.workDone();
          }
        }
        /*
         * use the custom regex check instead
         */
        else if (work.getBaseCaseObj().isUseRegexInstead()) {
          Pattern regexFindFile = Pattern.compile(work.getBaseCaseObj().getRegex());

          Matcher m = regexFindFile.matcher(rawResponce);
          /*
          System.out.println("======Trying to find======");
          System.out.println(work.getBaseCaseObj().getRegex());
          System.out.println("======In======");
          System.out.println(responce);
          System.out.println("======/In======");
           */
          if (m.find()) {
            // do nothing as we have a 404
            if (Config.debug) {

              System.out.println(
                  "DEBUG Worker[" + threadId + "]: Regex matched so it's a 404, " + url.toString());
            }

          } else {
            if (Config.parseHTML) {
              Header contentType = httpget.getResponseHeader("Content-Type");

              if (contentType != null) {
                if (contentType.getValue().startsWith("text")) {
                  manager.addHTMLToParseQueue(new HTMLparseWorkUnit(rawResponce, work));
                }
              }
            }
            if (work.isDir()) {
              if (Config.debug) {
                System.out.println(
                    "DEBUG Worker[" + threadId + "]: Found Dir (regex) " + url.toString());
              }
              // we found a dir
              manager.foundDir(
                  url,
                  code,
                  responce,
                  work.getBaseCaseObj().getBaseCase(),
                  rawResponce,
                  work.getBaseCaseObj());
            } else {
              // found a file
              if (Config.debug) {
                System.out.println(
                    "DEBUG Worker[" + threadId + "]: Found File (regex) " + url.toString());
              }
              manager.foundFile(
                  url,
                  code,
                  responce,
                  work.getBaseCaseObj().getBaseCase(),
                  rawResponce,
                  work.getBaseCaseObj());
            }
            // manager.foundError(url, "Base Case Mode Error - Responce code came back as " + code +
            // " it should have been 200");
            // manager.workDone();
          }

        }
        // just check the responce code
        else {
          // if is not the fail code, a 404 or a 400 then we have a possible
          if (code != work.getBaseCaseObj().getFailCode()
              && code != 404
              && code != 0
              && code != 400) {
            if (work.getMethod().equalsIgnoreCase("HEAD")) {
              if (Config.debug) {
                System.out.println(
                    "DEBUG Worker[" + threadId + "]: Getting responce via GET " + url.toString());
              }
              rawResponce = "";

              httpget = new GetMethod(url.toString());
              Vector HTTPheaders = manager.getHTTPHeaders();
              for (int a = 0; a < HTTPheaders.size(); a++) {
                HTTPHeader httpHeader = (HTTPHeader) HTTPheaders.elementAt(a);
                httpget.setRequestHeader(httpHeader.getHeader(), httpHeader.getValue());
              }
              httpget.setFollowRedirects(Config.followRedirects);

              /*
               * this code is used to limit the number of request/sec
               */
              if (manager.isLimitRequests()) {
                while (manager.getTotalDone()
                        / ((System.currentTimeMillis() - manager.getTimestarted()) / 1000.0)
                    > manager.getLimitRequestsTo()) {
                  Thread.sleep(100);
                }
              }

              int newCode = httpclient.executeMethod(httpget);

              // in some cases the second get can return a different result, than the first head
              // request!
              if (newCode != code) {
                manager.foundError(
                    url,
                    "Return code for first HEAD, is different to the second GET: "
                        + code
                        + " - "
                        + newCode);
              }

              rawResponce = "";
              // build a string version of the headers
              rawResponce = httpget.getStatusLine() + "\r\n";
              Header headers[] = httpget.getResponseHeaders();

              StringBuffer buf = new StringBuffer();
              for (int a = 0; a < headers.length; a++) {
                buf.append(headers[a].getName() + ": " + headers[a].getValue() + "\r\n");
              }

              buf.append("\r\n");

              rawResponce = rawResponce + buf.toString();

              if (httpget.getResponseContentLength() > 0) {

                // get the http body
                BufferedReader input =
                    new BufferedReader(new InputStreamReader(httpget.getResponseBodyAsStream()));

                String line;

                String tempResponce = "";

                buf = new StringBuffer();
                while ((line = input.readLine()) != null) {
                  buf.append("\r\n" + line);
                }
                tempResponce = buf.toString();
                input.close();

                rawResponce = rawResponce + tempResponce;

                Header contentType = httpget.getResponseHeader("Content-Type");

                if (Config.parseHTML) {
                  contentType = httpget.getResponseHeader("Content-Type");

                  if (contentType != null) {
                    if (contentType.getValue().startsWith("text")) {
                      manager.addHTMLToParseQueue(new HTMLparseWorkUnit(tempResponce, work));
                    }
                  }
                }
              }

              httpget.releaseConnection();
            }

            if (work.isDir()) {
              manager.foundDir(url, code, rawResponce, work.getBaseCaseObj());
            } else {
              manager.foundFile(url, code, rawResponce, work.getBaseCaseObj());
            }
          }
        }

        manager.workDone();
        Thread.sleep(20);

      } catch (NoHttpResponseException e) {
        manager.foundError(url, "NoHttpResponseException " + e.getMessage());
        manager.workDone();
      } catch (ConnectTimeoutException e) {
        manager.foundError(url, "ConnectTimeoutException " + e.getMessage());
        manager.workDone();
      } catch (URIException e) {
        manager.foundError(url, "URIException " + e.getMessage());
        manager.workDone();
      } catch (IOException e) {

        manager.foundError(url, "IOException " + e.getMessage());
        manager.workDone();
      } catch (InterruptedException e) {
        // manager.foundError(url, "InterruptedException " + e.getMessage());
        manager.workDone();
        return;
      } catch (IllegalArgumentException e) {

        e.printStackTrace();
        manager.foundError(url, "IllegalArgumentException " + e.getMessage());
        manager.workDone();
      } finally {
        if (httpget != null) {
          httpget.releaseConnection();
        }

        if (httphead != null) {
          httphead.releaseConnection();
        }
      }
    }
  }
  @Override
  protected RemoteOperationResult run(OwnCloudClient client) {
    AccountManager accountMngr = AccountManager.get(mContext);
    String statUrl = accountMngr.getUserData(mAccount, Constants.KEY_OC_BASE_URL);
    statUrl += AccountUtils.STATUS_PATH;
    RemoteOperationResult result = null;
    GetMethod get = null;
    try {
      get = new GetMethod(statUrl);
      int status = client.executeMethod(get);
      if (status != HttpStatus.SC_OK) {
        client.exhaustResponse(get.getResponseBodyAsStream());
        result = new RemoteOperationResult(false, status, get.getResponseHeaders());

      } else {
        String response = get.getResponseBodyAsString();
        if (response != null) {
          JSONObject json = new JSONObject(response);
          if (json != null && json.getString("version") != null) {

            String version = json.getString("version");
            mOwnCloudVersion = new OwnCloudVersion(version);
            if (mOwnCloudVersion.isVersionValid()) {
              accountMngr.setUserData(
                  mAccount, Constants.KEY_OC_VERSION, mOwnCloudVersion.getVersion());
              Log_OC.d(TAG, "Got new OC version " + mOwnCloudVersion.toString());

              result = new RemoteOperationResult(ResultCode.OK);

            } else {
              Log_OC.w(
                  TAG, "Invalid version number received from server: " + json.getString("version"));
              result = new RemoteOperationResult(RemoteOperationResult.ResultCode.BAD_OC_VERSION);
            }
          }
        }
        if (result == null) {
          result =
              new RemoteOperationResult(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED);
        }
      }
      Log_OC.i(
          TAG,
          "Check for update of ownCloud server version at "
              + client.getWebdavUri()
              + ": "
              + result.getLogMessage());

    } catch (JSONException e) {
      result = new RemoteOperationResult(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED);
      Log_OC.e(
          TAG,
          "Check for update of ownCloud server version at "
              + client.getWebdavUri()
              + ": "
              + result.getLogMessage(),
          e);

    } catch (Exception e) {
      result = new RemoteOperationResult(e);
      Log_OC.e(
          TAG,
          "Check for update of ownCloud server version at "
              + client.getWebdavUri()
              + ": "
              + result.getLogMessage(),
          e);

    } finally {
      if (get != null) get.releaseConnection();
    }
    return result;
  }
Esempio n. 8
0
    public void run() {
      AccountManager am = AccountManager.get(getActivity());
      Account account = AccountUtils.getCurrentOwnCloudAccount(getActivity());
      OwnCloudVersion ocv =
          new OwnCloudVersion(am.getUserData(account, AccountAuthenticator.KEY_OC_VERSION));
      String url =
          am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL)
              + AccountUtils.getWebdavPath(ocv);

      Log.d("share", "sharing for version " + ocv.toString());

      if (ocv.compareTo(new OwnCloudVersion(0x040000)) >= 0) {
        String APPS_PATH = "/apps/files_sharing/";
        String SHARE_PATH = "ajax/share.php";

        String SHARED_PATH = "/apps/files_sharing/get.php?token=";

        final String WEBDAV_SCRIPT = "webdav.php";
        final String WEBDAV_FILES_LOCATION = "/files/";

        WebdavClient wc =
            OwnCloudClientUtils.createOwnCloudClient(
                account, getActivity().getApplicationContext());
        HttpConnectionManagerParams params = new HttpConnectionManagerParams();
        params.setMaxConnectionsPerHost(wc.getHostConfiguration(), 5);

        // wc.getParams().setParameter("http.protocol.single-cookie-header", true);
        // wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

        PostMethod post =
            new PostMethod(
                am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL)
                    + APPS_PATH
                    + SHARE_PATH);

        post.addRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
        post.addRequestHeader(
            "Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        Log.d("share", mPath + "");
        formparams.add(new BasicNameValuePair("sources", mPath));
        formparams.add(new BasicNameValuePair("uid_shared_with", "public"));
        formparams.add(new BasicNameValuePair("permissions", "0"));
        post.setRequestEntity(
            new StringRequestEntity(URLEncodedUtils.format(formparams, HTTP.UTF_8)));

        int status;
        try {
          PropFindMethod find = new PropFindMethod(url + "/");
          find.addRequestHeader(
              "Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));
          Log.d("sharer", "" + url + "/");

          for (org.apache.commons.httpclient.Header a : find.getRequestHeaders()) {
            Log.d("sharer-h", a.getName() + ":" + a.getValue());
          }

          int status2 = wc.executeMethod(find);

          Log.d("sharer", "propstatus " + status2);

          GetMethod get =
              new GetMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + "/");
          get.addRequestHeader(
              "Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL));

          status2 = wc.executeMethod(get);

          Log.d("sharer", "getstatus " + status2);
          Log.d("sharer", "" + get.getResponseBodyAsString());

          for (org.apache.commons.httpclient.Header a : get.getResponseHeaders()) {
            Log.d("sharer", a.getName() + ":" + a.getValue());
          }

          status = wc.executeMethod(post);
          for (org.apache.commons.httpclient.Header a : post.getRequestHeaders()) {
            Log.d("sharer-h", a.getName() + ":" + a.getValue());
          }
          for (org.apache.commons.httpclient.Header a : post.getResponseHeaders()) {
            Log.d("sharer", a.getName() + ":" + a.getValue());
          }
          String resp = post.getResponseBodyAsString();
          Log.d("share", "" + post.getURI().toString());
          Log.d("share", "returned status " + status);
          Log.d("share", " " + resp);

          if (status != HttpStatus.SC_OK
              || resp == null
              || resp.equals("")
              || resp.startsWith("false")) {
            return;
          }

          JSONObject jsonObject = new JSONObject(resp);
          String jsonStatus = jsonObject.getString("status");
          if (!jsonStatus.equals("success"))
            throw new Exception("Error while sharing file status != success");

          String token = jsonObject.getString("data");
          String uri =
              am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + SHARED_PATH + token;
          Log.d("Actions:shareFile ok", "url: " + uri);

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

      } else if (ocv.compareTo(new OwnCloudVersion(0x030000)) >= 0) {

      }
    }
  @Override
  protected void doRequest(
      HttpServletRequest request, HttpServletResponse response, RequestType requestType)
      throws ServletException, IOException {
    RegexHelper MATCH_URL_REGEX = new RegexHelper("/+(.+)", "i");
    RegexHelper TEST_HOST_IN_URL_REGEX = new RegexHelper("^http\\:/{2}([^/]+)/", "i");
    RegexHelper SQUARE_BRACKETS_REGEX = new RegexHelper("\\[\\]", "g");

    logRequest(logger, request, requestType);

    String url = MATCH_URL_REGEX.matchFirst(request.getPathInfo());
    url =
        url.replaceFirst(
            "http:/{1,2}", "http://"); // stupid hack as tomcat 6.0 removes second forward slash
    String queryString = request.getQueryString();

    if (0 < url.length()) {
      if (!TEST_HOST_IN_URL_REGEX.test(url)) { // no host here, will self
        url = "http://localhost:" + String.valueOf(request.getLocalPort()) + "/" + url;
      }
      logger.debug("Will access [{}]", url);

      GetMethod getMethod = new GetMethod(url);

      if (null != queryString) {
        queryString = SQUARE_BRACKETS_REGEX.replace(queryString, "%5B%5D");
        getMethod.setQueryString(queryString);
      }

      Enumeration requestHeaders = request.getHeaderNames();
      while (requestHeaders.hasMoreElements()) {
        String name = (String) requestHeaders.nextElement();
        String value = request.getHeader(name);
        if (null != value) {
          getMethod.setRequestHeader(name, value);
        }
      }

      try {
        httpClient.executeMethod(getMethod);

        int statusCode = getMethod.getStatusCode();
        long contentLength = getMethod.getResponseContentLength();
        logger.debug("Got response [{}], length [{}]", statusCode, contentLength);

        Header[] responseHeaders = getMethod.getResponseHeaders();
        for (Header responseHeader : responseHeaders) {
          String name = responseHeader.getName();
          String value = responseHeader.getValue();
          if (null != name
              && null != value
              && !(name.equals("Server")
                  || name.equals("Date")
                  || name.equals("Transfer-Encoding"))) {
            response.setHeader(responseHeader.getName(), responseHeader.getValue());
          }
        }

        if (200 != statusCode) {
          response.setStatus(statusCode);
        }

        InputStream inStream = getMethod.getResponseBodyAsStream();
        if (null != inStream) {
          BufferedReader in = new BufferedReader(new InputStreamReader(inStream));

          BufferedWriter out =
              new BufferedWriter(new OutputStreamWriter(response.getOutputStream()));

          CharBuffer buffer = CharBuffer.allocate(PROXY_BUFFER_SIZE);
          while (in.read(buffer) >= 0) {
            buffer.flip();
            out.append(buffer);
            buffer.clear();
          }

          in.close();
          out.close();
        }
      } catch (Exception x) {
        if (x.getClass().getName().equals("org.apache.catalina.connector.ClientAbortException")) {
          logger.warn("Client aborted connection");
        } else {
          logger.error("Caught an exception:", x);
          response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, x.getMessage());
        }
      } finally {
        getMethod.releaseConnection();
      }
    }
  }