Example #1
0
  /** @param args the command line arguments */
  public static void main(String args[]) {
    /*
     * Set the Nimbus look and feel
     */
    // <editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /*
     * If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. For details see
     * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
     */
    try {
      for (javax.swing.UIManager.LookAndFeelInfo info :
          javax.swing.UIManager.getInstalledLookAndFeels()) {
        if ("Nimbus".equals(info.getName())) {
          javax.swing.UIManager.setLookAndFeel(info.getClassName());
          break;
        }
      }
    } catch (ClassNotFoundException ex) {
      java.util.logging.Logger.getLogger(SOSGenerator.class.getName())
          .log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
      java.util.logging.Logger.getLogger(SOSGenerator.class.getName())
          .log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
      java.util.logging.Logger.getLogger(SOSGenerator.class.getName())
          .log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
      java.util.logging.Logger.getLogger(SOSGenerator.class.getName())
          .log(java.util.logging.Level.SEVERE, null, ex);
    }
    // </editor-fold>
    Logger.getRootLogger()
        .addAppender(
            new ConsoleAppender(
                new org.apache.log4j.PatternLayout("%d - %-5p - %-20c (%C [%L]) - %m%n")));
    GlobalOptions.setSelectedServer("de43");
    ProfileManager.getSingleton().loadProfiles();
    GlobalOptions.setSelectedProfile(ProfileManager.getSingleton().getProfiles("de43")[0]);
    DataHolder.getSingleton().loadData(false);
    GlobalOptions.loadUserData();
    /*
     * Create and display the form
     */
    java.awt.EventQueue.invokeLater(
        new Runnable() {

          public void run() {
            new SOSGenerator().setVisible(true);
          }
        });
  }
Example #2
0
  /**
   * Constructor.
   *
   * @param rq request
   * @param rs response
   * @param servlet calling servlet instance
   * @throws IOException I/O exception
   */
  public HTTPContext(
      final HttpServletRequest rq, final HttpServletResponse rs, final BaseXServlet servlet)
      throws IOException {

    req = rq;
    res = rs;
    params = new HTTPParams(this);

    method = rq.getMethod();

    final StringBuilder uri = new StringBuilder(req.getRequestURL());
    final String qs = req.getQueryString();
    if (qs != null) uri.append('?').append(qs);
    log('[' + method + "] " + uri, null);

    // set UTF8 as default encoding (can be overwritten)
    res.setCharacterEncoding(UTF8);
    segments = decode(toSegments(req.getPathInfo()));

    // adopt servlet-specific credentials or use global ones
    final GlobalOptions mprop = context().globalopts;
    user = servlet.user != null ? servlet.user : mprop.get(GlobalOptions.USER);
    pass = servlet.pass != null ? servlet.pass : mprop.get(GlobalOptions.PASSWORD);

    // overwrite credentials with session-specific data
    final String auth = req.getHeader(AUTHORIZATION);
    if (auth != null) {
      final String[] values = auth.split(" ");
      if (values[0].equals(BASIC)) {
        final String[] cred = org.basex.util.Base64.decode(values[1]).split(":", 2);
        if (cred.length != 2) throw new LoginException(NOPASSWD);
        user = cred[0];
        pass = cred[1];
      } else {
        throw new LoginException(WHICHAUTH, values[0]);
      }
    }
  }
  private static String replaceHeadFootVariables(
      String pBlock, String pPlanName, List<Attack> pAttacks) {
    String result = pBlock;
    // set creator
    Tribe user = GlobalOptions.getSelectedProfile().getTribe();
    if (user != null) {
      result = result.replaceAll(CREATOR, Matcher.quoteReplacement(user.getName()));
    } else {
      result = result.replaceAll(CREATOR, "-");
    }
    // set planname
    if (pPlanName != null) {
      result = result.replaceAll(PLANNAME, EscapeChars.forHTML(pPlanName));
    } else {
      result = result.replaceAll(PLANNAME, "-");
    }
    // set attack count
    NumberFormat nf = NumberFormat.getInstance();
    nf.setMinimumFractionDigits(0);
    nf.setMinimumFractionDigits(0);
    result = result.replaceAll(ATTACK_COUNT, nf.format(pAttacks.size()));
    // set attack count
    String server = GlobalOptions.getSelectedServer();
    if (server != null) {
      result = result.replaceAll(SERVER, server);
    } else {
      result = result.replaceAll(SERVER, "-");
    }
    // replace version
    result =
        result.replaceAll(VERSION, Double.toString(Constants.VERSION) + Constants.VERSION_ADDITION);
    // replace creation date
    SimpleDateFormat f = new SimpleDateFormat("dd.MM.yyyy 'um' HH:mm:ss 'Uhr'");
    result = result.replaceAll(CREATION_DATE, f.format(new Date(System.currentTimeMillis())));

    return result;
  }
Example #4
0
  public MarioComponent(int width, int height) {
    adjustFPS();

    this.setFocusable(true);
    this.setEnabled(true);
    this.width = width;
    this.height = height;

    Dimension size = new Dimension(width, height);

    setPreferredSize(size);
    setMinimumSize(size);
    setMaximumSize(size);

    setFocusable(true);

    if (this.cheatAgent == null) {
      this.cheatAgent = new CheaterKeyboardAgent();
      this.addKeyListener(cheatAgent);
    }

    GlobalOptions.registerMarioComponent(this);
  }
  public static void loadCustomTemplate() {
    try {
      HEADER = "";
      BLOCK = "";
      FOOTER = "";

      String header = GlobalOptions.getProperty("attack.template.header");
      String block = GlobalOptions.getProperty("attack.template.block");
      String footer = GlobalOptions.getProperty("attack.template.footer");
      if (header == null) {
        header = "ThisFileDoesNotExist";
      }
      if (block == null) {
        block = "ThisFileDoesNotExist";
      }
      if (footer == null) {
        footer = "ThisFileDoesNotExist";
      }
      File fHeader = new File(header);
      File fBlock = new File(block);
      File fFooter = new File(footer);

      BufferedReader r = null;
      if (!fHeader.exists()) {
        r =
            new BufferedReader(
                new InputStreamReader(
                    AttackPlanHTMLExporter.class.getResourceAsStream(
                        "/de/tor/tribes/tmpl/attack_header.tmpl")));
      } else {
        r = new BufferedReader(new InputStreamReader(new FileInputStream(header)));
      }

      String line = "";
      while ((line = r.readLine()) != null) {
        HEADER += line + "\n";
      }
      r.close();

      if (!fBlock.exists()) {
        r =
            new BufferedReader(
                new InputStreamReader(
                    AttackPlanHTMLExporter.class.getResourceAsStream(
                        "/de/tor/tribes/tmpl/attack_block.tmpl")));
      } else {
        r = new BufferedReader(new InputStreamReader(new FileInputStream(block)));
      }
      line = "";
      while ((line = r.readLine()) != null) {
        BLOCK += line + "\n";
      }
      r.close();

      if (!fFooter.exists()) {
        r =
            new BufferedReader(
                new InputStreamReader(
                    AttackPlanHTMLExporter.class.getResourceAsStream(
                        "/de/tor/tribes/tmpl/attack_footer.tmpl")));
      } else {
        r = new BufferedReader(new InputStreamReader(new FileInputStream(footer)));
      }
      line = "";
      while ((line = r.readLine()) != null) {
        FOOTER += line + "\n";
      }
      r.close();
    } catch (Exception e) {
      logger.error("Failed to read custom templates. Switch to default template.", e);
      loadDefaultTemplate();
    }
  }
  public static void doExport(File pHtmlFile, String pPlanName, List<Attack> pAttacks) {
    if (TEMPLATE_ERROR) {
      logger.warn("Skip writing HTML file due to TEMPLATE_ERROR flag");
      return;
    }
    SimpleDateFormat f = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
    StringBuffer result = new StringBuffer();
    // append header
    result.append(replaceHeadFootVariables(HEADER, pPlanName, pAttacks));

    int cnt = 0;
    for (Attack a : pAttacks) {
      String b = BLOCK;
      // <editor-fold defaultstate="collapsed" desc="Replace DIV-IDs">
      if (cnt % 2 == 0) {
        b = b.replaceAll(DIV_CLASS, "odd_div");
      } else {
        b = b.replaceAll(DIV_CLASS, "even_div");
      }
      b = b.replaceAll(ID, Integer.toString(cnt));
      // </editor-fold>

      // <editor-fold defaultstate="collapsed" desc="Replace Unit Icons">
      UnitHolder unit = a.getUnit();
      b =
          b.replaceAll(
              UNIT,
              "<img src=\"http://www.dsworkbench.de/DSWorkbench/export/"
                  + unit.getPlainName()
                  + ".png\">");

      switch (a.getType()) {
        case Attack.CLEAN_TYPE:
          {
            b =
                b.replaceAll(
                    TYPE, "<img src=\"http://www.dsworkbench.de/DSWorkbench/export/att.png\">");
            break;
          }
        case Attack.SNOB_TYPE:
          {
            b =
                b.replaceAll(
                    TYPE, "<img src=\"http://www.dsworkbench.de/DSWorkbench/export/snob.png\">");
            break;
          }
        case Attack.FAKE_TYPE:
          {
            b =
                b.replaceAll(
                    TYPE, "<img src=\"http://www.dsworkbench.de/DSWorkbench/export/fake.png\">");
            break;
          }
        case Attack.FAKE_DEFF_TYPE:
          {
            b =
                b.replaceAll(
                    TYPE,
                    "<img src=\"http://www.dsworkbench.de/DSWorkbench/export/def_fake.png\">");
            break;
          }
        case Attack.SUPPORT_TYPE:
          {
            b =
                b.replaceAll(
                    TYPE, "<img src=\"http://www.dsworkbench.de/DSWorkbench/export/ally.png\">");
            break;
          }
        default:
          {
            b = b.replaceAll(TYPE, "-");
            break;
          }
      }
      // </editor-fold>

      String baseURL = ServerManager.getServerURL(GlobalOptions.getSelectedServer()) + "/";

      // <editor-fold defaultstate="collapsed" desc=" replace source tribe and ally">
      Tribe sourceTribe = a.getSource().getTribe();
      String sourceTribeName = "";
      String sourceTribeLink = "";
      String sourceAllyName = "";
      String sourceAllyTag = "";
      String sourceAllyLink = "";
      String sourceVillageName = "";
      String sourceVillageCoord = "";
      String sourceVillageLink = "";

      if (sourceTribe == null) {
        // tribe is null, so it is a barbarian village
        sourceTribeName = "Barbaren";
        sourceAllyName = "Barbaren";
      } else {
        sourceTribeLink = baseURL;
        sourceTribeLink += "guest.php?screen=info_player&id=" + sourceTribe.getId();
        sourceTribeName = sourceTribe.getName();

        // replace source tribe
        Ally sourceAlly = sourceTribe.getAlly();
        if (sourceAlly == null) {
          // tribe has no ally
          sourceAllyName = "Kein Stamm";
        } else {
          // ally valid
          sourceAllyName = sourceAlly.getName();
          sourceAllyTag = sourceAlly.getTag();
          sourceAllyLink = baseURL;
          sourceAllyLink += "guest.php?screen=info_ally&id=" + sourceAlly.getId();
        }
      }
      // replace source village
      sourceVillageLink = baseURL;
      sourceVillageLink += "guest.php?screen=info_village&id=" + a.getSource().getId();
      sourceVillageName = a.getSource().getFullName();
      sourceVillageCoord = a.getSource().getCoordAsString();

      // replace values
      b = b.replaceAll(SOURCE_PLAYER_NAME, Matcher.quoteReplacement(sourceTribeName));
      b = b.replaceAll(SOURCE_PLAYER_LINK, sourceTribeLink);
      b = b.replaceAll(SOURCE_ALLY_NAME, Matcher.quoteReplacement(sourceAllyName));
      b = b.replaceAll(SOURCE_ALLY_TAG, Matcher.quoteReplacement(sourceAllyTag));
      b = b.replaceAll(SOURCE_ALLY_LINK, sourceAllyLink);
      b = b.replaceAll(SOURCE_VILLAGE_NAME, Matcher.quoteReplacement(sourceVillageName));
      b = b.replaceAll(SOURCE_VILLAGE_COORD, sourceVillageCoord);
      b = b.replaceAll(SOURCE_VILLAGE_LINK, sourceVillageLink);

      // </editor-fold>

      // <editor-fold defaultstate="collapsed" desc=" replace target tribe and ally">
      Tribe targetTribe = a.getTarget().getTribe();
      String targetTribeName = "";
      String targetTribeLink = "";
      String targetAllyName = "";
      String targetAllyTag = "";
      String targetAllyLink = "";
      String targetVillageName = "";
      String targetVillageCoord = "";
      String targetVillageLink = "";

      if (targetTribe == null) {
        // tribe is null, so it is a barbarian village
        targetTribeName = "Barbaren";
        targetAllyName = "Barbaren";
      } else {
        targetTribeLink = baseURL;
        targetTribeLink += "guest.php?screen=info_player&id=" + targetTribe.getId();
        targetTribeName = targetTribe.getName();

        // replace source tribe
        Ally targetAlly = targetTribe.getAlly();
        if (targetAlly == null) {
          // tribe has no ally
          targetAllyName = "Kein Stamm";
        } else {
          // ally valid
          targetAllyName = targetAlly.getName();
          targetAllyTag = targetAlly.getTag();
          targetAllyLink = baseURL;
          targetAllyLink += "guest.php?screen=info_ally&id=" + targetAlly.getId();
        }
      }
      // replace source village
      targetVillageLink = baseURL;
      targetVillageLink += "guest.php?screen=info_village&id=" + a.getTarget().getId();
      targetVillageName = a.getTarget().getFullName();
      targetVillageCoord = a.getTarget().getCoordAsString();

      // replace values
      b = b.replaceAll(TARGET_PLAYER_NAME, Matcher.quoteReplacement(targetTribeName));
      b = b.replaceAll(TARGET_PLAYER_LINK, targetTribeLink);
      b = b.replaceAll(TARGET_ALLY_NAME, Matcher.quoteReplacement(targetAllyName));
      b = b.replaceAll(TARGET_ALLY_TAG, Matcher.quoteReplacement(targetAllyTag));
      b = b.replaceAll(TARGET_ALLY_LINK, targetAllyLink);
      b = b.replaceAll(TARGET_VILLAGE_NAME, Matcher.quoteReplacement(targetVillageName));
      b = b.replaceAll(TARGET_VILLAGE_COORD, targetVillageCoord);
      b = b.replaceAll(TARGET_VILLAGE_LINK, targetVillageLink);

      // </editor-fold>

      // <editor-fold defaultstate="collapsed" desc="Replace times and place URL">
      // replace arrive time
      String arrive = f.format(a.getArriveTime());
      b = b.replaceAll(ARRIVE_TIME, arrive);
      // replace send time
      long send =
          a.getArriveTime().getTime()
              - ((long)
                      DSCalculator.calculateMoveTimeInSeconds(
                          a.getSource(), a.getTarget(), a.getUnit().getSpeed())
                  * 1000);
      b = b.replaceAll(SEND_TIME, f.format(new Date(send)));
      // replace place link
      String placeURL = baseURL + "game.php?village=";
      int uvID = GlobalOptions.getSelectedProfile().getUVId();
      if (uvID >= 0) {
        placeURL = baseURL + "game.php?t=" + uvID + "&village=";
      }
      placeURL +=
          a.getSource().getId() + "&screen=place&mode=command&target=" + a.getTarget().getId();

      placeURL += "&type=0";

      StandardAttack stdAttack = StandardAttackManager.getSingleton().getElementByIcon(a.getType());
      for (UnitHolder u : DataHolder.getSingleton().getUnits()) {
        int amount = 0;
        if (stdAttack != null) {
          amount = stdAttack.getAmountForUnit(u, a.getSource());
        }
        placeURL += "&" + u.getPlainName() + "=" + amount;
      }

      b = b.replaceAll(PLACE, placeURL);
      // </editor-fold>

      result.append(b);
      cnt++;
    }

    // append footer
    result.append(replaceHeadFootVariables(FOOTER, pPlanName, pAttacks));
    try {
      FileWriter w = new FileWriter(pHtmlFile);
      w.write(result.toString());
      w.flush();
      w.close();
    } catch (Exception e) {
      logger.error("Failed writing HTML file", e);
    }
  }
Example #7
0
  /**
   * Process all the requests. The connection must have been opened and set first.
   *
   * @param requests the requets to process
   */
  public void processRequests(List requests)
      throws IOException, UnconfiguredRequestException, ResponseException, CommandAbortedException {

    if (requests == null || requests.size() == 0) {
      throw new IllegalArgumentException(
          "[processRequests] requests "
              + // NOI18N
              "was either null or empty."); // NOI18N
    }

    if (abort) {
      throw new CommandAbortedException(
          "Aborted during request processing", // NOI18N
          CommandException.getLocalMessage("Client.commandAborted", null)); // NOI18N
    }

    loggedDataInputStream = null;
    loggedDataOutputStream = null;

    // send the initialisation requests if we are handling the first
    // command
    boolean filterRootRequest = true;
    if (isFirstCommand()) {
      setIsFirstCommand(false);
      int pos = 0;
      if (!initialRequestsSent) {
        pos = fillInitialRequests(requests);
        initialRequestsSent = true;
        filterRootRequest = false;
      }
      if (globalOptions != null) {
        // sends the global options that are to be sent to server (-q, -Q, -t, -n, l)
        for (Iterator it = globalOptions.createRequestList().iterator(); it.hasNext(); ) {
          Request request = (Request) it.next();
          requests.add(pos++, request);
        }

        if (globalOptions.isUseGzip() && globalOptions.getCompressionLevel() != 0) {
          requests.add(pos++, new GzipFileContentsRequest(globalOptions.getCompressionLevel()));
        }
      }
    } else if (printConnectionReuseWarning) {
      if (System.getProperty("javacvs.multiple_commands_warning") == null) { // NOI18N
        System.err.println("WARNING TO DEVELOPERS:"); // NOI18N
        System.err.println(
            "Please be warned that attempting to reuse one open connection for more commands is not supported by cvs servers very well."); // NOI18N
        System.err.println("You are advised to open a new Connection each time."); // NOI18N
        System.err.println(
            "If you still want to proceed, please do: System.setProperty(\"javacvs.multiple_commands_warning\", \"false\")"); // NOI18N
        System.err.println("That will disable this message."); // NOI18N
      }
    }

    if (!ALLOWED_CONNECTION_REUSE_REQUESTS.contains(requests.get(requests.size() - 1).getClass())) {
      printConnectionReuseWarning = true;
    }

    final boolean fireEnhancedEvents = getEventManager().isFireEnhancedEventSet();
    int fileDetailRequestCount = 0;

    if (fireEnhancedEvents) {
      for (Iterator it = requests.iterator(); it.hasNext(); ) {
        Request request = (Request) it.next();

        FileDetails fileDetails = request.getFileForTransmission();
        if (fileDetails != null && fileDetails.getFile().exists()) {
          fileDetailRequestCount++;
        }
      }
      CVSEvent event =
          new EnhancedMessageEvent(
              this, EnhancedMessageEvent.REQUESTS_COUNT, new Integer(fileDetailRequestCount));
      getEventManager().fireCVSEvent(event);
    }

    LoggedDataOutputStream dos = connection.getOutputStream();
    loggedDataOutputStream = dos;

    // this list stores stream modification requests, each to be called
    // to modify the input stream the next time we need to process a
    // response
    List streamModifierRequests = new LinkedList();

    // sending files does not seem to allow compression
    transmitFileHandler = getUncompressedFileHandler();

    for (Iterator it = requests.iterator(); it.hasNext(); ) {
      if (abort) {
        throw new CommandAbortedException(
            "Aborted during request processing", // NOI18N
            CommandException.getLocalMessage("Client.commandAborted", null)); // NOI18N
      }

      final Request request = (Request) it.next();

      if (request instanceof GzipFileContentsRequest) {
        if (dontUseGzipFileHandler) {
          stderr.println(
              "Warning: The server is not supporting gzip-file-contents request, no compression is used.");
          continue;
        }
      }

      // skip the root request if already sent
      if (request instanceof RootRequest) {
        if (filterRootRequest) {
          continue;
        } else { // Even if we should not filter the RootRequest now, we must filter all successive
                 // RootRequests
          filterRootRequest = true;
        }
      }
      // send request to server
      String requestString = request.getRequestString();
      dos.writeBytes(requestString);

      // we must modify the outputstream now, but defer modification
      // of the inputstream until we are about to read a response.
      // This is because some modifiers (e.g. gzip) read the header
      // on construction, and obviously no header is present when
      // no response has been sent
      request.modifyOutputStream(connection);
      if (request.modifiesInputStream()) {
        streamModifierRequests.add(request);
      }
      dos = connection.getOutputStream();

      FileDetails fileDetails = request.getFileForTransmission();
      if (fileDetails != null) {
        final File file = fileDetails.getFile();
        // only transmit the file if it exists! When committing
        // a remove request you cannot transmit the file
        if (file.exists()) {
          Logger.logOutput(
              new String(
                      "<Sending file: "
                          + // NOI18N
                          file.getAbsolutePath()
                          + ">\n")
                  .getBytes("utf8")); // NOI18N

          if (fireEnhancedEvents) {
            CVSEvent event =
                new EnhancedMessageEvent(this, EnhancedMessageEvent.FILE_SENDING, file);
            getEventManager().fireCVSEvent(event);

            fileDetailRequestCount--;
          }

          if (fileDetails.isBinary()) {
            transmitFileHandler.transmitBinaryFile(file, dos);
          } else {
            transmitFileHandler.transmitTextFile(file, dos);
          }

          if (fireEnhancedEvents && fileDetailRequestCount == 0) {
            CVSEvent event =
                new EnhancedMessageEvent(this, EnhancedMessageEvent.REQUESTS_SENT, "Ok"); // NOI18N
            getEventManager().fireCVSEvent(event);
          }
        }
      }
      if (request.isResponseExpected()) {
        dos.flush();

        // now perform the deferred modification of the input stream
        Iterator modifiers = streamModifierRequests.iterator();
        while (modifiers.hasNext()) {
          System.err.println("Modifying the inputstream..."); // NOI18N
          final Request smRequest = (Request) modifiers.next();
          System.err.println(
              "Request is a: "
                  + // NOI18N
                  smRequest.getClass().getName());
          smRequest.modifyInputStream(connection);
        }
        streamModifierRequests.clear();

        handleResponse();
      }
    }
    dos.flush();

    transmitFileHandler = null;
  }