private InputStream processGetRequest(URL url, String keyStore, String keyStorePassword) {
    SSLSocketFactory sslFactory = getSSLSocketFactory(keyStore, keyStorePassword);
    HttpsURLConnection con = null;
    try {
      con = (HttpsURLConnection) url.openConnection();
    } catch (IOException e) {
      logger.error(e.getMessage(), e);
      throw new RuntimeException(e.getMessage(), e);
    }
    con.setSSLSocketFactory(sslFactory);
    try {
      con.setRequestMethod(REQUEST_METHOD_GET);
    } catch (ProtocolException e) {
      logger.error(e.getMessage(), e);
      throw new RuntimeException(e.getMessage(), e);
    }

    con.addRequestProperty(X_MS_VERSION_HEADER, X_MS_VERSION);

    InputStream responseStream = null;
    try {
      responseStream = (InputStream) con.getContent();
    } catch (IOException e) {
      logger.error(e.getMessage(), e);
      throw new RuntimeException(e.getMessage(), e);
    }

    return responseStream;
  }
  public void run() {
    String fileName;
    ResponseCallback cb = new ResponseCallback(mComm, mEvent);

    try {

      if ((fileName = Serialization.DecodeString(mEvent.payload)) == null)
        throw new ProtocolException("Filename not properly encoded in request packet");

      mBroker.Remove(cb, fileName);

    } catch (ProtocolException e) {
      int error = cb.error(Error.PROTOCOL_ERROR, e.getMessage());
      log.severe("Protocol error (REMOVE) - " + e.getMessage());
      if (error != Error.OK)
        log.severe("Problem sending (REMOVE) error back to client - " + Error.GetText(error));
    }
  }
  private void prepareRequest(String method) throws IOException, FisherException {
    try {
      conn = (HttpURLConnection) uri.openConnection();

      // Set method: GET, POST,...
      conn.setRequestMethod(method);

      // Set Headers
      if (headers != null) {
        for (String key : headers.fields.keySet()) {
          conn.setRequestProperty(key, headers.getField(key, null).asString(null));
        }
      }
    } catch (ProtocolException e) {
      System.err.println("ProtocolException: " + e.getMessage());
    }
  }
  private void transfer(HttpsURLConnection conn, String filename) {
    DataOutputStream dos = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;

    try {
      conn.setDoInput(true); // Allow Inputs
      conn.setDoOutput(true); // Allow Outputs
      conn.setUseCaches(false); // Don't use a Cached Copy
      conn.setRequestMethod("POST");
      conn.setRequestProperty("Connection", "Keep-Alive");
      conn.setRequestProperty("ENCTYPE", "multipart/form-data");
      conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

      dos = new DataOutputStream(conn.getOutputStream());

      dos.writeBytes(twoHyphens + boundary + lineEnd);
      dos.writeBytes(
          "Content-Disposition: form-data; name=\""
              + filename
              + "\";filename=\""
              + filename
              + "\""
              + lineEnd);

      dos.writeBytes(lineEnd);
      FileInputStream fileInputStream = this.context.openFileInput(filename);
      bytesAvailable = fileInputStream.available();

      bufferSize = Math.min(bytesAvailable, maxBufferSize);
      buffer = new byte[bufferSize];

      // read file and write it into form...
      bytesRead = fileInputStream.read(buffer, 0, bufferSize);
      Log.v("mark", "reading " + bytesRead + " bytes");
      while (bytesRead > 0) {
        dos.write(buffer, 0, bufferSize);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
      }

      // send multipart form data necesssary after file data...
      dos.writeBytes(lineEnd);
      dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

      // Responses from the server (code and message)
      int serverResponseCode = conn.getResponseCode();
      String serverResponseMessage = conn.getResponseMessage();

      Log.v("mark", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
      fileInputStream.close();

      DataInputStream dis = new DataInputStream(conn.getInputStream());
      if (dis.available() > 0) {
        byte[] buf = new byte[256];
        dis.read(buf);
        Log.v("mark", "line1:" + new String(buf));
      } else {
        Log.v("mark", "line1:none");
      }

      // close the streams //
      //			if(dis.available()>0){
      //				byte[] buf = new byte[256];
      //				dis.read(buf);
      //				Log.v("mark","line2:"+new String(buf));
      //			}else{
      //				Log.v("mark","line2:none");
      //			}
      dis.close();
      dos.flush();
      dos.close();

    } catch (ProtocolException e) {
      Log.v("mark", "ProtocolException:" + e.getMessage());
    } catch (IOException e) {
      Log.v("mark", "IOException:" + e.getMessage());
    }
  }
示例#5
0
  private void test() {

    HttpURLConnection fbc;
    String response = "";

    boolean isConnectionError = false;
    String connectionErrorMessage = "";
    String uidstr = Long.toString(uid);
    boolean unknown = true;
    long random = new Random().nextInt();
    long channel = 65;
    long seq = 0;

    String endpoint = createEndpoint(channel, random, unknown, uidstr, seq);
    String endpointHost = createEndpointHost(channel, random, unknown, uidstr, seq);
    String endpointFile = createEndpointFile(channel, random, unknown, uidstr, seq);

    // endpoint = "http://www.google.com";
    int mConnectionTimeout = 50000;
    String REQUEST_METHOD = "GET";

    response = "";

    CookieManager cm = CookieManager.getInstance();
    String cookies = cm.getCookie("facebook.com");

    Log.d(LOG_TAG, "cookie: " + cookies);
    try {
      HttpClientConnection httpClientConn;

      URL url = new URL("http", endpointHost, 80, endpointFile);
      Log.d(LOG_TAG, "url to connect:" + url.toString());
      fbc = (HttpURLConnection) url.openConnection();
      fbc.setUseCaches(true);
      fbc.setConnectTimeout(mConnectionTimeout);
      fbc.setRequestMethod(REQUEST_METHOD);
      fbc.setRequestProperty("Content-type", REQUEST_CONTENT_TYPE);
      fbc.setRequestProperty("User-Agent", REQUEST_USER_AGENT);
      fbc.setRequestProperty("Accept-Language", REQUEST_ACCEPT_LANGUAGE);
      fbc.setRequestProperty("Accept", REQUEST_ACCEPT);
      fbc.setRequestProperty("Accept-Charset", REQUEST_ACCEPT_CHARSET);
      fbc.setRequestProperty("Cookie", cookies);

      // DataOutputStream dos = new DataOutputStream(fbc.getOutputStream());
      // dos.writeBytes(response);
      // dos.flush();
      // dos.close();

      // fbc.connect();
      // fbc.getContent();

      /*
      try{
      	Object obj = fbc.getContent();
      	Log.d(LOG_TAG,"content class: " + obj.getClass().getCanonicalName());
      }

      catch(Exception e){

      }
      */

      // String responseMsg = fbc.getResponseMessage();
      // Log.d(LOG_TAG,"response message:"+responseMsg);
      InputStream is = fbc.getInputStream();
      BufferedReader breader =
          new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
      int linecount = 0;

      while (true) {
        String line = breader.readLine();
        if (line == null) {
          break;
        }
        linecount++;
        response += line;
        Log.d(LOG_TAG, linecount + ":" + line);
      }

      Log.d(LOG_TAG, "TEST_DONE");

    } catch (MalformedURLException e) {
      e.printStackTrace();
      isConnectionError = true;
      connectionErrorMessage = "MalformedURLException: " + e.getMessage();
    } catch (ProtocolException e) {
      e.printStackTrace();
      isConnectionError = true;
      connectionErrorMessage = "ProtocolException: " + e.getMessage();
    } catch (UnknownHostException e) {
      e.printStackTrace();
      isConnectionError = true;
      connectionErrorMessage = "UnknownHostException: " + e.getMessage();
    } catch (IOException e) {
      e.printStackTrace();
      isConnectionError = true;
      connectionErrorMessage = "IOException: " + e.getMessage();
    }
  }
示例#6
0
  /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String message = "";
    boolean success = false;
    String baseUrl = request.getParameter(PARAM_SEED_HUB);
    String accessKey = request.getParameter(AppConstants.SETTINGS_ACCESS_KEY);

    // Non empty parameters
    if (baseUrl == null || accessKey == null) {
      baseUrl = "";
      accessKey = "";
    }
    if (baseUrl.equals("") || accessKey.equals("")) {
      throw new ServletException("accessKey and baseUrl must be defined.");
    }

    // Access key should have no value on database. Or if it's present it must coincide with the
    // given value
    try {
      String dbKey = SettingsBusiness.getAccessKey();
      if (dbKey != null) {
        if (!dbKey.equals(accessKey)) {
          throw new ServletException(
              "accessKey already exists. This software has already been installed.");
        }
      }
    } catch (OrmException e) {
      throw new ServletException(e.getMessage(), e);
    }
    // Set accessKey
    try {
      SettingsBusiness.setAccessKey(accessKey);
    } catch (OrmException e) {
      throw new ServletException(e.getMessage(), e);
    }
    message += "Access key has been correctly set.<br/><br/>";

    // Hub list should be empty
    boolean emptyHubList = true;
    try {
      List<Hubs> hubList = HubBusiness.findAllHubs(true, false);
      if (hubList != null) {
        if (hubList.size() > 0) {
          message += "The first hub has already been defined.";
          emptyHubList = false;
        }
      }
    } catch (OrmException e) {
      throw new ServletException(e.getMessage(), e);
    }
    // Set the seed
    Hubs hub = null;
    if (emptyHubList) {
      // Look for hub baseUrl
      String pollUrl = null;
      try {
        if (baseUrl != null) {
          String baseUrlParam = HubBusiness.cleanBaseUrl(baseUrl);
          pollUrl = baseUrlParam + AppConstants.JSON_SITEINFO;
          if (urlExists(pollUrl)) {
            baseUrl = baseUrlParam;
          }
        }
        LOG.debug("baseUrl = " + baseUrl);
        LOG.debug("response from pollUrl = " + pollUrl);

        if (baseUrl != null) {
          try {
            // Revive or add hub
            hub = HubBusiness.addHub(baseUrl);
            message +=
                "Your hub have been correctly registered.<br />"
                    + "It will be included in global statistics within 24 hours.";
            success = true;
          } catch (Exception e) {
            // UrlException, BusinessException and OrmException => exit with error message
            LogBusiness.addLog(AppConstants.LOG_DEBUG, "install", e.getMessage());
            message = baseUrl + " could not be added.<br />" + "Cause: " + e.getMessage();
            LOG.error(message, e);
          }
        } else {
          message = "The hub base URL is incorrect. Please re-submit this page.";
        }
      } catch (ProtocolException e) {
        message = e.getMessage();
        LOG.debug(e.getMessage(), e);
      } catch (IOException e) {
        message = e.getMessage();
        LOG.debug(e.getMessage(), e);
      }
    }

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println(
        "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n"
            + "<html> \n"
            + "<head> \n"
            + "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\"> \n"
            + "<title>Hubzilla hub registration</title> \n"
            + "<meta name='viewport' content='width=device-width, initial-scale=1'>"
            + "<link href='css/bootstrap.min.css' rel='stylesheet'>"
            + "</head> \n"
            + "<body> \n"
            + "<div class='container'>"
            + "<h1><img src='images/hubchart2-32.png' align='middle' /> hubchart</h1>"
            + "&nbsp;<br />");
    if (success) {
      out.println("<p>" + message + "</p>");
      if (hub != null) {
        out.println("<p>");
        out.println("Name: " + hub.getName() + "<br />");
        out.println("Base URL: " + hub.getBaseUrl() + "<br />");
        String icon = AppConstants.NETWORK_ICONS.get(hub.getNetworkType());
        if (icon == null) icon = AppConstants.NETWORK_ICON_UNKNOWN;
        out.println(
            "Network: <img src='" + icon + "' border='0'/> " + hub.getNetworkType() + "<br />");
        // out.println("Server location: <img
        // src='"+LookupUtil.decodeCountryToFlag(hub.getCountryCode())+"' /> "+
        //		hub.getCountryName()+"<br />");
        out.println(
            "Registration: "
                + AppConstants.REGISTRATION_DESCRIPTIONS.get(hub.getRegistrationPolicy())
                + "<br />");
        out.println("Version: " + hub.getVersion() + "<br />");
        out.println("</p>");
      }
    } else {
      out.println("<p style='color:#c60032;'>ERROR: " + message + "</p>");
      out.println(
          "<p>You must provide a correct and working base URL in the form <br />"
              + "<code>https://&lt;domain&gt;</code><br />"
              + "<code>http://&lt;domain&gt;</code><br />"
              + "<code>http(s)://&lt;domain&gt;/&lt;base_dir&gt;</code><br /><br />"
              + "Please check the <b>http</b> or <b>https</b> prefix!<br /><br />"
              + "If you find a bug please contact the author</a>.<br /><br />");
    }
    out.println("<a href='index.jsp'><b>&lt;- back</b></a>");
    out.println("</div><!-- /container -->");
    out.println("</body> \n" + "</html>");
  }