예제 #1
0
 /**
  * Override the update of Observer, After notify event
  *
  * @param Observable o
  * @param Object arg
  */
 @Override
 public void update(Observable o, Object arg) {
   if (o == view) {
     if (arg != null && arg.getClass().getName().equals("java.lang.String") == true) {
       String[] args = ((String) arg).split(" ");
       boolean dos = false;
       String s = null;
       for (int i = 0; i < args.length; i++) {
         if (commandsMap.containsKey(s) == true && dos == false) {
           dos = true;
         } else {
           if (dos == false) {
             if (s == null) s = args[i];
             else if (s != null) s = s + " " + args[i];
           }
         }
       }
       if (commandsMap.containsKey(s) == true) {
         commandsMap.get(s).doCommand(args);
       } else {
         view.displayString("Error");
       }
     }
   } else if (o == model) {
     if (arg != null && arg.getClass().getName().equals("java.lang.String") == true) {
       // System.out.println("presenter update = "+(String)arg);
       if (((String) arg).contains("has")) {
         view.displayClient((String) arg);
       } else {
         view.displayString((String) arg);
       }
     }
   }
 }
예제 #2
0
  public void start() {

    // Start the menuActivity.

    view.startActivity(new MenuActivity(this), null);
    view.setVisible(true);
  }
예제 #3
0
 public Controller(View view) {
   this.view = view;
   view.setConfirmButtonListener(new SaveListener());
   view.setClearUrlButtonListener(new ClearURLListener());
   view.setFindButtonListener(new FindFilesListener());
   view.setSaveAllButtonListener(new SaveAllListener());
 }
예제 #4
0
파일: Controller.java 프로젝트: higorzz/svt
  /**
   * Método que imprime o relatório da verificação do jTextArea, informa se há vírus no programa por
   * comando true/false nos métodos booleanos, e null nos métodos String ou a própria String, caso
   * ela não seje nula.
   */
  public void taRealatorioText() {

    try {
      // Começando a exibir Relatório da verificação.
      view.getTaRelatorio().setText("");
      view.getTaRelatorio().setText("#################TOOL VÍRUS TOTAL#################;\n");

      // Função  que retornará o relatório da verificação do arquivo.
      VirusTotal VT = new VirusTotal(service.getAPI_KEY());

      Set<ReportScan> Report = VT.ReportScan(SHA256);

      for (ReportScan report : Report) {

        // Exibindo no JTextArea(taRelatorio).
        view.getTaRelatorio()
            .setText(
                view.getTaRelatorio().getText()
                    + "AV: "
                    + report.getVendor()
                    + " Detected: "
                    + report.getDetected()
                    + " Update: "
                    + report.getUpdate()
                    + " Malware Name: "
                    + report.getMalwarename()
                    + ";\n");
      }
    } catch (IOException ex) {
      Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
예제 #5
0
  private boolean place(Command command) {

    if (!command.hasSecondWord() || !command.hasThirdWord()) {
      System.out.println("Please enter a valid position");
      return true;
    }

    int x = Integer.parseInt(command.getSecondWord());
    int y = Integer.parseInt(command.getThirdWord());
    Position pos = new Position(x, y);

    Piece piece = null;
    if (validMove(pos)) {
      if (turn == X) {
        piece = new X();
      } else if (turn == O) {
        piece = new O();
      }
      board.addPiece(pos, piece);

      view.update(board);
      view.display();
      return checkGameStatus(pos);
    } else {
      System.out.println("Invalid Position");
      return place(parser.getCommand());
    }
  }
예제 #6
0
 public static void main(String[] args) throws IOException {
   Model model = new Model(); // Initialize model
   controller controller = new controller(model); // Initialize controller
   View view = new View(); // Initialize view
   controller.setVistaRef(view);
   view.fijarControlador(controller);
   view.arranca(); // Show view
   model.addObserver(view);
 }
예제 #7
0
  public ControlGroup(Model model, View view) {

    this.model = model;
    this.view = view;

    ControlInterface controleInterface = new ControlInterface(model, view);
    ControlBoard controleBoard = new ControlBoard(model, view);
    ControlWall controleWall = new ControlWall(model, view);

    view.setActionListener(controleInterface, controleBoard, controleWall);
    view.display(true);
  }
예제 #8
0
파일: Controller.java 프로젝트: higorzz/svt
  /**
   * Método que dá a função do botão procurar Serve para localizar o diretório do arquivo que será
   * scaneado pelo Virus Total.
   */
  private void btProcurarOnClick() {

    // Atualizando painel de Logs com informação da operação.
    view.getTaLogs().setText("########PAINEL DE LOGS########");
    helper.attLog("\n[+] Selecionando Diretório");

    // Instanciando classe que irá procurar o diretório do arquivo.
    JFileChooser fc = new JFileChooser();

    // Restringindo busca a arquivos.
    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);

    // Atribuindo valor se foi escolhido ou não um arquivo
    int res = fc.showOpenDialog(null);

    if (res == JFileChooser.APPROVE_OPTION) {

      // Deixando botão de scan aberto para clique após escolher diretório.
      view.getBtScan().setEnabled(true);

      // Atribuindo arquivo selecionado a um File.
      File arq = fc.getSelectedFile();

      // Realizando cálculo para saber se o arquivo é menor que 20 MB
      long tam = arq.length();
      float mb = (tam / 1024) / 1024;

      if (mb < 20) {

        // Atualizando painel de Logs com informação obtida.
        helper.attLog("\n[+] Diretório Selecionado");

        // Colocando diretório no JTextField(taDiretorio).
        // que está pronto para enviar pra scan.
        String dir = arq.getAbsolutePath();
        view.getTaDiretorio().setText(dir);

      } else {

        // Atualizando painel de Logs com informação obtida.
        helper.attLog("\n[+] Diretório Selecionado Maior que 20MB");

        // Avisando usuário que o arquivo selecionado é menor que 20MB.
        JOptionPane.showMessageDialog(
            view, "Selecione um arquivo menor que 20MB", "Erro ao selecionar Arquivo", 2);
      }
    } else {

      // Atualizando painel de Logs cominformação obtida.
      helper.attLog("\n[+] Diretório não Selecionado");
    }
  }
예제 #9
0
파일: Controller.java 프로젝트: higorzz/svt
  /**
   * Método criado para quando clicar no botão copiar verificação, ele copiar os dados para
   * clipboard.
   */
  private void btCopiarOnClick() {

    // Atribuindo valor do jTextField a uma String.
    String copia = view.getTaRelatorio().getText();

    // Copiando para clipboard.
    helper.copiarClipboard(copia);

    // Mensagem copiado.
    JOptionPane.showMessageDialog(view, "Copiado com sucesso!", "Verificação Copiada", 2);

    // Desabilitando botão.
    view.getBtCopiar().setEnabled(false);
  }
예제 #10
0
  @Override
  public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    System.out.println("Action ");
    if (v.getList().getSelectedValue() == null) {
      System.out.println(">> No item selected");
      return;
    }
    String[] values = v.getList().getSelectedValue().toString().split("->");
    values[1] = values[1].substring(0, values[1].length() - 1);
    System.out.println(values[0] + values[1]);

    v.getActivTab().add(new BasketLine(values[0], 1, values[1]));
    v.update();
  }
  /**
   * @param xcomputer
   * @return
   * @author Julius Huelsmann
   * @version %I%, %U%
   * @since 1.0
   */
  private boolean addComputer(final ComputerRemote xcomputer) {

    if (xcomputer == null || computer == null) {
      View.print(getClass() + "Fehler.");
      return false;
    }

    for (int i = 0; i < computer.size(); i++) {

      //
      // In case the computer has already been added or the computer to add
      // is the local computer, return false.
      if (xcomputer.matches(computer.get(i))) {
        return false;
      } else if (xcomputer.getUid().equals(getUid())) {
        return false;
      }
    }
    Staticio.skipPort(xcomputer.getPort());
    computer.add(xcomputer);

    setChanged();
    notifyObservers(new Object[] {View.ID_UPDATE_COMPUTER, computer});
    save(Constants.getConfigLocal());
    return true;
  }
    private void removeTasklock(final String xoldid) {

      final String newId = taskLock.remove(0);

      if (!newId.equals(xoldid)) {
        View.print("Fatal error in removing task lock" + xoldid + ". removed " + newId);
      }
    }
예제 #13
0
파일: Controller.java 프로젝트: higorzz/svt
  /** Método que criará o arquivo com os dados do taRelatorio. */
  private void btArquivoOnClick() {
    JFileChooser arquivo = new JFileChooser();
    int retorno = arquivo.showSaveDialog(null);
    if (retorno == JFileChooser.APPROVE_OPTION) {

      String titulo = arquivo.getSelectedFile().getAbsolutePath() + ".txt";

      String conteudo = view.getTaRelatorio().getText();

      try {
        Arquivo arq = new Arquivo(titulo, conteudo);
        view.getBtArquivo().setEnabled(false);
      } catch (IOException ex) {
        JOptionPane.showMessageDialog(view, "Erro ao gerar Arquivo!", "Erro ao gerar Arquivo", 2);
      }
    }
  }
예제 #14
0
 @Override
 public void setValue(String edit) throws VariableWrongTypeException {
   if (Regex.getInstance().getType(edit) == GeneralType.CONSTANT) {
     View.getInstance()
         .showDialog(
             "The edited value looks like a variable, but since this is a String variable, the edit will be interpreted as a string. Use the command line to change types.");
   }
   myProperty.set(edit);
 }
  /* (non-Javadoc)
   * @see controller.Command#doCommand(java.lang.String, view.View, model.Model)
   */
  @Override
  public void doCommand(String args, View v, Model m) {

    String[] s = args.split(" ");
    char crossBy = s[0].charAt(0);
    int index = Integer.parseInt(s[1]);
    String name = s[2];
    int[][] cs = m.getCrossSection(crossBy, index, name);
    v.displayCrossSection(cs);
  }
  /**
   * Initialize a new (local) repository which will be provided to remote computers afterwards.
   *
   * @param xpath the path to the repository at local computer
   * @param xdescription Description of the repository (is stored inside the repository's
   *     configuration file)
   * @param xname the repository's name.
   * @author Julius Huelsmann
   * @version %I%, %U%
   * @since 1.0
   */
  public boolean initializeRepository(
      final String xpath, final String xdescription, final String xname) {

    //
    // Create folder and call the initialize - script.
    final boolean success = new File(xpath).mkdirs();
    final boolean success3 =
        Utils.callScript(
            Constants.UNIX_SRC_GIT_INIT,
            Constants.UNIX_DEST_GIT_INIT.getAbsolutePath(),
            xpath + " " + xname,
            true);
    if (!success3) {

      // Inform the user on the failure
      View.print(
          "Failed to create repository "
              + xname
              + " at "
              + xpath
              + ":\n"
              + "\tSuccess creating folder: "
              + success
              + "\tSuccess executing script: "
              + success3);
    } else {

      //
      // Inform the user on the success, add new repository and link to the
      // suitable vectors
      View.print("Successfully created repository " + xname + " at " + xpath + ".");
      final Repository rep = new Repository(xname, new Random().nextDouble(), xdescription);

      addRepository(rep);
      addLink(new Link(xpath, this, rep));

      //
      // inform the remote computers on the new computer
      broadcastInformation();
    }

    return success3;
  }
예제 #17
0
  /**
   * main --- where the program starts
   *
   * @param args
   */
  public static void main(String args[]) {
    // view of user's content
    ScrollingManager scrollManager = new DefaultScrollingManager();
    View display = new View(PlatformerConstants.DEFAULT_WINDOW_SIZE, scrollManager);
    scrollManager.initView(display);

    // container that will work with user's OS
    JFrame frame = new JFrame(TITLE);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // add our user interface components
    frame.getContentPane().add(display, BorderLayout.CENTER);
    // display them
    frame.pack();
    frame.setVisible(true);
    // start animation
    display.start();
    // TODO: handle iconify (reason for start/stop)
    // TODO: full screen?
  }
  /**
   * Handle HI message.
   *
   * @param xaddr
   */
  public final void handleHi(final String xaddr, final String xuid) {
    for (int i = 0; i < computer.size(); i++) {
      if (computer.get(i).getAddress().equals(xaddr) && computer.get(i).getUid().equals(xuid)) {

        computer.get(i).setContacted();
      } else if (computer.get(i).getAddress().equals(xaddr)
          || computer.get(i).getUid().equals(xuid)) {
        View.print("Wrong computer UID or address.");
        computer.get(i).setConnected(false);
      }
    }
  }
예제 #19
0
파일: Controller.java 프로젝트: higorzz/svt
  /**
   * Método que dá a função ao clicar no botão 'Scanear Verificação', ela que manda o arquivo para
   * scan no vírus total.
   */
  private void btScanOnClick() {
    // Zerando taRelatorio.
    view.getTaRelatorio().setText("Tool Vírus Total Desktop");

    // Desabilitando botões
    view.getBtCopiar().setEnabled(false);
    view.getBtArquivo().setEnabled(false);

    // Atualizando painel de Logs com informação obtida.
    helper.attLog("\n[+] Começando Scan");

    // Desabilidando botão Procurar, até que o relatório seje imprimido.
    view.getBtProcurar().setEnabled(false);

    // Chamando função que envia arquivo para verificação.
    ProcessarThead pt = new ProcessarThead();
    pt.start();

    // Atualizando painel de Logs com últimas informações do Scan.
    helper.attLog(
        "\n[+] Scan Concluído\n[+] Abra no navegadou ou aguarde"
            + " 2 minutos\n[+] E aparecerá o relatório do scan");

    // Habilitando/Desabilitando botôes.
    view.getBtOpen().setEnabled(true);
    view.getBtScan().setEnabled(false);

    new Cronometro(view).go();

    // Chamando função que imprimirá dados da verificação após 2 minutos.
    Temporizador temporizador = new Temporizador(120);
  }
  /** Force a packet to be sent. */
  public void sendPacket() {
    // Also save stuff to a player's local hard-drive.

    if (activationEvent) {
      View MyView = MyHacker.getView();
      Object[] send =
          new Object[] {new Integer(activationID), new Integer(activationType), MyHacker.getIP()};
      MyView.addFunctionCall(
          new RemoteFunctionCall(Hacker.HACKTENDO_PLAYER, "hacktendoActivate", send));
    } else if (targetEvent) {
      View MyView = MyHacker.getView();
      Object[] send = null;
      if (playerSprite != null)
        send =
            new Object[] {
              new Integer(targetX),
              new Integer(targetY),
              MyHacker.getIP(),
              new Integer(playerSprite.getX()),
              new Integer(playerSprite.getY())
            };
      else
        send =
            new Object[] {
              new Integer(targetX),
              new Integer(targetY),
              MyHacker.getIP(),
              new Integer(targetX),
              new Integer(targetY)
            };

      MyView.addFunctionCall(
          new RemoteFunctionCall(Hacker.HACKTENDO_PLAYER, "hacktendoTarget", send));
    }

    activationEvent = false;
    targetEvent = false;
  }
예제 #21
0
  // Create all the Objects needed for a new Game and add them to the pl ParameterList.
  private void startGame() {

    mix();
    ParameterList pl = new ParameterList();
    pl.addParameter(GameActivity.PARAMS_PIC, model.getImage());
    pl.addParameter(GameActivity.PARAMS_BLACK, model.getBlack());
    pl.addParameter(GameActivity.PARAMS_SORT, model.getSort());
    pl.addParameter(GameActivity.PARAMS_NEIGHBORS, model.getNeighbors());
    pl.addParameter(GameActivity.PARAMS_TIME, model.getRoundTime());
    gameActivity = new GameActivity(this);
    model.setRoundTime(0);
    view.startActivity(gameActivity, pl);
    if (null == counter) {
      counter = new Counter(model, gameActivity);
      counter.start();
    } else counter.setActivity(gameActivity);
  }
  /**
   * Save the instance of {@link #ComputerLocal(String)} to the specified location.
   *
   * @param xconfigLocal the specified location
   * @author Julius Huelsmann
   * @version %I%, %U%
   * @since 1.0
   */
  public void save(final File xconfigLocal) {
    final GitThread t = gitThread;
    gitThread = null;
    ObjectOutputStream oos;
    try {
      FileOutputStream fos = new FileOutputStream(xconfigLocal);
      oos = new ObjectOutputStream(fos);
      oos.writeObject(this);
      oos.flush();
      oos.close();
    } catch (IOException e) {
      View.print(
          "The configuration could not be saved because the " + "folder does not exist: " + e);
    }

    gitThread = t;
  }
  /**
   * @param xlink
   * @return
   * @author Julius Huelsmann
   * @version %I%, %U%
   * @since 1.0
   */
  private boolean addLink(final Link xlink) {

    if (xlink == null || combination == null) {
      View.print(getClass() + "Fehler.");
      return false;
    }

    for (int i = 0; i < combination.size(); i++) {
      if (xlink.matches(combination.get(i))) {
        return false;
      }
    }
    combination.add(xlink);
    setChanged();
    notifyObservers(new Object[] {View.ID_UPDATE_LINK, combination});
    save(Constants.getConfigLocal());
    return true;
  }
  /**
   * @param xrepository
   * @return
   * @author Julius Huelsmann
   * @version %I%, %U%
   * @since 1.0
   */
  private boolean addRepository(final Repository xrepository) {

    if (xrepository == null || repositories == null) {
      View.print(getClass() + "Fehler.");
      return false;
    }

    for (int i = 0; i < repositories.size(); i++) {
      if (xrepository.matches(repositories.get(i))) {
        return false;
      }
    }
    repositories.add(xrepository);
    setChanged();
    notifyObservers(new Object[] {View.ID_UPDATE_REPO, repositories});
    save(Constants.getConfigLocal());
    return true;
  }
예제 #25
0
  /**
   * Constructor
   *
   * @param view
   * @param model
   */
  public Presenter(View view, Model model) {
    this.view = view;
    this.model = model;
    this.properties = new Properties();
    properties.defaultProp();
    model.setProperties(properties);

    this.commandMap = new HashMap<String, Command>();
    commandMap.put("dir", new Dir(this));
    commandMap.put("generate", new Generate(this));
    commandMap.put("display", new Display(this));
    commandMap.put("save", new Save(this));
    commandMap.put("load", new Load(this));
    commandMap.put("maze", new MazeSize(this));
    commandMap.put("file", new FileSize(this));
    commandMap.put("solve", new Solve(this));
    commandMap.put("move", new Moves(this));
    commandMap.put("exit", new Exit(this));

    view.setCommand(commandMap);
  }
  /**
   * This function is called once for starting to scan for other copies of the program inside the
   * local network. It generates {@value #amountOfThreads} threads by calling the private method
   * {@link #getNewClient(int, int, int, ComputerLocal)}.
   *
   * @param xcl instance of the Local Computer class that handles the received information -
   *     strings.
   * @author Julius Huelsmann
   * @version %I%, %U%
   * @since 1.0
   */
  public static void startScanning(final ComputerLocal xcl) {

    //
    // In case local testing is enabled, do not scan for remote computers
    // but use the local IP and given port.
    if (Constants.isLocalTesting()) {

      requestLocalServerInformation(xcl);
    } else {

      //
      // Initialize the Vector which contains information on the current
      // process of each XTreaead that is created in the following.
      currentProgress = new Vector<Integer>();

      //
      // Print information message and compute the range of one thread.
      // Afterwards initialize #amountOfThreads threads by calling the method
      // #getNewClient.
      View.print("Start scanning for clients in " + amountOfThreads + " Threads.");
      final int threadRange =
          (Constants.globalPortEnd - Constants.globalPortStart) / amountOfThreads;
      int sum = Constants.globalPortStart;
      for (int i = 0; i < amountOfThreads; i++) {

        // Add the lower range of scanning of the client to the progress vector
        // and generate upper range by adding the threadRange.
        currentProgress.add(sum);
        int sump = sum + threadRange;

        // Create new client and set the sum - integer to the upper range of
        // the current process.
        getNewClient(i, sum, sump, xcl);
        sum = sump;
      }
    }
  }
  /**
   * @param xia
   * @param xport
   * @author Julius Huelsmann
   * @version %I%, %U%
   * @since 1.0
   */
  public final void generateAddclientTask(final InetAddress xia, final int xport) {

    // If the address - port combination is unknown, generate new task to add
    // the client
    boolean found = false;
    for (int i = 0; i < computer.size(); i++) {
      if (computer.get(i).getAddress().equals(xia.getHostAddress())) {
        found = true;

        if (xport != computer.get(i).getPort()) {
          computer.get(i).setPort(xport);
          View.print(
              "Stored wrong port identifier for client with ip " + computer.get(i).getAddress());
        }
      }
    }

    //
    // In case the remote computer has not already been added, create new
    // instance of TaskAddclient.
    if (!found) {
      taskList.add(new TaskAddclient(this, xia, xport));
    }
  }
예제 #28
0
 @Test
 public void testWelcomeMessage() {
   View view = View.getView();
   view.displayWelcomeMessage();
   assertEquals(String.format(MESSAGE_WELCOME), stringOutput.toString());
 }
예제 #29
0
  /** Tell the view to create new message box */
  public void process(View view, Model model) {
    String message = "<html>jNetwalk<br>by Jakub Maleszewski</html>";
    String title = "About";

    view.showMessage(message, title);
  }
예제 #30
0
  public void returnData(String activityClass, ParameterList params) {

    // A new ParameterList for starting new Activitys
    ParameterList pl = new ParameterList();

    // If MenuActivity returns data.
    if (activityClass.equals(MenuActivity.class.getSimpleName())) {

      // Switches based on the selected entry.
      switch ((Integer) params.getValue(MenuActivity.PARAM_MENUITEM)) {

          // When new game is clicked.
        case MainMenuModel.NEW_GAME:

          // Add the actual playername to the PArameters.
          pl.addParameter(PlayernameActivity.PARAMS_NAME, model.getPlayerName());

          // Start a new PlayernameActivity.
          view.startActivity(new PlayernameActivity(this), pl);

          break;

          // When new highscore is clicked.
        case MainMenuModel.HIGHSCORE:
          ArrayList<String> s = new ArrayList<String>();
          s.add("Hans");
          s.add("Peter");
          s.add("Olaf");

          ArrayList<Integer> i = new ArrayList<Integer>();
          i.add(20);
          i.add(30);
          i.add(120);

          pl.addParameter(HighscoreActivity.PARAM_USERS, s);
          pl.addParameter(HighscoreActivity.PARAM_SCORES, i);

          view.startActivity(new HighscoreActivity(this), pl);
          break;

          // When options is clicked.
        case MainMenuModel.OPTIONS:
          pl.addParameter(OptionsActivity.PARAMS_DIF, model.getDifficulty());
          pl.addParameter(OptionsActivity.PARAMS_SIZE, model.getSize());

          view.startActivity(new OptionsActivity(this), pl);
          break;

          // When credits is clicked.
        case MainMenuModel.CREDITS:
          view.startActivity(new CreditsActivity(this), null);
          break;

          // When quit is clicked.
        case MainMenuModel.QUIT:
          view.startActivity(new QuitActivity(this), null);
          break;
      }
    }

    // If QuitActivity returns data.
    else if (activityClass.equals(QuitActivity.class.getSimpleName())) {
      if ((Boolean) params.getValue(QuitActivity.RETURN_QUIT)) System.exit(0);
      start();
    }

    // If HighscoreActivity returns data.
    else if (activityClass.equals(HighscoreActivity.class.getSimpleName())) start();

    // If CreditsActivity returns data.
    else if (activityClass.equals(CreditsActivity.class.getSimpleName())) start();

    // If ImageLoader returns data.
    else if (activityClass.equals(ImageLoder.class.getSimpleName())) {

      pl.addParameter(GalleryActivity.PARAM_PICS, params.getValue(ImageLoder.RETURN_PICS));
      view.startActivity(new GalleryActivity(this), params);
    }

    // If PlayernameActivity returns data.
    else if (activityClass.equals(PlayernameActivity.class.getSimpleName())) {
      model.setPlayerName((String) params.getValue(PlayernameActivity.RETURN_NAME));
      if ((Boolean) params.getValue(PlayernameActivity.RETURN_BACK)) start();
      else if ((Boolean) params.getValue(PlayernameActivity.RETURN_GALLARY)) {
        pl.addParameter(LoadingActivity.PARAM_MESSAGE, "Loading Gallery");
        view.startActivity(new LoadingActivity(this), pl);
        ImageLoder il = new ImageLoder(this, galleryModel);
        il.start();
      } else {
        view.startActivity(new ChoosePicActivity(this), params);
      }

    }

    // If ChoosePicActivity returns data.
    else if (activityClass.equals(ChoosePicActivity.class.getSimpleName())) {
      try {
        pl.addParameter(LoadingActivity.PARAM_MESSAGE, "Loading Image");
        // view.startActivity(new LoadingActivity(this), pl);
        Image image =
            ImageIO.read(new File((String) params.getValue(ChoosePicActivity.RETURN_PATH)));
        model.setImage(
            Graphics.subImage(Graphics.scale(image, 800, 600), model.getSize(), 700, 400));
        startGame();
      } catch (IOException e) {
        view.startActivity(new MenuActivity(this), null);
      }
    }

    // If GalleryActivity returns data.
    else if (activityClass.equals(GalleryActivity.class.getSimpleName())) {
      Image image =
          Graphics.scale(
              (Image) params.getValue(GalleryActivity.RETURN_PIC),
              view.getWidth(),
              view.getHeight());
      model.setImage(Graphics.subImage(Graphics.scale(image, 800, 600), model.getSize(), 700, 400));
      startGame();
    }

    // If OptionsActivity returns data.
    else if (activityClass.equals(OptionsActivity.class.getSimpleName())) {
      model.setDifficulty((Integer) params.getValue(OptionsActivity.RETURN_DIF));
      model.setSize((Integer) params.getValue(OptionsActivity.RETURN_SIZE));
      view.startActivity(new MenuActivity(this), null);
    }

    // If GameActivity returns data.
    else if (activityClass.equals(GameActivity.class.getSimpleName())) {

      // if returnbutton ore shufflebutton is clicked.
      if (params.getValue(GameActivity.RETURN_SELECTED).equals(GameActivity.RETURN_BACK)) {
        view.startActivity(new MenuActivity(this), null);
        return;
      }
      if (params.getValue(GameActivity.RETURN_SELECTED).equals(GameActivity.RETURN_SHUFFLE)) {
        startGame();
        return;
      }

      // Change the black picture with the selected one.
      int[] sort = model.getSort();
      int temp = sort[model.getBlack()];
      sort[model.getBlack()] = sort[(Integer) params.getValue(GameActivity.RETURN_SELECTED)];
      sort[(Integer) params.getValue(GameActivity.RETURN_SELECTED)] = temp;

      // Set the new order to the model.
      model.setBlack((Integer) params.getValue(GameActivity.RETURN_SELECTED));
      model.setSort(sort);
      model.setNeighbors(getNeighbors());

      // Check if the pictures are in the correct order.
      boolean t = true;
      for (int i = 0; i < sort.length; i++) {
        if (i != sort[i]) {
          t = false;
          break;
        }
      }
      // If correct order.
      if (t) {
        pl.addParameter(WonActivity.PARAMS_NAME, model.getPlayerName());
        pl.addParameter(WonActivity.PARAMS_TIME, model.getRoundTime());
        view.startActivity(new WonActivity(this), pl);
      }
      // If order is incorrect.
      else {

        // Set all the parameters needed for the new GameActivity.
        pl.addParameter(GameActivity.PARAMS_PIC, model.getImage());
        pl.addParameter(GameActivity.PARAMS_BLACK, model.getBlack());
        pl.addParameter(GameActivity.PARAMS_SORT, model.getSort());
        pl.addParameter(GameActivity.PARAMS_NEIGHBORS, model.getNeighbors());
        pl.addParameter(GameActivity.PARAMS_TIME, model.getRoundTime());

        view.startActivity(gameActivity, pl);
      }

    }

    // If WonActivity returns data.
    else if (activityClass.equals(WonActivity.class.getSimpleName())) start();
  }