/** Deletes a search using the specified uri target. */
  private void doDelete(String uriTarget, HttpResponse response) throws IOException {
    // Use GUID to get search result list.
    SearchResultList searchList;
    try {
      String guidStr = parseGuid(uriTarget);
      searchList = searchManager.getSearchResultList(new GUID(guidStr));
    } catch (Exception ex) {
      searchList = null;
    }

    if (searchList != null) {
      Search search = searchList.getSearch();

      // Stop search.
      search.stop();

      // Remove search from core management.
      searchManager.removeSearch(search);

      // Set OK status.
      response.setStatusCode(HttpStatus.SC_OK);

    } else {
      response.setStatusCode(HttpStatus.SC_NOT_FOUND);
    }
  }
 public void verify(
     final HttpRequest request, final HttpResponse response, final HttpContext context)
     throws HttpException {
   String creds = this.authTokenExtractor.extract(request);
   if (creds == null || !creds.equals("test:test")) {
     response.setStatusCode(HttpStatus.SC_UNAUTHORIZED);
   } else {
     response.setStatusCode(HttpStatus.SC_CONTINUE);
   }
 }
  /** Processes request to retrieve data for a single search. */
  private void doGetSearch(String uriTarget, Map<String, String> queryParams, HttpResponse response)
      throws IOException {

    // Use GUID to get search result list.
    SearchResultList searchList;
    try {
      String guidStr = parseGuid(uriTarget);
      searchList = searchManager.getSearchResultList(new GUID(guidStr));
    } catch (Exception ex) {
      searchList = null;
    }

    // Return empty object if null.
    if (searchList == null) {
      response.setEntity(RestUtils.createStringEntity("{}"));
      response.setStatusCode(HttpStatus.SC_OK);
      return;
    }

    try {
      if (uriTarget.indexOf(FILES) < 0) {
        // Return search metadata.
        JSONObject jsonObj = RestUtils.createSearchJson(searchList);
        HttpEntity entity = RestUtils.createStringEntity(jsonObj.toString());
        response.setEntity(entity);
        response.setStatusCode(HttpStatus.SC_OK);

      } else {
        // Get query parameters.
        String offsetStr = queryParams.get("offset");
        String limitStr = queryParams.get("limit");
        int offset = (offsetStr != null) ? Integer.parseInt(offsetStr) : 0;
        int limit =
            (limitStr != null) ? Math.min(Integer.parseInt(limitStr), MAX_LIMIT) : MAX_LIMIT;

        // Create search result array.
        List<GroupedSearchResult> resultList =
            new ArrayList<GroupedSearchResult>(searchList.getGroupedResults());
        JSONArray jsonArr = new JSONArray();
        for (int i = offset, max = Math.min(offset + limit, resultList.size()); i < max; i++) {
          GroupedSearchResult result = resultList.get(i);
          jsonArr.put(RestUtils.createSearchResultJson(result));
        }

        // Set response entity and status.
        HttpEntity entity = RestUtils.createStringEntity(jsonArr.toString());
        response.setEntity(entity);
        response.setStatusCode(HttpStatus.SC_OK);
      }

    } catch (JSONException ex) {
      throw new IOException(ex);
    }
  }
 public void handle(
     final HttpRequest request, final HttpResponse response, final HttpContext context)
     throws HttpException, IOException {
   String creds = (String) context.getAttribute("creds");
   if (creds == null || !creds.equals("test:test")) {
     response.setStatusCode(HttpStatus.SC_UNAUTHORIZED);
   } else {
     response.setStatusCode(HttpStatus.SC_OK);
     StringEntity entity = new StringEntity("success", Consts.ASCII);
     response.setEntity(entity);
   }
 }
Example #5
0
  @Override
  protected void getResponse(HttpRequest request, HttpResponse response, HttpContext context) {
    if (!"POST".equals(request.getRequestLine().getMethod())) {
      response.setStatusCode(405);
      return;
    }

    if (request instanceof BasicHttpEntityEnclosingRequest) {
      HttpEntity postEntity = ((BasicHttpEntityEnclosingRequest) request).getEntity();

      String title = null;
      String note = null;
      String tags = null;

      List<NameValuePair> postParams;
      try {
        postParams = URLEncodedUtils.parse(postEntity);
      } catch (IOException e) {
        Log.e(TAG, "Failed to parse parameters!", e);
        response.setStatusCode(500);
        return;
      }

      for (NameValuePair nvp : postParams) {
        Log.d(TAG, "(" + nvp.getName() + "|" + nvp.getValue() + ")");
        if ("note".equals(nvp.getName())) note = nvp.getValue();
        if ("title".equals(nvp.getName())) title = nvp.getValue();
        if ("tags".equals(nvp.getName())) tags = nvp.getValue();
      }

      if (title == null || note == null) {
        response.setStatusCode(400);
        return;
      }

      ContentValues values = new ContentValues();
      values.put("modified", new Long(System.currentTimeMillis()));
      values.put("created", new Long(System.currentTimeMillis()));
      values.put("title", title);
      values.put("note", note);
      if (tags != null) {
        values.put("tags", tags);
      }
      // prevent notepad app from throwing IndexOutOfBoundsException
      values.put("selection_start", new Long(0));
      values.put("selection_end", new Long(0));

      mContext.getContentResolver().insert(mNotesURI, values);
    }
  }
 /**
  * Handles the given exception and generates an HTTP response to be sent back to the client to
  * inform about the exceptional condition encountered in the course of the request processing.
  *
  * @param ex the exception.
  * @param response the HTTP response.
  */
 protected void handleException(final HttpException ex, final HttpResponse response) {
   if (ex instanceof MethodNotSupportedException) {
     response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED);
   } else if (ex instanceof UnsupportedHttpVersionException) {
     response.setStatusCode(HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED);
   } else if (ex instanceof ProtocolException) {
     response.setStatusCode(HttpStatus.SC_BAD_REQUEST);
   } else {
     response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
   }
   byte[] msg = EncodingUtils.getAsciiBytes(ex.getMessage());
   ByteArrayEntity entity = new ByteArrayEntity(msg);
   entity.setContentType("text/plain; charset=US-ASCII");
   response.setEntity(entity);
 }
  @Override
  public void handle(HttpRequest request, HttpResponse response, HttpContext context)
      throws HttpException, IOException {

    // Get request method and uri target.
    String method = request.getRequestLine().getMethod();
    String uriTarget = RestUtils.getUriTarget(request, RestPrefix.SEARCH.pattern());
    Map<String, String> queryParams = RestUtils.getQueryParams(request);

    if (RestUtils.GET.equals(method) && ALL.equals(uriTarget)) {
      // Get metadata for all searches.
      doGetAll(uriTarget, queryParams, response);

    } else if (RestUtils.GET.equals(method) && (uriTarget.length() > 0)) {
      // Get data for single search.
      doGetSearch(uriTarget, queryParams, response);

    } else if (RestUtils.POST.equals(method) && START.equals(uriTarget)) {
      // Start search.
      doStart(uriTarget, queryParams, response);

    } else if (RestUtils.DELETE.equals(method) && (uriTarget.length() > 0)) {
      // Delete search.
      doDelete(uriTarget, response);

    } else {
      response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED);
    }
  }
 @Override
 public void handle(
     final HttpRequest request, final HttpResponse response, final HttpContext context)
     throws HttpException, IOException {
   response.setStatusCode(200);
   response.setEntity(new StringEntity("Hello World"));
 }
  /** Starts a new search using the specified uri target and query parameters. */
  private void doStart(String uriTarget, Map<String, String> queryParams, HttpResponse response)
      throws IOException {

    // Get parameters to start search.
    String searchQuery = queryParams.get("q");

    // Create search.
    SearchDetails searchDetails = RestSearchDetails.createKeywordSearch(searchQuery);
    Search search = searchFactory.createSearch(searchDetails);

    // Add search to search manager.  The search is monitored so it will
    // be cancelled if we stop polling for its results.
    SearchResultList searchList = searchManager.addMonitoredSearch(search, searchDetails);

    // Start search.
    search.start();

    try {
      // Return search metadata.
      JSONObject jsonObj = RestUtils.createSearchJson(searchList);
      HttpEntity entity = RestUtils.createStringEntity(jsonObj.toString());
      response.setEntity(entity);
      response.setStatusCode(HttpStatus.SC_OK);

    } catch (JSONException ex) {
      throw new IOException(ex);
    }
  }
Example #10
0
  @Override
  public void handler(HttpRequest request, HttpResponse response, HttpContext context)
      throws UnsupportedEncodingException, JSONException {
    String url = parseGetUrl(request);
    JSONObject result = new JSONObject();
    String[] urlpart = url.split("/");
    String classNameString = urlpart[1].toLowerCase();
    String methodNameString = urlpart[2].toLowerCase();
    Map<String, String> params = parseGetParamters(request);

    // 获取粘贴板内容
    if (methodNameString.equals("get")) {
      String data = Clipboard.get(mContext);
      result.put("data", data);
    }
    // 设置粘贴板内容
    if (methodNameString.equals("set")) {
      String text = params.get("text");
      Clipboard.set(mContext, text);
    }

    result.put("code", "10000");
    result.put("msg", "success");

    StringEntity entity =
        new StringEntity(wrap_jsonp(result.toString(), params), Constants.ENCODING);
    response.setStatusCode(HttpStatus.SC_OK);
    response.setHeader("Content-Type", "application/javascript");
    response.setEntity(entity);
  }
Example #11
0
    public void handle(HttpRequest request, HttpResponse response, HttpContext arg2)
        throws HttpException, IOException {
      EntityTemplate body =
          new EntityTemplate(
              new ContentProducer() {
                public void writeTo(final OutputStream outstream) throws IOException {
                  OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
                  writer.write("var sounds = [");
                  for (int i = 0; i < raws.length - 1; i++) {
                    writer.write("'" + raws[i].getName() + "',");
                  }
                  writer.write("'" + raws[raws.length - 1].getName() + "'];");
                  writer.write("var screenState = " + (screenState ? "1" : "0") + ";");
                  writer.flush();
                }
              });

      response.setStatusCode(HttpStatus.SC_OK);
      body.setContentType("application/json; charset=UTF-8");
      response.setEntity(body);

      // Bring SpydrdoiActivity to the foreground
      if (!screenState) {
        Intent i = new Intent(context, ServerActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
      }
    }
Example #12
0
 /**
  * 从响应中获取body信息
  *
  * @param res
  * @return String
  */
 @SuppressWarnings("deprecation")
 private String getResBody(HttpResponse res) {
   String strResult = "";
   if (res == null) return strResult;
   if (res.getStatusLine().getStatusCode() == 200) {
     try {
       strResult = strResult + EntityUtils.toString(res.getEntity(), charset);
     } catch (ParseException e) {
       log.error("获取body信息异常450:");
       log.error(e.getMessage());
       strResult = e.getMessage().toString();
     } catch (IOException e) {
       log.error("获取body信息异常454:");
       log.error(e.getMessage());
       strResult = e.getMessage().toString();
     }
   } else if (res.getStatusLine().getStatusCode() == 302) {
     String url = res.getLastHeader("Location").getValue();
     res.setStatusCode(200);
     strResult = url;
     return strResult;
   } else {
     strResult = "Error Response:" + res.getStatusLine().toString();
     if (res.getEntity() != null) {
       try {
         res.getEntity().consumeContent();
       } catch (IOException e) {
         log.error("获取body信息异常469:");
         log.error(e.getMessage());
       }
     }
   }
   return strResult;
 }
  private void prepareErrorResponse(final HttpResponse response, final PlatformException e) {
    final int errorCode =
        (e.getHttpStatus() != 0 ? e.getHttpStatus() : HttpStatus.SC_INTERNAL_SERVER_ERROR);
    final String errorMessage = e.getMessage();
    ErrorMessage message = new ErrorMessage(errorCode, errorMessage);

    try {
      ByteArrayOutputStream baos = errorParser.writeInternal(message);
      response.setStatusCode(errorCode);
      response.setEntity(new ByteArrayEntity(baos.toByteArray(), ErrorParser.DEFAULT_CONTENT_TYPE));
      response.setHeader(
          HttpHeader.CONTENT_TYPE.toString(), ErrorParser.DEFAULT_CONTENT_TYPE.toString());
    } catch (JsonConverterException jce) {
      response.setStatusCode(errorCode);
      response.setEntity(new ByteArrayEntity(jce.getMessage().getBytes()));
    }
  }
Example #14
0
 @Override
 public void handle(HttpRequest request, HttpResponse response, HttpContext context)
     throws HttpException, IOException {
   LogUtil.w("Unsupported request received: " + request.getRequestLine());
   response.setStatusCode(HttpStatus.SC_NOT_FOUND);
   response.setReasonPhrase("Not Found");
   response.setEntity(new StringEntity("Endpoint not implemented\n", Utf8Charset.NAME));
 }
 public HttpResponse prepareResponse(int responseStatus, String fileName) throws IOException {
   HttpResponse response =
       new BasicHttpResponse(
           new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), responseStatus, ""));
   response.setStatusCode(responseStatus);
   byte[] bytes = Resources.toByteArray(Resources.getResource(fileName));
   response.setEntity(new ByteArrayEntity(bytes));
   return response;
 }
Example #16
0
    public void handle(HttpRequest request, HttpResponse response, HttpContext arg2)
        throws HttpException, IOException {

      final String uri = URLDecoder.decode(request.getRequestLine().getUri());
      final List<NameValuePair> params = URLEncodedUtils.parse(URI.create(uri), "UTF-8");
      final String[] content = {"Error"};
      int soundID;

      response.setStatusCode(HttpStatus.SC_NOT_FOUND);

      if (params.size() > 0) {
        try {
          for (Iterator<NameValuePair> it = params.iterator(); it.hasNext(); ) {
            NameValuePair param = it.next();
            // Load sound with appropriate name
            if (param.getName().equals("name")) {
              for (int i = 0; i < raws.length; i++) {
                if (raws[i].getName().equals(param.getValue())) {
                  soundID = soundPool.load(context, raws[i].getInt(null), 0);
                  response.setStatusCode(HttpStatus.SC_OK);
                  content[0] = "OK";
                }
              }
            }
          }
        } catch (Exception e) {
          Log.e(TAG, "Error !");
          e.printStackTrace();
        }
      }

      EntityTemplate body =
          new EntityTemplate(
              new ContentProducer() {
                public void writeTo(final OutputStream outstream) throws IOException {
                  OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
                  writer.write(content[0]);
                  writer.flush();
                }
              });
      body.setContentType("text/plain; charset=UTF-8");
      response.setEntity(body);
    }
Example #17
0
 public void handle(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext)
     throws HttpException, IOException {
   httpResponse.setHeader(
       "location",
       "http4://"
           + localServer.getInetAddress().getHostName()
           + ":"
           + localServer.getLocalPort()
           + "/someplaceelse");
   httpResponse.setStatusCode(code);
 }
Example #18
0
  protected void handleException(HttpException var1, HttpResponse var2) {
    if (var1 instanceof MethodNotSupportedException) {
      var2.setStatusCode(501);
    } else if (var1 instanceof UnsupportedHttpVersionException) {
      var2.setStatusCode(505);
    } else if (var1 instanceof ProtocolException) {
      var2.setStatusCode(400);
    } else {
      var2.setStatusCode(500);
    }

    String var4 = var1.getMessage();
    String var3 = var4;
    if (var4 == null) {
      var3 = var1.toString();
    }

    ByteArrayEntity var5 = new ByteArrayEntity(EncodingUtils.getAsciiBytes(var3));
    var5.setContentType("text/plain; charset=US-ASCII");
    var2.setEntity(var5);
  }
  @Override
  public void getResponse(HttpRequest request, HttpResponse response, HttpContext context) {
    if (!"GET".equals(request.getRequestLine().getMethod())) {
      response.setStatusCode(405);
      return;
    }

    String oldName = URLUtil.getParameter(request.getRequestLine().getUri(), "oldname");
    String newName = URLUtil.getParameter(request.getRequestLine().getUri(), "newname");
    String id = URLUtil.getParameter(request.getRequestLine().getUri(), "id");

    if (newName == null || newName.equals("")) {
      response.setStatusCode(400);
      return;
    }

    if ((oldName == null && id == null) || (oldName != null && id != null)) {
      response.setStatusCode(400);
      return;
    }

    ContentValues values = new ContentValues();
    values.put(MODIFIED_DATE, Long.valueOf(System.currentTimeMillis()));
    values.put(NAME, newName);

    String where;
    String[] selectionArgs;

    if (oldName != null) {
      where = NAME + " = ?";
      selectionArgs = new String[] {oldName};
    } else {
      where = _ID + " = ?";
      selectionArgs = new String[] {id};
    }

    if (0 == mContext.getContentResolver().update(CONTENT_URI, values, where, selectionArgs)) {
      response.setStatusCode(400);
    }
  }
Example #20
0
  protected void doService(HttpRequest var1, HttpResponse var2, HttpContext var3)
      throws HttpException, IOException {
    HttpRequestHandler var4 = null;
    if (this.handlerMapper != null) {
      var4 = this.handlerMapper.lookup(var1);
    }

    if (var4 != null) {
      var4.handle(var1, var2, var3);
    } else {
      var2.setStatusCode(501);
    }
  }
 /**
  * The default implementation of this method attempts to resolve an {@link HttpRequestHandler} for
  * the request URI of the given request and, if found, executes its {@link
  * HttpRequestHandler#handle(HttpRequest, HttpResponse, HttpContext)} method.
  *
  * <p>Super-classes can override this method in order to provide a custom implementation of the
  * request processing logic.
  *
  * @param request the HTTP request.
  * @param response the HTTP response.
  * @param context the execution context.
  * @throws IOException in case of an I/O error.
  * @throws HttpException in case of HTTP protocol violation or a processing problem.
  */
 protected void doService(
     final HttpRequest request, final HttpResponse response, final HttpContext context)
     throws HttpException, IOException {
   HttpRequestHandler handler = null;
   if (this.handlerResolver != null) {
     String requestURI = request.getRequestLine().getUri();
     handler = this.handlerResolver.lookup(requestURI);
   }
   if (handler != null) {
     handler.handle(request, response, context);
   } else {
     response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED);
   }
 }
Example #22
0
 @Override
 public void handle(HttpRequest request, HttpResponse response, HttpContext context)
     throws HttpException, IOException {
   response.setStatusCode(HttpStatus.SC_NO_CONTENT);
   magnetExecutor.execute(
       new Runnable() {
         public void run() {
           try {
             Thread.sleep(2500);
           } catch (InterruptedException e) {
           }
         }
       });
 }
Example #23
0
  private void handleException(String msg, Exception e) {

    if (e == null) {
      log.error(msg);
    } else {
      log.error(msg, e);
    }
    Exception newException = e;
    if (e == null) {
      newException = new Exception(msg);
    }

    try {
      MessageContext faultContext =
          MessageContextBuilder.createFaultMessageContext(msgContext, newException);
      AxisEngine.sendFault(faultContext);

    } catch (Exception ex) {
      response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
      response.addHeader(CONTENT_TYPE, TEXT_XML);
      conn.getContext().setAttribute(NhttpConstants.FORCE_CONNECTION_CLOSE, true);
      serverHandler.commitResponseHideExceptions(conn, response);

      try {
        if (is != null) {
          try {
            is.close();
          } catch (IOException ignore) {
          }
        }

        String body =
            "<html><body><h1>" + "Failed to process the request" + "</h1><p>" + msg + "</p>";
        if (e != null) {
          body = body + "<p>" + e.getMessage() + "</p></body></html>";
        }
        if (ex != null) {
          body = body + "<p>" + ex.getMessage() + "</p></body></html>";
        }
        os.write(body.getBytes());
        os.flush();
        os.close();
      } catch (IOException ignore) {
      }
    }
  }
  private boolean handleFileRequest(Path path, final HttpResponse response) {
    WebServerLog.log(this, "Request handler checking file: " + path.toString());

    final File file = new File(path.toString());
    HttpEntity entity = null;

    // bad request
    if (!path.startsWith(baseDir) || !file.exists() || !file.canRead()) {
      WebServerLog.log(this, "File " + path.toString() + " is invalid");
      response.setStatusCode(HttpStatus.SC_NOT_FOUND);
      response.setReasonPhrase(ReasonPhrases.NOT_FOUND);

      entity = createNotFoundEntity();
      response.setEntity(entity);
      return false;
    }

    assert response.getStatusLine().getStatusCode() == HttpStatus.SC_OK;
    WebServerLog.log(this, "File " + path.toString() + " is locked and loaded!! THIS IS SPARTA!");
    if (file.isDirectory()) {
      // directory request
      String s = "Directory " + path.toString() + ":\n";
      for (final String fileName : file.list()) {
        s += fileName + "\n";
      }
      try {
        entity = new StringEntity(s);
        response.setEntity(entity);
      } catch (final UnsupportedEncodingException e) {
        System.err.println("Couldn't set response entity to directory content");
        e.printStackTrace();
      }
    } else {
      // file request
      entity = new FileEntity(file);

      response.setEntity(entity);
    }

    return file.isFile();
  }
  /** Processes request to retrieve metadata for all searches. */
  private void doGetAll(String uriTarget, Map<String, String> queryParams, HttpResponse response)
      throws IOException {

    // Get active search lists.
    List<SearchResultList> searchLists = searchManager.getActiveSearchLists();

    try {
      // Create JSON result.
      JSONArray jsonArr = new JSONArray();
      for (SearchResultList searchList : searchLists) {
        jsonArr.put(RestUtils.createSearchJson(searchList));
      }

      // Set response entity and status.
      HttpEntity entity = RestUtils.createStringEntity(jsonArr.toString());
      response.setEntity(entity);
      response.setStatusCode(HttpStatus.SC_OK);

    } catch (JSONException ex) {
      throw new IOException(ex);
    }
  }
Example #26
0
  // FIXME: rather than isError, we might was to pass in the status code to give more flexibility
  private void writeResponse(
      HttpResponse resp,
      final String responseText,
      final int statusCode,
      String responseType,
      String reasonPhrase) {
    try {
      resp.setStatusCode(statusCode);
      resp.setReasonPhrase(reasonPhrase);

      BasicHttpEntity body = new BasicHttpEntity();
      if (BaseCmd.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) {
        // JSON response
        body.setContentType(jsonContentType);
        if (responseText == null) {
          body.setContent(
              new ByteArrayInputStream(
                  "{ \"error\" : { \"description\" : \"Internal Server Error\" } }"
                      .getBytes("UTF-8")));
        }
      } else {
        body.setContentType("text/xml");
        if (responseText == null) {
          body.setContent(
              new ByteArrayInputStream("<error>Internal Server Error</error>".getBytes("UTF-8")));
        }
      }

      if (responseText != null) {
        body.setContent(new ByteArrayInputStream(responseText.getBytes("UTF-8")));
      }
      resp.setEntity(body);
    } catch (Exception ex) {
      s_logger.error("error!", ex);
    }
  }
    public synchronized void handle(HttpRequest request, HttpResponse response, HttpContext context)
        throws HttpException, IOException {
      Socket socket = ((ModifiedHttpContext) context).getSocket();

      // Parse URI and configure the Session accordingly
      final String uri = URLDecoder.decode(request.getRequestLine().getUri());

      final String sessionDescriptor =
          "v=0\r\n"
              + "o=- 15143872582342435176 15143872582342435176 IN IP4 "
              + socket.getLocalAddress().getHostName()
              + "\r\n"
              + "s=Unnamed\r\n"
              + "i=N/A\r\n"
              + "c=IN IP4 "
              + socket.getLocalAddress().getHostAddress()
              + "\r\n"
              + "t=0 0\r\n"
              + "a=tool:spydroid\r\n"
              + "a=recvonly\r\n"
              + "a=type:broadcast\r\n"
              + "a=charset:UTF-8\r\n";

      response.setStatusCode(HttpStatus.SC_OK);
      EntityTemplate body =
          new EntityTemplate(
              new ContentProducer() {
                public void writeTo(final OutputStream outstream) throws IOException {
                  OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
                  writer.write(sessionDescriptor);
                  writer.flush();
                }
              });
      body.setContentType("text/plain; charset=UTF-8");
      response.setEntity(body);
    }
 private void prepareResponse(final HttpResponse httpResponse, final String contentType) {
   httpResponse.setStatusCode(HttpStatus.SC_OK);
   httpResponse.setHeader(HttpHeader.CONTENT_TYPE.toString(), contentType);
 }
  public void handle(HttpRequest request, HttpResponse response, HttpContext argument)
      throws HttpException, IOException {
    if (BasicAuthHelper.isAuthenticated(request) == false) {
      BasicAuthHelper.unauthedResponse(response);

      return;
    }

    response.setStatusCode(HttpStatus.SC_OK);

    if (request instanceof HttpEntityEnclosingRequest) {
      HttpEntityEnclosingRequest enclosingRequest = (HttpEntityEnclosingRequest) request;

      HttpEntity entity = enclosingRequest.getEntity();

      String entityString = EntityUtils.toString(entity);

      Uri u = Uri.parse("http://localhost/?" + entityString);

      JSONObject arguments = null;

      try {
        arguments = new JSONObject(URLDecoder.decode(u.getQueryParameter("json"), "UTF-8"));
      } catch (JSONException e) {
        LogManager.getInstance(this._context).logException(e);

        response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);

        StringEntity body = new StringEntity(e.toString());
        body.setContentType("text/plain");

        response.setEntity(body);

        return;
      }

      if (arguments != null) {
        try {
          JavaScriptEngine engine = new JavaScriptEngine(this._context);

          String action = arguments.getString("action");

          if ("fetch".equals(action)) {
            if (arguments.has("keys")) {
              JSONObject result = new JSONObject();
              result.put("status", "success");

              JSONArray keys = arguments.getJSONArray("keys");

              JSONObject values = new JSONObject();

              for (int i = 0; i < keys.length(); i++) {
                String key = keys.getString(i);

                String value = engine.fetchString(key);

                values.put(key, value);
              }

              result.put("values", values);

              StringEntity body = new StringEntity(result.toString(2));
              body.setContentType("application/json");

              response.setEntity(body);

              return;
            }
          } else if ("put".equals(action)) {
            JSONArray names = arguments.names();

            for (int i = 0; i < names.length(); i++) {
              String name = names.getString(i);

              if ("action".equals(name) == false) {
                String value = arguments.getString(name);

                if (value != null) engine.persistString(name, value);
              }
            }

            JSONObject result = new JSONObject();
            result.put("status", "success");

            StringEntity body = new StringEntity(result.toString(2));
            body.setContentType("application/json");

            response.setEntity(body);

            return;
          }
        } catch (JSONException e) {
          LogManager.getInstance(this._context).logException(e);

          response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);

          StringEntity body = new StringEntity(e.toString());
          body.setContentType("text/plain");

          response.setEntity(body);

          return;
        }
      }
    }

    response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);

    StringEntity body = new StringEntity(this._context.getString(R.string.error_malformed_request));
    body.setContentType("text/plain");

    response.setEntity(body);
  }
Example #30
0
    public void handle(HttpRequest request, HttpResponse response, HttpContext httpContext)
        throws HttpException, IOException {

      SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
      final String uri = URLDecoder.decode(request.getRequestLine().getUri());
      final List<NameValuePair> params = URLEncodedUtils.parse(URI.create(uri), "UTF-8");
      String result = "Error";

      if (params.size() > 0) {
        try {

          // Set the configuration
          if (params.get(0).getName().equals("set")) {
            Editor editor = settings.edit();
            editor.putBoolean("stream_audio", false);
            editor.putBoolean("stream_video", false);
            for (Iterator<NameValuePair> it = params.iterator(); it.hasNext(); ) {
              NameValuePair param = it.next();
              if (param.getName().equals("h263") || param.getName().equals("h264")) {
                editor.putBoolean("stream_video", true);
                Session.defaultVideoQuality = VideoQuality.parseQuality(param.getValue());
                editor.putInt("video_resX", Session.defaultVideoQuality.resX);
                editor.putInt("video_resY", Session.defaultVideoQuality.resY);
                editor.putString(
                    "video_framerate", String.valueOf(Session.defaultVideoQuality.frameRate));
                editor.putString(
                    "video_bitrate", String.valueOf(Session.defaultVideoQuality.bitRate / 1000));
                editor.putString("video_encoder", param.getName().equals("h263") ? "2" : "1");
              }
              if (param.getName().equals("amr") || param.getName().equals("aac")) {
                editor.putBoolean("stream_audio", true);
                Session.defaultVideoQuality = VideoQuality.parseQuality(param.getValue());
                editor.putString("audio_encoder", param.getName().equals("amr") ? "3" : "5");
              }
            }
            editor.commit();
            result = "[]";
          }

          // Send the current streaming configuration to the client
          else if (params.get(0).getName().equals("get")) {
            result =
                "{\""
                    + HX_DETECt_TAG
                    + "\": true,"
                    + "\"streamAudio\":"
                    + settings.getBoolean("stream_audio", false)
                    + ","
                    + "\"audioEncoder\":\""
                    + (Integer.parseInt(settings.getString("audio_encoder", "3")) == 3
                        ? "AMR-NB"
                        : "AAC")
                    + "\","
                    + "\"streamVideo\":"
                    + settings.getBoolean("stream_video", true)
                    + ","
                    + "\"videoEncoder\":\""
                    + (Integer.parseInt(settings.getString("video_encoder", "2")) == 2
                        ? "H.263"
                        : "H.264")
                    + "\","
                    + "\"videoResolution\":\""
                    + settings.getInt("video_resX", Session.defaultVideoQuality.resX)
                    + "x"
                    + settings.getInt("video_resY", Session.defaultVideoQuality.resY)
                    + "\","
                    + "\"videoFramerate\":\""
                    + settings.getString(
                        "video_framerate", String.valueOf(Session.defaultVideoQuality.frameRate))
                    + " fps\","
                    + "\"videoBitrate\":\""
                    + settings.getString(
                        "video_bitrate", String.valueOf(Session.defaultVideoQuality.bitRate / 1000))
                    + " kbps\"}";
          }
        } catch (Exception e) {
          Log.e(TAG, "Error !");
          e.printStackTrace();
        }
      }

      final String finalResult = result;
      EntityTemplate body =
          new EntityTemplate(
              new ContentProducer() {
                public void writeTo(final OutputStream outstream) throws IOException {
                  OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
                  writer.write(finalResult);
                  writer.flush();
                }
              });

      response.setStatusCode(HttpStatus.SC_OK);
      body.setContentType("application/json; charset=UTF-8");
      response.setEntity(body);
    }