Example #1
0
  @EventHandler
  public void onPlayerQuit(PlayerQuitEvent e) {
    Player p = e.getPlayer();

    if (Config.getConfig().getBoolean("options.set-fly-on-join.fly")) p.setAllowFlight(false);

    if (Config.getConfig().getBoolean("broadcast.player-quit.enabled")) {
      if (Config.getConfig().getBoolean("broadcast.player-quit.hide")) {
        e.setQuitMessage(null);
      } else {
        e.setQuitMessage(
            ChatColor.translateAlternateColorCodes(
                '&',
                Config.getConfig()
                    .getString("broadcast.player-quit.message")
                    .replaceAll("%player%", e.getPlayer().getName())));
      }
    }

    if (pvp.containsKey(p)) {
      if (pvp.get(p).isSync()) pvp.get(p).cancel();

      pvp.remove(p);
    }

    if (Commands.delay.containsKey(p)) {
      if (Commands.delay.get(p).getTask().isSync()) Commands.delay.get(p).getTask().cancel();

      Commands.delay.remove(p);
    }
  }
 public void saveArenas() {
   Config config = new Config("Arena/arenas");
   for (Arena ar : arenas) {
     config.getConfig().set(ar.getId() + ".location", serializeLoc(ar.spawn));
     config.getConfig().set(ar.getId() + ".type", ar.getType());
     config.getConfig().set(ar.getId() + ".size", ar.getSize());
     config.save();
   }
 }
 public void loadArenas() {
   Config config = new Config("Arena/arenas");
   for (String key : config.getConfig().getKeys(false)) {
     createArena(
         deserializeLoc(config.getConfig().getString(key + ".location")),
         config.getConfig().getString(key + ".type"),
         config.getConfig().getInt(key + ".size"));
   }
 }
 @Before
 public void setup() {
   Config c = Config.getConfig("TESTTEST");
   c.add("restfixture.null.value.representation", NULL);
   exec = mock(StatementExecutorInterface.class);
   variables = new SlimVariables(c, exec);
 }
 private void handleOpenArticle(
     Request request, HttpServletResponse httpServletResponse, String target) throws Exception {
   try {
     int k1 = target.indexOf('/', 1);
     int k2 = target.indexOf('/', k1 + 1);
     String feedId = target.substring(k1 + 1, k2);
     String strSeq = target.substring(k2 + 1);
     int seq = Integer.parseInt(strSeq);
     Article article = articleDb.get(feedId, seq);
     LoginInfo loginInfo = userHelpers.getLoginInfo(request);
     // ttt2 using the link from a non-authenticated browser causes a NPE; maybe do something
     // better, e.g. sign up
     ReadArticlesColl readArticlesColl = readArticlesCollDb.get(loginInfo.userId, feedId);
     if (readArticlesColl == null) {
       readArticlesColl = new ReadArticlesColl(loginInfo.userId, feedId);
     }
     if (!readArticlesColl.isRead(seq)) {
       readArticlesColl.markRead(seq, Config.getConfig().maxSizeForReadArticles);
       readArticlesCollDb.add(readArticlesColl);
     }
     String s =
         URIUtil.encodePath(article.url)
             .replace("%3F", "?")
             .replace("%23", "#"); // ttt2 see how to do this right
     httpServletResponse.sendRedirect(s);
   } catch (Exception e) {
     WebUtils.showResult(
         String.format("Failed to get article for path %s. %s", target, e),
         "/",
         request,
         httpServletResponse);
   }
 }
Example #6
0
  /** Inits the. */
  public static synchronized void init() {
    if (inited) {
      return;
    }

    _conf = Config.getConfig();

    /** initialize app command */
    Command.init();

    /** initialize the RSA key, hardcode 2048 bits */
    TConn.pub_key = SystemConfig.s("pub_key", null);
    if (TConn.pub_key == null) {
      Key k = RSA.generate(2048);
      TConn.pri_key = k.pri_key;
      TConn.pub_key = k.pub_key;

      /** set back in database */
      SystemConfig.setConfig("pri_key", TConn.pri_key);
      SystemConfig.setConfig("pub_key", TConn.pub_key);
    } else {

      /** get from the database */
      TConn.pri_key = SystemConfig.s("pri_key", null);
    }

    inited = true;
  }
  /**
   * This is the main loop of the whole server. It sets up the socket and then proceeds to loop
   * indefinitely, blocking while it waits for incoming connections.
   */
  public void run() {
    try {
      listenSocket = new ServerSocket();
      listenSocket.setReuseAddress(true);
      listenSocket.setPerformancePreferences(1, 2, 0);
      listenSocket.bind(
          new InetSocketAddress(
              Config.getConfig().getAddressToBind(), Config.getConfig().getPortNumber()));
    } catch (IOException e) {
      System.err.println("Exception while creating listening socket: " + e.toString());
      System.err.println("Server exiting.");
      System.exit(-1);
    }

    System.out.println("The socket is now listening.");
    Socket socket;
    PrintWriter writer;
    ConnectionHandler temp;
    int listSize;
    while (keepRunning) {
      try {
        socket = listenSocket.accept();
        socket.setSoTimeout(120000);
        synchronized (listLock) {
          listSize = connectionList.size();
        }
        if (Config.getConfig().getMaxConnections() != 0
            && listSize >= Config.getConfig().getMaxConnections()) {
          writer = new PrintWriter(socket.getOutputStream(), true);
          writer.println("Error: server has reached maximum number " + "of connections.");
          writer.close();
          socket.close();
        } else {
          temp = new ConnectionHandler(socket, this);
          synchronized (listLock) {
            connectionList.add(temp);
          }
          new Thread(temp).start();
        }
      } catch (IOException e) {
        System.err.println("Exception while accepting incoming " + "connection: ");
        System.err.println(e.toString());
      }
    }
  }
 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   if (requestCode == ConfigActivity.CONFIG_UPDATE_REQUEST && resultCode == RESULT_OK) {
     showFetchingProgress();
     Config config = Config.getConfig(this);
     twitter = new TwitterService(config.getUsername(), config.getPassword());
     twitter.requestFriendsTimeline(handler);
   }
 }
Example #9
0
 @EventHandler
 public void onEntityDamage(EntityDamageEvent e) {
   if (e.getEntity() instanceof Player
       && e.getCause().equals(DamageCause.VOID)
       && Config.getConfig().getBoolean("teleport-to-spawn-on.void-fall")) {
     Utils.teleportToSpawn((Player) e.getEntity());
     e.setCancelled(true);
   }
 }
 // !!! IDEA reports this as unused, but it is called from JSP
 public static String getStyle(LoginInfo loginInfo) {
   StringBuilder bld = new StringBuilder();
   bld.append("<style media=\"screen\" type=\"text/css\">\n\n");
   if (loginInfo == null) {
     bld.append(Config.getConfig().defaultStyle);
   } else {
     bld.append(loginInfo.style); // ttt3 detect broken styles and return default
   }
   bld.append("</style>\n");
   return bld.toString();
 }
  private void handleSignupPost(Request request, HttpServletResponse httpServletResponse)
      throws Exception {
    String userId = request.getParameter(PARAM_USER_ID);
    String userName = request.getParameter(PARAM_USER_NAME);
    String email = request.getParameter(PARAM_EMAIL);
    String stringPassword = request.getParameter(PARAM_PASSWORD);
    String stringPasswordConfirm = request.getParameter(PARAM_PASSWORD_CONFIRM);

    if (!stringPassword.equals(stringPasswordConfirm)) {
      WebUtils.redirectToError(
          "Mismatch between password and password confirmation", request, httpServletResponse);
      return;
    }

    SecureRandom secureRandom = new SecureRandom();
    String salt = "" + secureRandom.nextLong();
    byte[] password = User.computeHashedPassword(stringPassword, salt);
    User user = userDb.get(userId);
    if (user != null) {
      WebUtils.redirectToError(
          "There already exists a user with the ID " + userId, request, httpServletResponse);
      return;
    }

    user =
        new User(
            userId,
            userName,
            password,
            salt,
            email,
            new ArrayList<String>(),
            Config.getConfig().activateAccountsAtCreation,
            false);
    // ttt2 add confirmation by email, captcha, ...
    List<String> fieldErrors = user.checkFields();
    if (!fieldErrors.isEmpty()) {
      StringBuilder bld =
          new StringBuilder("Invalid values when trying to create user with ID ")
              .append(userId)
              .append("<br/>");
      for (String s : fieldErrors) {
        bld.append(s).append("<br/>");
      }
      WebUtils.redirectToError(bld.toString(), request, httpServletResponse);
      return;
    }

    // ttt2 2 clients can add the same userId simultaneously
    userDb.add(user);

    httpServletResponse.sendRedirect("/");
  }
Example #12
0
  private void manageInstances() {
    if (configuration.getConfig().getBoolean("Death.DeathChest Enabled"))
      getServer().getPluginManager().registerEvents(dcl, this);
    if (configuration.getConfig().getBoolean("Tagging.Use TagAPI")
        && getServer().getPluginManager().getPlugin("TagAPI") != null) {
      this.tagApi = new TagEnabled(this);
    } else {
      this.tagApi = new TagDisabled();
    }
    getServer().getPluginManager().registerEvents(tagApi, this);

    if (configuration.getConfig().getBoolean("Auto update", false))
      updater = new Updater(this, "pvp-tag", this.getFile(), Updater.UpdateType.DEFAULT, false);
    if (configuration.getConfig().getBoolean("Send Usage")) {
      try {
        Metrics m = new Metrics(this);
        m.start();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
Example #13
0
  @EventHandler
  public void onEntityDamageByEntity(EntityDamageByEntityEvent e) {
    if (!((e.getEntity() instanceof Player)
        && Config.getConfig().getBoolean("disable-spawn-command-in-pvp.enabled"))) return;

    final Player p = (Player) e.getEntity();

    if (e.getDamager() instanceof Player) {
      pvp(p, (Player) e.getDamager());
    } else if ((e.getDamager() instanceof Arrow)
        && (((Arrow) e.getDamager()).getShooter() instanceof Player)) {
      pvp(p, (Player) ((Arrow) e.getDamager()).getShooter());
    }
  }
 public List<DisplayField> getFieldValues() {
   ArrayList<DisplayField> list = new ArrayList<DisplayField>();
   EmailFields emailFields = Config.getConfig().getEmailFields();
   for (EmailField field : emailFields.getAvailableFields().values()) {
     if (field.getShowInResults() != EmailField.ShowInResults.NORESULTS) {
       try {
         EmailFieldValue efv = searchResult.getFieldValue(field.getName());
         list.add(DisplayField.getDisplayField(efv, locale, false));
       } catch (MessageSearchException mse) {
         logger.debug("failed to retrieve field value from message: " + mse.getMessage());
       }
     }
   }
   return list;
 }
Example #15
0
 public static Container createContainer(long nextId, long parentId, Item item) {
   Container c = new Container();
   c.setId("" + nextId);
   c.setParentID("" + parentId);
   /*
   if (FolderItem.class.isAssignableFrom(item.getClass())) {
   FolderItem fi = (FolderItem) item;
   c.setChildCount(fi.getChildren().size());
   }
   */
   c.setRestricted(true);
   c.setTitle(item.getName());
   c.setCreator(Config.getConfig().getString(Config.UPNP_SERVER_NAME_KEY));
   c.setClazz(DIDL_CLASS_OBJECT_CONTAINER);
   return c;
 }
  public ApplicationManager(NitroXyModule main, IApplicationInstance appInstance) {
    this.appInstance = appInstance;
    this.main = main;
    this.vhost = appInstance.getVHost();

    loadRouting();

    config = Config.getConfig(appInstance.getApplication().getName(), main);
    if (config.exists()) {
      if (config.settings.StreamSwitcher_Enabled) {
        streamSwitcher = new StreamSwitcher(main, appInstance, config);
      }

      if (config.settings.StreamSwitcher_autoRecord) {
        startRecording();
      }
    }
  }
Example #17
0
  /**
   * Instantiates a new MDC server.
   *
   * @param host the host
   * @param port the port
   */
  protected MDCServer(String host, int port) {
    _conf = Config.getConfig();

    address = (host == null) ? new InetSocketAddress(port) : new InetSocketAddress(host, port);

    /** initialize app command */
    Command.init();

    /** initialize the connection center */
    TConnCenter.init(_conf, port);

    synchronized (_conf) {
      /** load public key from database */
      TConn.pub_key = SystemConfig.s("pub_key", null);
      TConn.pri_key = SystemConfig.s("pri_key", null);

      /** initialize the RSA key, hardcode 2048 bits */
      if (TConn.pub_key == null
          || TConn.pri_key == null
          || "".equals(TConn.pub_key)
          || "".equals(TConn.pri_key)) {
        /** print out the old state */
        log.warn(
            "the pub_key or pri_key missed, the old state are pub_key:["
                + TConn.pub_key
                + "], pri_key:["
                + TConn.pri_key
                + "]");

        Key k = RSA.generate(2048);
        TConn.pri_key = k.pri_key;
        TConn.pub_key = k.pub_key;

        /** print out the new public key */
        log.warn("create new RSA key pair, pub_key:[" + TConn.pub_key + ']');

        /** set back in database */
        SystemConfig.setConfig("pri_key", TConn.pri_key);
        SystemConfig.setConfig("pub_key", TConn.pub_key);
      }

      MAX_SIZE = SystemConfig.i("mdc.max_size", MAX_SIZE);
    }
  }
  public static synchronized List<SearchResultBean> getSearchResultBeans(
      List<Search.Result> results, Locale locale) {
    List<SearchResultBean> searchResultBeans = new LinkedList<SearchResultBean>();
    try {
      for (Search.Result result : results) {
        searchResultBeans.add(new SearchResultBean(result, locale));
      }
      while (searchResultBeans.size() < Config.getConfig().getSearch().getMaxSearchResults()) {
        searchResultBeans.add(new SearchResultBean());
      }
    } catch (java.util.ConcurrentModificationException ce) {
      // bit of a hack to say the least

      try {
        Thread.sleep(50);
      } catch (Exception e) {
      }
      return getSearchResultBeans(results, locale);
    }
    return searchResultBeans;
  }
Example #19
0
  /**
   * Parse the command line arguments
   *
   * @param args command line arguments
   * @return
   * @throws ParseException
   */
  public static Config parse(String... args) throws Exception {

    if (args == null || args.length <= 0) {
      logger.error("args is null!");
      return null;
    }

    Config config = Config.getConfig();

    // Create the command line parser.
    CommandLineParser parser = new DefaultParser();

    // Parse the command line arguments.
    logger.info("Get input args: " + Arrays.asList(args));
    CommandLine line = parser.parse(OPTIONS, args);

    // Copy args to config
    copyOptionToConfig(line, config);

    return config;
  }
  /**
   * Returns the LSRN identifier for the given node. The method will first try to obtain an
   * explicitly specified ID as encoded by the following SIO attribute structure:
   *
   * <pre>{@code
   * root [
   *   'has attribute'/'has identifier' (SIO_000008/SIO_000067)
   *     [
   *       rdf:type $identifierClass;
   *       'has value' (SIO_000300) $ID
   *     ]
   * ]
   * }</pre>
   *
   * <p>If no such structure is attached to root, then the method will fall back to parsing the ID
   * from the root's URI, using the regular expressions associated with the given LSRN identifier
   * class.
   *
   * @param root the root resource
   * @param lsrnIdentifierType the LSRN identifier type URI (e.g. lsrn:UniProt_Identifier).
   * @return the database identifier of the given node
   */
  public static String getID(Resource root, Resource lsrnIdentifierType) {
    Collection<String> identifiers = SIOUtils.getAttributeValues(root, lsrnIdentifierType);
    identifiers.addAll(SIOUtils.getAttributeValues(root, SIO.has_identifier, lsrnIdentifierType));

    if (identifiers.size() > 0) {
      if (identifiers.size() > 1) {
        log.warn(
            String.format(
                "%s has multiple IDs of type %s, returning only the first ID",
                root, lsrnIdentifierType));
      }
      return identifiers.iterator().next();
    }

    log.info(String.format("%s has no explicit ID, attempting to parse URI", root));
    if (!root.isURIResource()) {
      log.warn(
          "could not determine the database ID, resource has no attached LSRN ID and is a blank node");
      return null;
    }

    String uri = root.getURI();
    for (Pattern pattern : Config.getConfig().getURIPatterns(lsrnIdentifierType)) {
      Matcher matcher = pattern.matcher(uri);
      if (matcher.groupCount() < 1) {
        log.warn(String.format("URI pattern '%s' does not contain any capturing groups", pattern));
        continue;
      }
      if (matcher.find()) {
        String match = matcher.group(1);
        if (!match.isEmpty()) return match;
      }
    }

    log.warn(
        String.format(
            "could not determine lsrn ID for %s, it has no attached ID and does not match any known URI pattern",
            root));
    return null;
  }
Example #21
0
 public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
   if (cmd.getName()
       .equalsIgnoreCase("freeze")) { // If the player typed /basic then do the following...
     if (!(sender instanceof Player)) {
       sender.sendMessage("This command can only be run by a player.");
     } else {
       Player player = (Player) sender;
       if (freeze.get(player.getName()) == null || freeze.get(player.getName()) == "false") {
         freeze.put(player.getName(), "true");
         player.sendMessage("true");
       } else {
         freeze.put(player.getName(), "false");
         player.sendMessage("false");
       }
       player.sendMessage("Lista:");
       List<String> konta = Config.getStringList("lista");
       for (String s : konta) {
         player.sendMessage(s);
       }
     }
     return true;
   } else if (cmd.getName().equalsIgnoreCase("login")) {
     if (!(sender instanceof Player)) {
       sender.sendMessage("This command can only be run by a player.");
     } else {
       Player player = (Player) sender;
       if (args.length == 1) {
         if (args[1].equalsIgnoreCase(
             Config.getConfig("accounts." + player.getName() + ".pass"))) {
           player.sendMessage("password corect");
         } else {
           player.sendMessage("password incorect");
         }
       } else {
         player.sendMessage("use /login <password>");
       }
     }
   }
   return false;
 }
  private void handleAddFeedPost(Request request, HttpServletResponse httpServletResponse)
      throws Exception {
    LOG.info("adding feed");
    User user = userHelpers.getUser(request);

    try {
      if (user == null) {
        LOG.error("User not found");
        return;
      }

      String url = request.getParameter(PARAM_NEW_FEED_URL);
      // ttt1 add some validation; probably best try to actually get data, set the title, ...
      if (url == null || url.equals("")) {
        LOG.error("New feed not specified");
        // ttt1 show some error
        return;
      }

      MessageDigest digest = MessageDigest.getInstance("MD5");
      String feedId = PrintUtils.byteArrayAsUrlString(digest.digest(url.getBytes("UTF-8")));
      feedId = feedId.substring(0, Config.getConfig().feedIdSize);

      Feed feed = feedDb.get(feedId);
      if (feed == null) {
        feed = new Feed(feedId, url);
        feedDb.add(feed);
      }

      if (user.feedIds.contains(feedId)) {
        LOG.error(String.format("Trying to add existing feed %s to user %s", feedId, user));
      } else {
        user.feedIds.add(feedId);
        userDb.updateFeeds(user);
      }
    } finally {
      httpServletResponse.sendRedirect(PATH_FEED_ADMIN);
    }
  }
  public static void main(String[] args) throws Exception {
    // process args
    Config cArgs = Config.getConfig("JdbcLoader", args);
    JdbcLoader loader = new JdbcLoader(cArgs);

    loader.logger.info("===============================================");
    loader.logger.info("This run of JDBC loader started at" + new Date());
    loader.logger.info("===============================================");

    loader.connectToSource();
    loader.client = VoltDBClientConnectionUtil.connectToVoltDB(cArgs);
    if (cArgs.queriesFile.isEmpty()) {
      loader.loadTables(cArgs.tables, cArgs.procname);
    } else {
      loader.load(cArgs.queriesFile, cArgs.modules.trim(), cArgs.tables.trim());
    }

    VoltDBClientConnectionUtil.close(loader.client);

    loader.logger.info("==================================================");
    loader.logger.info("This run of JDBC loader completed at" + new Date());
    loader.logger.info("==================================================");
    System.out.println("Read/write complete!");
  }
Example #24
0
  void manageConfig() {
    configuration.enable();
    this.SAFE_DELAY = configuration.getConfig().getInt("Tagging.Safe Time", 30) * 1000;
    this.DEATH_TP_DELAY = configuration.getConfig().getInt("Death.DeathTP Time", 30) * 1000;
    DeathChest.CHEST_BREAK_DELAY = configuration.getConfig().getInt("Death.Chest Time", 45) * 1000;
    useDeathTP = configuration.getConfig().getBoolean("Death.DeathTP Enabled", true);
    this.nameTagColor = configuration.parseNameTagColor();

    PvPLoggerZombie.HEALTH = configuration.getConfig().getInt("PvPLogger Zombie.Health", 50);

    this.disableFlight = configuration.getConfig().getBoolean("Tagging.Disable Flying", true);
    this.unInvis = configuration.getConfig().getBoolean("Tagging.Remove Invisible", true);
    this.taggingEnabled = configuration.getConfig().getBoolean("Tagging.Enabled", true);
    this.antiPilejump = configuration.getConfig().getBoolean("Tagging.Anti Pilejump", true);
    this.pvpZombEnabled = configuration.getConfig().getBoolean("PvPLogger Zombie.Enabled", true);
    this.disableEnderpearls =
        configuration.getConfig().getBoolean("Tagging.Disable Enderpearls", true);
    this.preventTeleport = configuration.getConfig().getBoolean("Tagging.Prevent Teleport", true);
    PvPTag.keepPlayerHealthZomb =
        configuration.getConfig().getBoolean("PvPLogger Zombie.Keep Player Health", true);
    this.deathChestEnabled = configuration.getConfig().getBoolean("Death.DeathChest Enabled", true);
    this.safeTimeObjective =
        configuration.getConfig().getBoolean("Scoreboard Display.Safe Time", true);
    this.healthObjective = configuration.getConfig().getBoolean("Scoreboard Display.Health", true);
    this.factionsEnabled = configuration.getConfig().getBoolean("Factions Enabled", false);
  }
Example #25
0
  @EventHandler
  public void onPlayerJoin(PlayerJoinEvent e) {
    Player p = e.getPlayer();

    if (Main.hasNewVersion() && p.isOp())
      p.sendMessage(
          ChatColor.translateAlternateColorCodes(
              '&', Config.getConfig().getString("check-version.warning-message")));

    if (Config.getConfig().getBoolean("broadcast.player-join.enabled")) {
      if (Config.getConfig().getBoolean("broadcast.player-join.hide")) {
        e.setJoinMessage(null);
      } else {
        e.setJoinMessage(
            ChatColor.translateAlternateColorCodes(
                '&',
                Config.getConfig()
                    .getString("broadcast.player-join.message")
                    .replaceAll("%player%", p.getName())));
      }
    }

    if (Config.getConfig().getBoolean("join-message.enabled")) {
      for (String message : Config.getConfig().getStringList("join-message.text")) {
        p.sendMessage(
            ChatColor.translateAlternateColorCodes(
                '&', message.replaceAll("%player%", p.getName())));
      }
    }

    if (p.hasPlayedBefore()) {
      if (Config.getConfig().getBoolean("teleport-to-spawn-on.join")) {
        Utils.teleportToSpawn(p);
      }
    } else {
      if (Config.getConfig().getBoolean("teleport-to-spawn-on.first-join"))
        Utils.teleportToSpawn(p);

      if (Config.getConfig().getBoolean("broadcast.first-join.enabled"))
        Bukkit.broadcastMessage(
            ChatColor.translateAlternateColorCodes(
                '&',
                Config.getConfig()
                    .getString("broadcast.first-join.message")
                    .replaceAll("%player%", p.getName())));

      if (Config.getConfig().getBoolean("first-join-message.enabled")) {
        for (String message : Config.getConfig().getStringList("first-join-message.text")) {
          p.sendMessage(
              ChatColor.translateAlternateColorCodes(
                  '&', message.replaceAll("%player%", p.getName())));
        }
      }
    }

    int gm = Config.getConfig().getInt("options.set-gamemode-on-join.gamemode");

    if (Config.getConfig().getBoolean("options.set-gamemode-on-join.enabled")) {
      if (gm == 0) {
        p.setGameMode(GameMode.SURVIVAL);
      } else if (gm == 1) {
        p.setGameMode(GameMode.CREATIVE);
      } else if (gm == 2) {
        p.setGameMode(GameMode.ADVENTURE);
      } else if (gm == 3) {
        p.setGameMode(GameMode.SPECTATOR);
      }
    }

    if (Config.getConfig().getBoolean("options.set-fly-on-join.enabled") && gm != 3)
      p.setAllowFlight(Config.getConfig().getBoolean("options.set-fly-on-join.fly"));

    if (Config.getConfig().getBoolean("options.set-max-health-on-join")) p.setHealth(20.0);

    if (Config.getConfig().getBoolean("options.set-max-food-level-on-join")) p.setFoodLevel(20);
  }
  private void handleLoginPost(
      Request request, HttpServletResponse httpServletResponse, boolean secured) throws Exception {
    String userId = request.getParameter(PARAM_USER_ID);
    String password = request.getParameter(PARAM_PASSWORD);
    String rememberAccountStr = request.getParameter(PARAM_REMEMBER_ACCOUNT);
    boolean rememberAccount = Boolean.parseBoolean(rememberAccountStr);
    LoginInfo.SessionInfo sessionInfo = UserHelpers.getSessionInfo(request);

    logOut(sessionInfo.browserId);

    User user = userDb.get(userId);
    if (user == null) {
      WebUtils.redirectToError("User " + userId + " not found", request, httpServletResponse);
      return;
    }

    if (!user.checkPassword(password)) {
      WebUtils.redirectToError("Invalid password", request, httpServletResponse);
      return;
    }

    if (!user.active) {
      WebUtils.redirectToError(
          "Account for User " + userId + " needs to be activated", request, httpServletResponse);
      return;
    }

    LOG.info("Logged in user " + userId);

    sessionInfo.sessionId = null;
    if (sessionInfo.browserId == null) {
      sessionInfo.browserId = getRandomId();
    } else {
      for (LoginInfo loginInfo : loginInfoDb.getLoginsForBrowser(sessionInfo.browserId)) {
        if (userId.equals(loginInfo.userId)) {
          sessionInfo.sessionId = loginInfo.sessionId;
          break;
        }
      }
    }

    long expireOn = System.currentTimeMillis() + Config.getConfig().loginExpireInterval;
    if (sessionInfo.sessionId == null) {
      sessionInfo.sessionId = getRandomId();
      Config config = Config.getConfig();
      loginInfoDb.add(
          new LoginInfo(
              sessionInfo.browserId,
              sessionInfo.sessionId,
              userId,
              expireOn,
              rememberAccount,
              config.defaultStyle,
              config.defaultItemsPerPage,
              config.defaultFeedDateFormat));
      LOG.info(String.format("Logging in in a new session. User: %s", user));
    } else {
      loginInfoDb.updateExpireTime(sessionInfo.browserId, sessionInfo.sessionId, expireOn);
      LOG.info(String.format("Logging in in an existing session. User: %s", user));
    }

    WebUtils.saveCookies(
        httpServletResponse, secured, sessionInfo.browserId, sessionInfo.sessionId);

    httpServletResponse.sendRedirect("/");
  }
Example #27
0
 /** @param output */
 public static void output(String output) {
   System.out.println("\n");
   System.out.println(WordUtils.wrap(output, Config.getConfig().getWordWrap()));
 }
Example #28
0
  public static int[] replayMetaProgramWith(Class<?> TEST_CLASS) throws Exception {
    System.out.println("******************" + TEST_CLASS.getName() + "******************");

    boolean debug = false;

    JUnitCore core = new JUnitCore();

    // output folder
    File fail = new File("results/fail.replay/" + TEST_CLASS.getName().replace(".", "/"));
    fail.mkdirs();
    File success = new File("results/success.replay/" + TEST_CLASS.getName().replace(".", "/"));
    success.mkdirs();

    String path = "results/fail/" + TEST_CLASS.getName().replace(".", "/");
    File source = new File(path);
    File[] mutants;
    if (source.exists() && source.isDirectory()) {
      mutants = source.listFiles();
    } else {
      throw new Exception(
          "The directory fail or success dosen't exist, or is not a directory, please execute MutantSearchSpaceExplorator.runMetaProgramWith(Class<?> TEST_CLASS) first.");
    }

    // we first run the test suite once to load all classes and their static
    // fields
    // this registers only the executed ifs, so indirectly
    // it collects a kind of trace
    Result result = core.run(TEST_CLASS);

    if (debug) {
      core.addListener(new TextListener(System.out));
    }

    List<Selector> selectors = Selector.getAllSelectors();

    // if (selectors.isEmpty())
    // // There's no hot spot in program. Add one to run it at least once
    // selectors = ImmutableList.of(Selector.of(0, "n/a"));

    List<String> successes = Lists.newArrayList();
    List<String> failures = Lists.newArrayList();
    Multimap<Integer, String> failures2 =
        Multimaps.newListMultimap(Maps.newHashMap(), Lists::newArrayList);

    String[] strOptions = new String[selectors.size()];
    // Execute the test for each hot spot permutation
    // for (int[] options :
    // permutations(selectors.stream().map(Selector::getOptionCount).collect(Collectors.toList())))
    // {

    int nattempts = 0;

    for (int mut = 0; mut < mutants.length; mut++) {
      Config conf = Config.getInitInstance();

      Map<String, Integer> mapedConf =
          conf.getConfig(mutants[mut].getPath()).get(selectors.get(0).getLocationClass().getName());

      Set<String> cles = mapedConf.keySet();

      int[] options = new int[selectors.size()];
      int sel = 0;
      for (String cle : cles) {

        Selector.getSelectorByName(cle).choose(mapedConf.get(cle));
        strOptions[sel] = Selector.getSelectorByName(cle).getChosenOptionDescription();
        for (int o = 0; o < Selector.getSelectorByName(cle).getOptionCount(); o++) {

          boolean value = (o == mapedConf.get(cle)) ? true : false;

          conf.write(
              Selector.getSelectorByName(cle).getLocationClass().getName()
                  + ":"
                  + Selector.getSelectorByName(cle).getId()
                  + ":"
                  + Selector.getSelectorByName(cle).getOption()[o]
                  + ":"
                  + value);
        }
        sel++;
      }

      if (debug) System.out.println("Checking options: " + Arrays.toString(options));

      result = core.run(TEST_CLASS);

      if (result.wasSuccessful()) {
        successes.add(
            "   Worked !!!  -> " + Arrays.toString(options) + " / " + Arrays.toString(strOptions));

        // On essaye avec renameTo
        File dest = new File(success.getPath() + "/" + mutants[mut].getName());
        new File("config.txt").renameTo(dest);
      } else {
        String txt =
            String.format(
                "%s / %s -> It has %s failures out of %s runs in %s ms",
                Arrays.toString(options),
                Arrays.toString(strOptions),
                result.getFailureCount(),
                result.getRunCount(),
                result.getRunTime());
        String txt_trace = String.format("%s", Arrays.toString(strOptions));

        failures.add(txt);
        failures2.put(result.getFailureCount(), txt);
        System.out.println(result.getFailures().get(0).getException());
        File dest = new File(fail.getPath() + "/" + mutants[mut].getName());
        new File("config.txt").renameTo(dest);
      }
    }

    System.out.println("killed " + failures.size());
    System.out.println("alive " + successes.size());

    Selector.reset();

    int[] val = {failures.size(), successes.size()};

    return val;

    // Show result summary
    // Sets.newHashSet(failures2.keys()).forEach(k -> {
    // System.out.println(String.format("\n-- Cases with %s", k));
    // Collection<String> texts = failures2.get(k);
    // if (k <= 2 || texts.size() < 10)
    // texts.forEach(System.out::println);
    // else
    // System.out.println("There are " + texts.size());
    // });

    // failures.forEach(System.out::println);

    // System.out.println();
    //
    // if (successes.isEmpty())
    // System.out.println("Oops, sorry, we could find a successful option");
    // else
    // successes.forEach(System.out::println);

  }
Example #29
0
 public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
   if (cmd.getName().equalsIgnoreCase("uuidban")) {
     if (sender instanceof Player) {
       Player player = (Player) sender;
       if (player.hasPermission("uuidban.ban")) {
         String UUID = "";
         JSONObject json = JsonReader.readJsonFromUrl("https://us.mc-api.net/v3/uuid/" + args[0]);
         try {
           UUID = json.getString("uuid");
         } catch (Exception ex) {
           UUID = "";
           ex.printStackTrace();
         }
         if (config.getConfig().contains(UUID)) {
           if (config.getConfig().getString(UUID).equalsIgnoreCase(args[1])) {
             sender.sendMessage(
                 ChatColor.BLUE
                     + "UUIDBan> "
                     + ChatColor.GREEN
                     + args[0]
                     + " is already uuid banned!");
             if (Bukkit.getServer().getPlayer(args[0]) != null) {
               Bukkit.getServer()
                   .getPlayer(args[0])
                   .kickPlayer(
                       "Your account, "
                           + Bukkit.getServer().getPlayer(args[0]).getName()
                           + ", is banned from this server!");
             }
           } else {
             config.getConfig().set(UUID, args[1]);
             config.save();
             sender.sendMessage(
                 ChatColor.BLUE
                     + "UUIDBan> "
                     + ChatColor.GREEN
                     + args[0]
                     + " updated after uuid change. Player is still banned.");
             if (Bukkit.getServer().getPlayer(args[0]) != null) {
               Bukkit.getServer()
                   .getPlayer(args[0])
                   .kickPlayer(
                       "Your account, "
                           + Bukkit.getServer().getPlayer(args[0]).getName()
                           + ", is banned from this server!");
             }
           }
         } else {
           config.getConfig().set(UUID, args[1]);
           config.save();
           if (Bukkit.getServer().getPlayer(args[0]) != null) {
             Bukkit.getServer()
                 .getPlayer(args[0])
                 .kickPlayer(
                     "Your account, "
                         + Bukkit.getServer().getPlayer(args[0]).getName()
                         + ", is banned from this server!");
           }
           sender.sendMessage(
               ChatColor.BLUE + "UUIDBan> " + ChatColor.GREEN + args[0] + " is now uuid banned!");
         }
       } else {
         sender.sendMessage(
             ChatColor.BLUE
                 + "UUIDBan> "
                 + ChatColor.GREEN
                 + "You do not have permission to use this command!");
       }
     } else {
       String UUID = "";
       JSONObject json = JsonReader.readJsonFromUrl("https://us.mc-api.net/v3/uuid/" + args[0]);
       try {
         UUID = json.getString("uuid");
       } catch (Exception ex) {
         UUID = "";
         ex.printStackTrace();
       }
       if (config.getConfig().contains(UUID)) {
         if (config.getConfig().getString(UUID).equalsIgnoreCase(args[1])) {
           log.info(args[0] + " is already banned!");
           if (Bukkit.getServer().getPlayer(args[0]) != null) {
             Bukkit.getServer()
                 .getPlayer(args[0])
                 .kickPlayer(
                     "Your account, "
                         + Bukkit.getServer().getPlayer(args[0]).getName()
                         + ", is banned from this server!");
           }
         } else {
           config.getConfig().set(UUID, args[1]);
           config.save();
           log.info(args[0] + " updated after uuid change. Player is still banned.");
           if (Bukkit.getServer().getPlayer(args[0]) != null) {
             Bukkit.getServer()
                 .getPlayer(args[0])
                 .kickPlayer(
                     "Your account, "
                         + Bukkit.getServer().getPlayer(args[0]).getName()
                         + ", is banned from this server!");
           }
         }
       } else {
         config.getConfig().set(UUID, args[1]);
         config.save();
         if (Bukkit.getServer().getPlayer(args[0]) != null) {
           Bukkit.getServer()
               .getPlayer(args[0])
               .kickPlayer(
                   "Your account, "
                       + Bukkit.getServer().getPlayer(args[0]).getName()
                       + ", is banned from this server!");
         }
         log.info(args[0] + " is now uuid banned!");
       }
     }
   } else if (cmd.getName().equalsIgnoreCase("uuidunban")) {
     if (sender instanceof Player) {
       Player player = (Player) sender;
       if (player.hasPermission("uuidban.unban")) {
         String UUID = "";
         JSONObject json = JsonReader.readJsonFromUrl("https://us.mc-api.net/v3/uuid/" + args[0]);
         try {
           UUID = json.getString("uuid");
         } catch (Exception ex) {
           UUID = "";
           ex.printStackTrace();
         }
         if (config.getConfig().contains(UUID)) {
           config.getConfig().set(UUID, null);
           config.save();
           sender.sendMessage(
               ChatColor.BLUE + "UUIDBan> " + ChatColor.GREEN + args[0] + " is now unbanned!");
         } else {
           sender.sendMessage(
               ChatColor.BLUE
                   + "UUIDBan> "
                   + ChatColor.GREEN
                   + args[0]
                   + " is not already uuid bannned!");
         }
       } else {
         sender.sendMessage(
             ChatColor.BLUE
                 + "UUIDBan> "
                 + ChatColor.GREEN
                 + "You do not have permission to use this command!");
       }
     } else {
       String UUID = "";
       JSONObject json = JsonReader.readJsonFromUrl("https://us.mc-api.net/v3/uuid/" + args[0]);
       try {
         UUID = json.getString("uuid");
       } catch (Exception ex) {
         UUID = "";
         ex.printStackTrace();
       }
       if (config.getConfig().contains(UUID)) {
         config.getConfig().set(UUID, null);
         config.save();
         log.info(args[0] + " is now unbanned!");
       } else {
         log.info(args[0] + " is not already uuid banned!");
       }
     }
   }
   return false;
 }
 public static boolean ThermalExpansionRecipesEnabled() {
   boolean defaultval = isThermalExpansionLoaded();
   return Config.getConfig()
       .get(Configuration.CATEGORY_GENERAL, "Thermal Expansion Recipes", defaultval)
       .getBoolean(defaultval);
 }