@Override
  public void handleMessage(Message msg) {
    super.handleMessage(msg);
    if (msg.obj instanceof ServerRequest) {
      ServerRequest req = (ServerRequest) msg.obj;
      try {

        // Open URL Connection with the specified Request Method
        HttpURLConnection conn = (HttpURLConnection) new URL(req.mUrl).openConnection();
        conn.setRequestMethod(req.mReqMethod);

        // Pass parameters, if any
        for (String key : req.mParams.keySet()) {
          conn.setRequestProperty(key, req.mParams.get(key));
        }

        // If we have parameters, we have output
        if (req.hasOutput()) {
          conn.setDoOutput(true);
          OutputStream stream = conn.getOutputStream();
          stream.write(req.getOutput().getBytes());
          stream.flush();
        } else {
          conn.connect();
        }

        // Check to see if there is a response error code
        int responseCode = conn.getResponseCode();
        if (responseCode < 200 || responseCode >= 300) {
          Log.e(TAG, "Connection failed with error " + responseCode);
          return;
        }

        // Build a string from the output if we have no errors
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String y = "";
        while ((y = reader.readLine()) != null) {
          sb.append(y);
        }

        // Pass back any information we have
        if (req.mResponseHandler != null) {
          Message responseMessage = Message.obtain();
          responseMessage.obj = new ServerResponse(sb.toString(), req.mType);
          req.mResponseHandler.sendMessage(responseMessage);
        } else {
          Log.i(TAG, "No response handler available");
          return;
        }
      } catch (MalformedURLException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
    } else {
      Log.e(TAG, "Error: Message is not a ServerRequest");
      return;
    }
  }
 public void fetchDummyArticle(QueryListener activity) {
   /*UTRequest(<activity to send back info>,<host>,<port to connect to on host>)*/
   ServerRequest req = new ServerRequest(activity);
   /*make a non-blocking request to server. Data returned will be through
    * the receiveResult(result) method below. Any activity that wants to
    * use UTRequest then it must subscribe to the QueryListener interface.*/
   req.execute("h3ll0");
 }
  @Override
  public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) {
    ServerRequest tenant = new ServerRequest();
    if (description != null) tenant.description = description;
    if (name != null) tenant.name = name;
    tenant.enabled = enabled;

    return bindToRequest(request, ImmutableMap.of("tenant", tenant));
  }
 private void registerUser(User registeredUser) {
   ServerRequest serverRequest = new ServerRequest(this);
   serverRequest.storeUserDataInBackground(
       registeredUser,
       new GetUserCallback() {
         @Override
         public void done(User returnedUser) {
           Toast.makeText(
                   RegisterActivity.this, "You've been registered successully!", Toast.LENGTH_LONG)
               .show();
           startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
         }
       });
 }
 private void authenticate(User user) {
   ServerRequest serverRequest = new ServerRequest(this);
   serverRequest.fetchUserDataBackground(
       user,
       new GetUserCallback() {
         @Override
         public void done(User returnedUser) {
           if (returnedUser == null) {
             showErrorMessage();
           } else {
             logUserIn(returnedUser);
           }
         }
       });
 }
  // This listen to login button - dont know exactly how it works, but for now it is fine -
  // something with onclinck in button
  public void sendMessage(View view) {
    usertxt = user.getText().toString();
    passwordtxt = password.getText().toString();

    params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("username", usertxt));
    params.add(new BasicNameValuePair("password", passwordtxt));
    JSONObject json = null;
    sr = new ServerRequest();
    json =
        sr.getJSON(
            "http://10.9.146.239:1317/mobileapi/login?username="******"&pass="******"text", json.toString());
    if (json != null) {
      try {
        if (json.getString("error").isEmpty()) {
          String jsonstr = json.getJSONObject("data").getString("fullName");
          // String jsonstr = json.toString();
          Intent profactivity = new Intent(this, Destinations.class);
          profactivity.putExtra("name", jsonstr);
          startActivity(profactivity);
        } else {
          Toast.makeText(getApplication(), json.getString("error"), Toast.LENGTH_LONG).show();
        }

      } catch (JSONException e) {
        e.printStackTrace();
      }
    }
  }
 @Override
 public void bindToRequest(HttpRequest request, Map<String, String> postParams) {
   ServerRequest server =
       new ServerRequest(
           checkNotNull(postParams.get("name"), "name parameter not present"),
           Integer.parseInt(
               checkNotNull(postParams.get("imageId"), "imageId parameter not present")),
           Integer.parseInt(
               checkNotNull(postParams.get("flavorId"), "flavorId parameter not present")));
   if (metadata.size() > 0) server.metadata = metadata;
   if (files.size() > 0) server.personality = files;
   if (sharedIpGroupId != null) server.sharedIpGroupId = this.sharedIpGroupId;
   if (publicIp != null) {
     server.addresses = new Addresses();
     server.addresses.getPublicAddresses().add(publicIp);
     server.addresses.setPrivateAddresses(null);
   }
   bindToRequest(request, ImmutableMap.of("server", server));
 }
  /**
   * {@inheritDoc}
   *
   * @see com.corona.context.InjectMethod#invoke(com.corona.context.ContextManager,
   *     java.lang.Object)
   */
  @SuppressWarnings({"unchecked", "rawtypes"})
  @Override
  public Object invoke(final ContextManager contextManager, final Object component) {

    // find server by server name from current context and make sure it is defined
    Server server = contextManager.get(Server.class, this.serverName);
    if (server == null) {
      this.logger.error(
          "Server [{0}] isn't registered in context, should define it first", this.serverName);
      throw new ValueException(
          "Server [{0}] isn't registered in context, should define it first", this.serverName);
    }

    // transform client input stream into request object
    ServerRequest request = null;
    try {
      request = this.getRequest(contextManager, server);
    } catch (RemoteException e) {
      this.logger.error(
          "Fail to open client input stream or transform stream to server request object", e);
      return new ServerInternalErrorResponse(
          server, "Fail to get server request object: " + e.getMessage());
    }

    // execute producing method according to client request and return it in order to create server
    // response
    try {
      switch (request.getCode()) {
        case Constants.REQUEST.EXECUTE:
          Object outcome = this.execute(component, (ServerExecuteRequest) request);
          if (outcome != null) {
            return new ServerExecutedResponse(
                server,
                server.getToken(((ServerExecuteRequest) request).getToken()),
                this.getMarshaller(),
                outcome);
          } else {
            return new ServerExecutedResponse(
                server, server.getToken(((ServerExecuteRequest) request).getToken()), null, null);
          }

        case Constants.REQUEST.LOGIN:
          if (server.isSupportedVersion(((ServerLoginRequest) request).getClientLibraryVersion())) {
            String token = this.login(component, (ServerLoginRequest) request);
            if (token != null) {
              return new ServerLoggedInResponse(server, token);
            } else {
              return new ServerCantLoggedInResponse(
                  server, "Invalid user name or password to log in");
            }
          } else {
            return new ServerCantLoggedInResponse(server, "Client libray version is not supported");
          }

        case Constants.REQUEST.LOGOUT:
          this.logout(component, (ServerLogoutRequest) request);
          return new ServerLoggedOutResponse(server);

        default:
          return new ServerInvalidActionResponse(
              server, ((ServerInvalidActionRequest) request).getInvalidCode());
      }
    } catch (Exception e) {
      return new ServerFailExecuteResponse(server, e);
    }
  }
  /**
   * @param contextManager the current context manager
   * @param server the server
   * @return the request
   * @throws RemoteException if fail to translate stream to request object
   */
  private ServerRequest getRequest(final ContextManager contextManager, final Server server)
      throws RemoteException {

    // get input stream from
    InputStream input;
    try {
      input = contextManager.get(HttpServletRequest.class).getInputStream();
      input = new GZIPInputStream(input);
    } catch (IOException e) {
      this.logger.error("Fail to open client servlet request as GZIP input stream", e);
      throw new RemoteException("Fail to open client servlet request as GZIP input stream", e);
    }

    // read identifier and check whether this identifier is valid or not
    int identifier;
    try {
      identifier = input.read();
    } catch (IOException e) {
      this.logger.error("Fail to read identifier from client input stream", e);
      throw new RemoteException("Fail to read identifier from client input stream", e);
    }

    if (identifier == -1) {
      this.logger.error("Should can read identifier but client input stream is empty");
      throw new RemoteException("Should can read identifier but client input stream is empty");
    } else if (((byte) identifier) != Constants.IDENTIFIER) {
      this.logger.error("Invalid identifier [{0}] read from client input stream", identifier);
      throw new RemoteException(
          "Invalid identifier [{0}] read from client input stream", identifier);
    }

    // read action code and make sure it is read from client stream
    int action;
    try {
      action = input.read();
    } catch (IOException e) {
      this.logger.error("Fail to read action code from client input stream", e);
      throw new RemoteException("Fail to read action code from client input stream", e);
    }

    if (action == -1) {
      this.logger.error("Should can read action code but client input stream is empty");
      throw new RemoteException("Should can read action code but client input stream is empty");
    }

    // create request according to action code
    ServerRequest request;
    switch (action) {
      case Constants.REQUEST.EXECUTE:
        request = new ServerExecuteRequest(server, this.getUnmarshaller());
        break;

      case Constants.REQUEST.LOGIN:
        request = new ServerLoginRequest(server);
        break;

      case Constants.REQUEST.LOGOUT:
        request = new ServerLogoutRequest(server);
        break;

      default:
        request = new ServerInvalidActionRequest(server, (byte) action);
        break;
    }

    // read request specified data from client input stream
    request.read(input);
    return request;
  }
Exemple #10
0
 // called by login button
 public void getAccountInfo(View view) throws InterruptedException {
   String usernameString = editUsername.getText().toString();
   String passwordString = editPassword.getText().toString();
   ServerRequest servReq = new ServerRequest(this);
   servReq.login(usernameString, passwordString);
 }