Esempio n. 1
0
  /**
   * Konstruktor, uebernimmt eine Socket-Verbindung vom Server, initialisiert die Ein-und
   * Ausgabestreams des Sockets und speichert seine Spielernummer, die er vom Server zugewiesen
   * bekommt. Diese wird dann zuletzt an den Communicator gesendet.
   *
   * @param connection Socketverbindung
   * @param server Server-Objekt
   * @param cnt Spielernummer
   * @param gameID Spiel-ID
   * @param name Spielname
   * @exception IOException
   * @exception SocketException
   */
  public ServerThread(Socket connection, Server server, int cnt, int gameID, String name) {
    this.connection = connection;
    this.server = server;
    this.myNumber = cnt;
    this.gameID = gameID;
    this.nameOfTheGame = name;

    try {
      out =
          new PrintWriter(
              new BufferedWriter(new OutputStreamWriter(this.connection.getOutputStream())));
      in = new BufferedReader(new InputStreamReader(this.connection.getInputStream()));
    } catch (IOException e) {
      String log = "player " + (myNumber + 1) + ":error creating ServerThread\n";
      System.out.print(log);
      this.server.log(log, server.getPort());
    }

    send("1" + Integer.toString(myNumber)); // sende die zugewiesene
    // Spielernummer
    // an den Communicator
    try {
      this.connection.setSoTimeout(1800000);
      this.connection.setSoLinger(true, 6); // optional?
    } catch (SocketException e) {
      String log = "player " + (myNumber + 1) + ": error setting socket options\n";
      System.out.print(log);
      this.server.log(log, server.getPort());
    }
  }
Esempio n. 2
0
  /**
   * Main Method
   *
   * @param args command line arguments
   */
  public static void main(String[] args) {
    // init logging
    try {
      Logging.init("lucane.log", "ALL");
    } catch (IOException ioe) {
      System.err.println("Unable to init logging, exiting.");
      System.exit(1);
    }

    Server server = null;
    ServerConfig config = null;

    try {
      config = new ServerConfig(CONFIG_FILE);
    } catch (Exception e) {
      Logging.getLogger().severe("Unable to read or parse the config file.");
      e.printStackTrace();
      System.exit(1);
    }

    // Server creation
    server = new Server(config);
    server.generateKeys();
    Logging.getLogger().info("Server is ready.");
    server.run();
  }
 private void stopTimeout(MessageContext context, String args) {
   if (args.isEmpty()) {
     apiClient.sendMessage(
         loc.localize("commands.mod.stoptimeout.response.invalid"), context.getChannel());
     return;
   }
   String uid = args;
   if (uid.length() > 4) {
     if (uid.startsWith("<@")) {
       uid = uid.substring(2, uid.length() - 1);
     }
     Server server = context.getServer();
     User user = apiClient.getUserById(uid, server);
     if (user == NO_USER) {
       user = new User("UNKNOWN", uid, "", null);
     }
     LOGGER.info(
         "{} ({}) is attempting to cancel timeout for {} ({}) in {} ({})",
         context.getAuthor().getUsername(),
         context.getAuthor().getId(),
         user.getUsername(),
         user.getId(),
         server.getName(),
         server.getId());
     cancelTimeout(user, server, context.getChannel());
   } else {
     apiClient.sendMessage(
         loc.localize("commands.mod.stoptimeout.response.invalid"), context.getChannel());
   }
 }
  @Override
  @Transactional
  public Application start(Application application) throws ServiceException {
    try {
      User user = authentificationUtils.getAuthentificatedUser();
      logger.debug("start : Methods parameters : " + application);

      List<Module> modules = application.getModules();
      for (Module module : modules) {
        try {
          module = moduleService.startModule(module);
        } catch (ServiceException e) {
          logger.error("failed to start " + application.toString(), e);
        }
      }
      List<Server> servers = application.getServers();
      for (Server server : servers) {
        logger.info("old server ip : " + server.getContainerIP());
        server = serverService.startServer(server);
      }

      if (application.getAliases() != null && !application.getAliases().isEmpty()) {
        updateAliases(application);
      }
      logger.info("ApplicationService : Application successfully started ");
    } catch (PersistenceException e) {
      throw new ServiceException(e.getLocalizedMessage(), e);
    }
    return application;
  }
 private void refreshTimeoutOnEvade(User user, Server server) {
   ServerTimeout timeout =
       SafeNav.of(serverStorage.get(server.getId()))
           .next(TempServerConfig::getServerTimeouts)
           .next(ServerTimeoutStorage::getTimeouts)
           .next(timeouts -> timeouts.get(user.getId()))
           .get();
   if (timeout == null) {
     LOGGER.warn(
         "Attempted to refresh a timeout on a user who was not timed out! {} ({})",
         user.getUsername(),
         user.getId());
     return;
   }
   LOGGER.info(
       "User {} ({}) attempted to evade a timeout on {} ({})!",
       user.getUsername(),
       user.getId(),
       server.getName(),
       server.getId());
   Channel channel = apiClient.getChannelById(server.getId(), server);
   apiClient.sendMessage(
       loc.localize(
           "listener.mod.timeout.on_evasion",
           user.getId(),
           formatDuration(Duration.between(Instant.now(), timeout.getEndTime())),
           formatInstant(timeout.getEndTime())),
       channel);
   applyTimeoutRole(user, server, channel);
 }
  @Override
  @Transactional
  public void addNewAlias(Application application, String alias)
      throws ServiceException, CheckException {

    logger.info("ALIAS VALUE IN addNewAlias : " + alias);

    if (checkAliasIfExists(alias)) {
      throw new CheckException(
          "This alias is already used by another application on this CloudUnit instance");
    }

    alias = alias.toLowerCase();
    if (alias.startsWith("https://") || alias.startsWith("http://") || alias.startsWith("ftp://")) {
      alias = alias.substring(alias.lastIndexOf("//") + 2, alias.length());
    }

    if (!StringUtils.isAlphanumeric(alias)) {
      throw new CheckException(
          "This alias must be alphanumeric. Please remove all other characters");
    }

    try {
      Server server = application.getServers().get(0);
      application.getAliases().add(alias);
      hipacheRedisUtils.writeNewAlias(alias, application, server.getServerAction().getServerPort());
      applicationDAO.save(application);

    } catch (DataAccessException e) {
      throw new ServiceException(e.getLocalizedMessage(), e);
    }
  }
 public boolean applyTimeout(
     User issuingUser, Channel noticeChannel, Server server, User user, Duration duration) {
   String serverId = server.getId();
   if (duration != null && !duration.isNegative() && !duration.isZero()) {
     ServerTimeout timeout =
         new ServerTimeout(
             duration,
             Instant.now(),
             user.getId(),
             serverId,
             user.getUsername(),
             issuingUser.getId());
     TempServerConfig serverConfig = serverStorage.get(serverId);
     if (serverConfig == null) {
       serverConfig = new TempServerConfig(serverId);
       serverStorage.put(serverId, serverConfig);
     }
     ServerTimeoutStorage storage = serverConfig.getServerTimeouts();
     if (storage == null) {
       storage = new ServerTimeoutStorage();
       serverConfig.setServerTimeouts(storage);
     }
     if (applyTimeoutRole(user, server, noticeChannel)) {
       storage.getTimeouts().put(user.getId(), timeout);
       ScheduledFuture future =
           timeoutService.schedule(
               () -> onTimeoutExpire(user, server), duration.getSeconds(), TimeUnit.SECONDS);
       timeout.setTimerFuture(future);
       saveServerConfig(serverConfig);
       String durationStr = formatDuration(duration);
       String instantStr = formatInstant(timeout.getEndTime());
       String msg =
           loc.localize(
               "commands.mod.timeout.response",
               user.getUsername(),
               user.getId(),
               durationStr,
               instantStr);
       apiClient.sendMessage(msg, noticeChannel);
       LOGGER.info(
           "[{}] '{}': Timing out {} ({}) for {} (until {}), issued by {} ({})",
           serverId,
           server.getName(),
           user.getUsername(),
           user.getId(),
           durationStr,
           instantStr,
           issuingUser.getUsername(),
           issuingUser.getId());
     }
     //  No else with error - applyTimeoutRole does that for us
     return true;
   } else {
     LOGGER.warn("Invalid duration format");
   }
   return false;
 }
Esempio n. 8
0
 /**
  * trennt die Socketverbindung zum entsprechenden Client
  *
  * @exception IOException
  */
 public void closeConnection() {
   try {
     connection.close();
   } catch (IOException e) {
     String log = "player " + (myNumber + 1) + ": error closing connection\n";
     System.out.print(log);
     server.log(log, server.getPort());
   }
 }
Esempio n. 9
0
 private static void monitor() {
   long nowInMillis;
   long dailyTimeStampInMillis;
   init();
   String subject = "HTTP Uptime monitor started: " + remoteHost + ".";
   String message = "Monitoring from " + Server.getHostName() + Names.NEW_LINE;
   message += "URL: " + url + Names.NEW_LINE;
   message += "remote host: " + remoteHost + Names.NEW_LINE;
   message += "local down command:" + downCommand + " " + remoteHost + Names.NEW_LINE;
   message += "local up command:" + upCommand + " " + remoteHost + Names.NEW_LINE;
   try {
     EMail.send(FROM, mailTo, subject, message, smtpHost);
   } catch (Exception e) {
     e.printStackTrace();
   }
   dailyTimeStamp = getToday();
   dailyTimeStampInMillis = dailyTimeStamp.getTimeInMillis();
   int year, month, day;
   year = dailyTimeStamp.get(Calendar.YEAR);
   month = dailyTimeStamp.get(Calendar.MONTH);
   day = dailyTimeStamp.get(Calendar.DAY_OF_MONTH);
   dailyTimeStamp = new GregorianCalendar(year, month, day, 5, 0, 0);
   Calendar currentTimeStamp;
   int i = 0;
   while (true) {
     i++;
     try {
       int code = getResponseCode();
       for (int x = 0; x < (i % 8); x++) System.out.print(".");
       {
       } // System.out.println("Http Response=" + HTTPCodes[code] + "[" +code + "] for " + url);
       if (code < 200 || code > 204) restartServer(code);
     } catch (Exception e) {
       e.printStackTrace();
       restartServer(601);
     }
     Sleep.sleep(POLLING_INTERVAL * 1000);
     currentTimeStamp = new GregorianCalendar();
     nowInMillis = currentTimeStamp.getTimeInMillis();
     if (nowInMillis > (dailyTimeStampInMillis + (1000 * 60 * 60 * 24))) {
       dailyTimeStamp = getToday();
       dailyTimeStampInMillis = dailyTimeStamp.getTimeInMillis();
       subject = "HTTP Uptime monitor running: " + remoteHost + ".";
       message = "Monitoring from " + Server.getHostName() + Names.NEW_LINE;
       message += "URL: " + url + Names.NEW_LINE;
       message += "remote host: " + remoteHost + Names.NEW_LINE;
       message += "local down command:" + downCommand + " " + remoteHost + Names.NEW_LINE;
       message += "local up command:" + upCommand + " " + remoteHost + Names.NEW_LINE;
       try {
         EMail.send(FROM, mailTo, subject, message, smtpHost);
       } catch (Exception e) {
         e.printStackTrace();
       }
     }
   }
 }
  @Override
  @Transactional
  public Application deploy(File file, Application application)
      throws ServiceException, CheckException {

    int code = -1;
    Map<String, String> configShell = new HashMap<>();

    try {
      // get app with all its components

      for (Server server : application.getServers()) {

        // loading server ssh informations

        String rootPassword = server.getApplication().getUser().getPassword();
        configShell.put("port", server.getSshPort());
        configShell.put("dockerManagerAddress", application.getManagerIp());
        configShell.put("password", rootPassword);
        String destFile = "/cloudunit/tmp/";

        // send the file on container

        shellUtils.sendFile(
            file, rootPassword, server.getSshPort(), application.getManagerIp(), destFile);

        // call deployment script

        code =
            shellUtils.executeShell(
                "bash /cloudunit/scripts/deploy.sh "
                    + file.getName()
                    + " "
                    + application.getUser().getLogin(),
                configShell);
      }

      // if all is ok, create a new deployment tag and set app to starting

      if (code == 0) {
        deploymentService.create(application, Type.WAR);
      } else {
        throw new CheckException("No way to deploy application " + file + ", " + application);
      }

    } catch (Exception e) {
      throw new ServiceException(e.getLocalizedMessage(), e);
    }

    return application;
  }
  public List<ContainerUnit> listContainers(String applicationName, boolean withModules)
      throws ServiceException {
    List<ContainerUnit> containers = new ArrayList<>();
    try {
      Application application =
          findByNameAndUser(authentificationUtils.getAuthentificatedUser(), applicationName);
      if (application != null) {
        try {
          // Serveurs
          List<Server> servers = application.getServers();
          // Ajout des containers de type server
          for (Server server : servers) {
            DockerContainer dockerContainer = new DockerContainer();
            dockerContainer.setName(server.getName());
            dockerContainer = DockerContainer.findOne(dockerContainer, application.getManagerIp());
            server = containerMapper.mapDockerContainerToServer(dockerContainer, server);
            ContainerUnit containerUnit =
                new ContainerUnit(server.getName(), server.getContainerID(), "server");
            containers.add(containerUnit);
          }
          if (withModules) {
            // Ajout des containers de type module
            List<Module> modules = application.getModules();
            for (Module module : modules) {
              // on evite de remonter les modules de type toolkit
              // (git, maven...)
              if (module.isTool()) {
                continue;
              }
              DockerContainer dockerContainer = new DockerContainer();
              dockerContainer.setName(module.getName());
              dockerContainer =
                  DockerContainer.findOne(dockerContainer, application.getManagerIp());
              module = containerMapper.mapDockerContainerToModule(dockerContainer, module);
              ContainerUnit containerUnit =
                  new ContainerUnit(module.getName(), module.getContainerID(), "module");
              containers.add(containerUnit);
            }
          }
        } catch (Exception ex) {
          // Si une application sort en erreur, il ne faut pas
          // arrêter la suite des traitements
          logger.error(application.toString(), ex);
        }
      }

    } catch (Exception e) {
      throw new ServiceException(e.getLocalizedMessage(), e);
    }
    return containers;
  }
  @Override
  @Transactional
  public void updateAliases(Application application) throws ServiceException {
    try {
      Server server = application.getServers().get(0);
      List<String> aliases = applicationDAO.findAllAliases(application.getName());
      for (String alias : aliases) {
        hipacheRedisUtils.updateAlias(alias, application, server.getServerAction().getServerPort());
      }

    } catch (DataAccessException e) {
      throw new ServiceException(e.getLocalizedMessage(), e);
    }
  }
 /**
  * Removes the timeout role from the given user. This does NOT create or manage any
  * storage/persistence, it only sets the user's roles
  *
  * @param user The user to remove the timeout role
  * @param server The server on which to remove the user from the timeout role
  * @param invocationChannel The channel to send messages on error
  */
 public boolean removeTimeoutRole(User user, Server server, Channel invocationChannel) {
   String serverId = server.getId();
   TempServerConfig serverConfig = serverStorage.get(serverId);
   if (serverConfig == null) {
     serverConfig = new TempServerConfig(serverId);
     serverStorage.put(serverId, serverConfig);
   }
   ServerTimeoutStorage storage = serverConfig.getServerTimeouts();
   String serverName = server.getName();
   if (storage != null && storage.getTimeoutRoleId() != null) {
     String timeoutRoleId = storage.getTimeoutRoleId();
     Role timeoutRole = apiClient.getRole(timeoutRoleId, server);
     if (timeoutRole != NO_ROLE) {
       //  Get roles
       Set<Role> userRoles =
           apiClient.getMemberRoles(apiClient.getUserMember(user, server), server);
       //  Delete the ban role
       LinkedHashSet<String> newRoles = new LinkedHashSet<>(userRoles.size() - 1);
       userRoles
           .stream()
           .map(Role::getId)
           .filter(s -> !timeoutRoleId.equals(s))
           .forEach(newRoles::add);
       //  Update
       apiClient.updateRoles(user, server, newRoles);
       return userRoles.size() == newRoles.size();
     } else {
       LOGGER.warn(
           "Timeout role ID {} for server {} ({}) does not exist",
           timeoutRoleId,
           serverName,
           serverId);
       apiClient.sendMessage(
           loc.localize("message.mod.timeout.bad_role", timeoutRoleId), invocationChannel);
     }
   } else {
     storage = new ServerTimeoutStorage();
     serverConfig.setServerTimeouts(storage);
     serverStorage.put(serverId, serverConfig);
     LOGGER.warn(
         "Timeout role for server {} ({}) is not configured",
         storage.getTimeoutRoleId(),
         serverName,
         serverId);
     apiClient.sendMessage(loc.localize("message.mod.timeout.not_configured"), invocationChannel);
   }
   return false;
 }
  /** Method declaration */
  public void run() {

    Channel c = init();

    if (c != null) {
      try {
        while (true) {
          String sql = mInput.readUTF();

          mServer.trace(mThread + ":" + sql);

          if (sql == null) {
            break;
          }

          write(mDatabase.execute(sql, c).getBytes());
        }
      } catch (Exception e) {
      }
    }

    try {
      mSocket.close();
    } catch (IOException e) {
    }

    if (mDatabase.isShutdown()) {
      System.out.println("The database is shutdown");
      System.exit(0);
    }
  }
 protected Item findItem(String itemName) {
   for (Item item : Server.getInstance().getItemList()) {
     if (item.getName().equals(itemName)) {
       return item;
     }
   }
   return null;
 }
 public void onTimeoutExpire(User user, Server server) {
   String serverId = server.getId();
   TempServerConfig serverConfig = serverStorage.get(serverId);
   if (serverConfig == null) {
     serverConfig = new TempServerConfig(serverId);
     serverStorage.put(serverId, serverConfig);
   }
   ServerTimeoutStorage storage = serverConfig.getServerTimeouts();
   if (storage != null) {
     ServerTimeout timeout = storage.getTimeouts().remove(user.getId());
     if (timeout != null) {
       saveServerConfig(serverConfig);
       LOGGER.info(
           "Expiring timeout for {} ({}) in {} ({})",
           user.getUsername(),
           user.getId(),
           server.getName(),
           server.getId());
       if (apiClient.getUserById(user.getId(), server) != NO_USER) {
         apiClient.sendMessage(
             loc.localize("message.mod.timeout.expire", user.getId()), server.getId());
       }
       removeTimeoutRole(user, server, apiClient.getChannelById(server.getId()));
       return;
     }
   }
   LOGGER.warn(
       "Unable to expire: find server or timeout entry for {} ({}) in {} ({})",
       user.getUsername(),
       user.getId(),
       server.getName(),
       server.getId());
 }
Esempio n. 17
0
  public void onEnable() {
    // TODO: Place any custom enable code here including the registration of any events

    // Setup Plugin Member Variables
    server = getServer();
    log = server.getLogger();

    commandMap =
        new CommandsManager<Player>() {
          @Override
          public boolean hasPermission(Player player, String perm) {
            // TODO: Implement Permissions
            return true;
          }
        };

    dungeons = new HashMap<String, Dungeon>();
    editSessions = new HashMap<Player, EditSession>();

    PluginManager pm = getServer().getPluginManager();

    try {
      // Register our events
      pm.registerEvent(Event.Type.ENTITY_DAMAGE, entityListener, Priority.Normal, this);
      pm.registerEvent(Event.Type.ENTITY_DEATH, entityListener, Priority.Normal, this);
      pm.registerEvent(Event.Type.ENTITY_COMBUST, entityListener, Priority.Normal, this);
      pm.registerEvent(Event.Type.ENTITY_EXPLODE, entityListener, Priority.Normal, this);
      pm.registerEvent(Event.Type.ENTITY_TARGET, entityListener, Priority.Normal, this);

    } catch (Exception e) {

      log.info("Exception while registering events.");
      log.info(e.getMessage());
    }

    try {

      // Setup PlayerListener class to preprocess command events
      pm.registerEvent(Event.Type.PLAYER_COMMAND_PREPROCESS, playerListener, Priority.Normal, this);
      pm.registerEvent(Event.Type.PLAYER_MOVE, playerListener, Priority.Normal, this);

      // Register Commands to the command map
      commandMap.register(LairDungeonCommand.class);

    } catch (Exception e) {

      log.info("Exception Registering Commands: ");
      log.info(e.getMessage());
    }

    // Say Hello
    log.info("Legends.Lair Hello!");
  }
 /*
  *  To run as a console application just open a console window and:
  * > java Server
  * > java Server portNumber
  * If the port number is not specified 1500 is used
  */
 public static void main(String[] args) {
   // start server on port 1500 unless a PortNumber is specified
   int portNumber = 1500;
   switch (args.length) {
     case 1:
       try {
         portNumber = Integer.parseInt(args[0]);
       } catch (Exception e) {
         System.out.println("Port yang diisikan invalid.");
         System.out.println("Usage is: > java Server [portNumber]");
         return;
       }
     case 0:
       break;
     default:
       System.out.println("Usage is: > java Server [portNumber]");
       return;
   }
   // create a server object and start it
   Server server = new Server(portNumber);
   server.start();
 }
 public void cancelTimeout(User user, Server server, Channel invocationChannel) {
   String serverId = server.getId();
   TempServerConfig serverConfig = serverStorage.get(serverId);
   if (serverConfig == null) {
     serverConfig = new TempServerConfig(serverId);
     serverStorage.put(serverId, serverConfig);
   }
   ServerTimeoutStorage storage = serverConfig.getServerTimeouts();
   removeTimeoutRole(user, server, apiClient.getChannelById(serverId));
   if (storage != null) {
     ServerTimeout timeout = storage.getTimeouts().remove(user.getId());
     saveServerConfig(serverConfig);
     if (timeout != null) {
       SafeNav.of(timeout.getTimerFuture()).ifPresent(f -> f.cancel(true));
       LOGGER.info(
           "Cancelling timeout for {} ({}) in {} ({})",
           user.getUsername(),
           user.getId(),
           server.getName(),
           serverId);
       apiClient.sendMessage(
           loc.localize("commands.mod.stoptimeout.response", user.getUsername(), user.getId()),
           invocationChannel);
       return;
     }
   }
   LOGGER.warn(
       "Unable to cancel: cannot find server or timeout entry for {} ({}) in {} ({})",
       user.getUsername(),
       user.getId(),
       server.getName(),
       server.getId());
   apiClient.sendMessage(
       loc.localize(
           "commands.mod.stoptimeout.response.not_found", user.getUsername(), user.getId()),
       invocationChannel);
 }
Esempio n. 20
0
  public void nick_name(String msg) {
    try {
      String name = msg.substring(13);
      this.setName(name);
      Vector v = father.onlineList;
      boolean isRepeatedName = false;
      int size = v.size();
      for (int i = 0; i < size; i++) {
        ServerAgentThread tempSat = (ServerAgentThread) v.get(i);
        if (tempSat.getName().equals(name)) {
          isRepeatedName = true;
          break;
        }
      }
      if (isRepeatedName == true) {
        dout.writeUTF("<#NAME_REPEATED#>");
        din.close();
        dout.close();
        sc.close();
        flag = false;
      } else {
        v.add(this);
        father.refreshList();
        String nickListMsg = "";
        StringBuilder nickListMsgSb = new StringBuilder();
        size = v.size();
        for (int i = 0; i < size; i++) {
          ServerAgentThread tempSat = (ServerAgentThread) v.get(i);
          nickListMsgSb.append("!");
          nickListMsgSb.append(tempSat.getName());
        }
        nickListMsgSb.append("<#NICK_LIST#>");
        nickListMsg = nickListMsgSb.toString();
        Vector tempv = father.onlineList;
        size = tempv.size();
        for (int i = 0; i < size; i++) {
          ServerAgentThread tempSat = (ServerAgentThread) tempv.get(i);
          tempSat.dout.writeUTF(nickListMsg);
          if (tempSat != this) {
            tempSat.dout.writeUTF("<#MSG#>" + this.getName() + "is now online....");
          }
        }
      }

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Esempio n. 21
0
 public Location getLocation(final String path, final Server server) throws InvalidWorldException {
   final String worldString = (path == null ? "" : path + ".") + "world";
   final String worldName = getString(worldString);
   if (worldName == null || worldName.isEmpty()) {
     return null;
   }
   final World world = server.getWorld(worldName);
   if (world == null) {
     throw new InvalidWorldException(worldName);
   }
   return new Location(
       world,
       getDouble((path == null ? "" : path + ".") + "x", 0),
       getDouble((path == null ? "" : path + ".") + "y", 0),
       getDouble((path == null ? "" : path + ".") + "z", 0),
       (float) getDouble((path == null ? "" : path + ".") + "yaw", 0),
       (float) getDouble((path == null ? "" : path + ".") + "pitch", 0));
 }
 public boolean banChecked(Channel channel, User author, User user, Server server) {
   String userId = user.getId();
   if (userId.equals(author.getId())) {
     apiClient.sendMessage("You cannot ban yourself", channel);
     return false;
   }
   if (userId.equals(apiClient.getClientUser().getId())) {
     apiClient.sendMessage("You cannot ban the bot", channel);
     return false;
   }
   if (bot.getCommands()
       .checkPermission(
           Permission.GEN_MANAGE_ROLES,
           apiClient.getUserMember(userId, server),
           server,
           apiClient)) {
     apiClient.sendMessage("You cannot ban an admin", channel);
     return false;
   }
   return banImpl(userId, server.getId());
 }
Esempio n. 23
0
  public void client_leave(String msg) {
    try {
      Vector tempv = father.onlineList;
      tempv.remove(this);
      int size = tempv.size();
      String nl = "<#NICK_LIST#>";
      for (int i = 0; i < size; i++) {
        ServerAgentThread tempSat = (ServerAgentThread) tempv.get(i);
        tempSat.dout.writeUTF("<#MSG#>" + this.getName() + "is offline....");
        nl = nl + "|" + tempSat.getName();
      }

      for (int i = 0; i < size; i++) {
        ServerAgentThread tempSat = (ServerAgentThread) tempv.get(i);
        tempSat.dout.writeUTF(nl);
      }
      this.flag = false;
      father.refreshList();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
 @Override
 public void placeItemForBid(
     String ownerName,
     String itemName,
     String itemDesc,
     double startBid,
     int auctionTime,
     String auctionType)
     throws RemoteException {
   List<Item> items = Server.getInstance().getItemList();
   BiddingStrategyValidator validator;
   if (auctionType.equals("English")) {
     validator = new EnglishAuctionBiddingStrategyValidator();
   } else {
     validator = new DutchAuctionBiddingStrategyValidator();
   }
   Item newItem =
       new Item(
           ownerName,
           itemName,
           itemDesc,
           startBid,
           null,
           auctionTime,
           validator,
           Calendar.getInstance());
   if (items.contains(newItem)) {
     throw new RemoteException("Item with that name already exists!");
   } else {
     items.add(newItem);
     System.out.println(
         "Wystawiono przedmiot "
             + newItem
             + " na aukcje typu "
             + newItem.getValidator().getClass().getName()
             + ".");
   }
 }
  /**
   * Method declaration
   *
   * @return
   */
  private Channel init() {

    try {
      mSocket.setTcpNoDelay(true);

      mInput = new DataInputStream(new BufferedInputStream(mSocket.getInputStream()));
      mOutput = new DataOutputStream(new BufferedOutputStream(mSocket.getOutputStream()));

      String user = mInput.readUTF();
      String password = mInput.readUTF();
      Channel c;

      try {
        mServer.trace(mThread + ":trying to connect user " + user);

        return mDatabase.connect(user, password);
      } catch (SQLException e) {
        write(new Result(e.getMessage()).getBytes());
      }
    } catch (Exception e) {
    }

    return null;
  }
  private void timeout(MessageContext context, String args) {
    Channel channel = context.getChannel();
    if (!args.isEmpty()) {
      String[] split = args.split(" ", 2);
      String uid = split[0];
      if (uid.length() > 4) {
        if (uid.startsWith("<@!")) {
          uid = uid.substring(3, uid.length() - 1);
        } else if (uid.startsWith("<@")) {
          uid = uid.substring(2, uid.length() - 1);
        }
        if (!uid.matches("[0-9]+")) {
          apiClient.sendMessage(loc.localize("commands.mod.stoptimeout.response.not_id"), channel);
          return;
        }
        Server server = context.getServer();
        String serverId = server.getId();
        User user = apiClient.getUserById(uid, server);
        if (user == NO_USER) {
          user = new User("UNKNOWN", uid, "", null);
        }
        final User theUser = user;
        if (split.length == 2) {
          if (bot.getConfig().isAdmin(user.getId())) {
            apiClient.sendMessage(
                "```API error: Server returned HTTP: 403 Forbidden. Check bot " + "permissions```",
                channel);
            return;
          }

          Duration duration = parseDuration(split[1]);
          if (applyTimeout(context.getAuthor(), channel, server, user, duration)) {
            return;
          }
        } else if (split.length == 1) {
          if (isUserTimedOut(user, server)) {
            ServerTimeout timeout =
                SafeNav.of(serverStorage.get(serverId))
                    .next(TempServerConfig::getServerTimeouts)
                    .next(ServerTimeoutStorage::getTimeouts)
                    .next(m -> m.get(theUser.getId()))
                    .get();
            //  Timeout cannot be null since we just checked
            User timeoutIssuer = apiClient.getUserById(timeout.getIssuedByUserId(), server);
            apiClient.sendMessage(
                loc.localize(
                    "commands.mod.timeout.response.check",
                    user.getUsername(),
                    user.getId(),
                    formatDuration(Duration.between(Instant.now(), timeout.getEndTime())),
                    formatInstant(timeout.getEndTime()),
                    timeoutIssuer.getUsername(),
                    timeout.getIssuedByUserId()),
                channel);
          } else {
            apiClient.sendMessage(
                loc.localize(
                    "commands.mod.timeout.response.check.not_found",
                    user.getUsername(),
                    user.getId()),
                channel);
          }
          return;
        } else {
          LOGGER.warn("Split length not 1 or 2, was {}: '{}'", split.length, args);
        }
      } else {
        LOGGER.warn("UID/mention not long enough: '{}'", args);
      }
    } else {
      LOGGER.warn("Args was empty");
    }
    apiClient.sendMessage(loc.localize("commands.mod.timeout.response.invalid"), channel);
  }
 public boolean doesTimeoutEntryExistForUser(User user, Server server) {
   return doesTimeoutEntryExistForUser(user.getId(), server.getId());
 }
 public boolean isUserTimedOut(User user, Server server) {
   return isUserTimedOut(user.getId(), server.getId());
 }
  public void loadServerConfig(Path path) {
    boolean purge = false;
    TempServerConfig config;
    ServerTimeoutStorage storage;
    try (Reader reader = Files.newBufferedReader(path, UTF_8)) {
      config = gson.fromJson(reader, TempServerConfig.class);
      serverStorage.put(config.getServerId(), config);
      storage = config.getServerTimeouts();
      if (storage != null) {
        Server server = apiClient.getServerByID(config.getServerId());
        if (server == NO_SERVER) {
          LOGGER.warn("Rejecting {} server storage file: server not found", config.getServerId());
          return;
        }
        LOGGER.info(
            "Loaded {} ({}) server storage file",
            server.getName(),
            server.getId(),
            storage.getTimeoutRoleId());
        //  Prune expired entries
        for (Iterator<Map.Entry<String, ServerTimeout>> iter =
                storage.getTimeouts().entrySet().iterator();
            iter.hasNext(); ) {
          Map.Entry<String, ServerTimeout> e = iter.next();
          ServerTimeout timeout = e.getValue();
          String userId = timeout.getUserId();
          User user = apiClient.getUserById(userId, server);
          if (!isUserTimedOut(userId, server.getId())) {
            //  Purge!
            purge = true;
            if (user == NO_USER) {
              LOGGER.info(
                  "Ending timeout for departed user {} ({}) in {} ({})",
                  timeout.getLastUsername(),
                  userId,
                  server.getName(),
                  server.getId());
              //
              // apiClient.sendMessage(loc.localize("message.mod.timeout.expire.not_found",
              //                                    user.getId()),
              //                                    server.getId());
              //  Don't need to remove the timeout role because leaving does that for us
            } else {
              //  Duplicated from onTimeoutExpire except without remove since we're removing in an
              // iter
              LOGGER.info(
                  "Expiring timeout for {} ({}) in {} ({})",
                  user.getUsername(),
                  user.getId(),
                  server.getName(),
                  server.getId());
              //  Only send message if they still have the role
              if (removeTimeoutRole(user, server, apiClient.getChannelById(server.getId()))) {
                //
                // apiClient.sendMessage(loc.localize("message.mod.timeout.expire",
                //                                        user.getId()),
                //                                        server.getId());
              }
            }
            SafeNav.of(timeout.getTimerFuture()).ifPresent(f -> f.cancel(true));
            iter.remove();
          } else {
            //  Start our futures
            Duration duration = Duration.between(Instant.now(), timeout.getEndTime());
            ScheduledFuture future =
                timeoutService.schedule(
                    () -> onTimeoutExpire(user, server), duration.getSeconds(), TimeUnit.SECONDS);
            timeout.setTimerFuture(future);
          }
        }
      }
    } catch (IOException | JsonParseException e) {
      LOGGER.warn("Unable to load server storage file " + path.toString(), e);
      return;
    }

    if (purge) {
      saveServerConfig(config);
    }
  }
Esempio n. 30
0
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("utf-8");
    if (jjNumber.isDigit(jjTools.getParameter(request, "maxSize"))) {
      maxSize = Long.parseLong(jjTools.getParameter(request, "maxSize"));
    }

    response.setCharacterEncoding("utf-8");
    String name = request.getParameter("name");
    name = name == null ? "" : name;
    response.setContentType("text/plain");
    super.init(getServletConfig());
    //        response.setContentType("text/plain");
    PrintWriter out = response.getWriter();
    //        out.println();

    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    //        fileItemFactory.setSizeThreshold(1024 * 1024); //1 MB

    try {
      ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
      List items = uploadHandler.parseRequest(request);
      Iterator itr = items.iterator();
      while (itr.hasNext()) {
        FileItem item = (FileItem) itr.next();
        if (item.isFormField()) {
          /*
           * Field
           */
          //                    out.println("Field Name=" + item.getFieldName() + ", Value=" +
          // item.getString());
          data.put(item.getFieldName(), item.getString());
        } else {
          /*
           * File
           */
          File folderAddress =
              new File(request.getServletContext().getRealPath(Save_Folder_Name)); // "/" +
          String extension = "";
          String nameWithoutExtension = item.getName();
          if (item.getName().lastIndexOf(".") > -1) {
            extension = item.getName().substring(item.getName().lastIndexOf("."));
            nameWithoutExtension =
                item.getName()
                    .substring(
                        item.getName().lastIndexOf("\\") + 1, item.getName().lastIndexOf("."));
          }
          folderAddress.mkdirs();
          nameWithoutExtension = "P";
          File file =
              new File(
                  folderAddress
                      + "/"
                      + nameWithoutExtension.toLowerCase()
                      + jjNumber.getRandom(10)
                      + extension.toLowerCase());
          String i = "0000000000";
          while (file.exists()) {
            i = jjNumber.getRandom(10);
            file =
                new File(
                    folderAddress
                        + "/"
                        + nameWithoutExtension.toLowerCase()
                        + i
                        + extension.toLowerCase());
          }
          if (!name.equals("")) {
            file = new File(folderAddress + "/" + name);
          }
          //                    out.println("File Name=" + item.getName()
          //                            + ", Field Name=" + item.getFieldName()
          //                            + ", Content type=" + item.getContentType()
          //                            + ", File Size=" + item.getSize()
          //                            + ", Save Address=" + file);
          //                    out.println(file);
          //                    String urlPath =
          // request.getRequestURL().toString().replace("Upload2", "Upload") + "/" +
          // file.getName().replace("\\", "/");
          //                    out.println("<html><head><meta http-equiv='Content-Type'
          // content='text/html; charset=utf-8'></head><body><input type='text' name='T1' size='58'
          // value='" + urlPath + "'></body></html>");
          data.put(item.getFieldName(), file.getAbsolutePath());
          if (!file.getName().toLowerCase().endsWith(".exe")) {
            item.write(file);
          }
          long size = file.length();
          ServerLog.Print("?>>>>>>" + file + "   -    Size:" + size);
          if (size > maxSize) {
            file.delete();
            out.print("big");
          } else {
            out.print(
                file.getName()
                    .replace(" ", "%20")
                    .replace("<pre style=\"word-wrap: break-word; white-space: pre-wrap;\">", ""));
            ServerLog.Print("Write pic in: " + file + " size:" + file.length());
            String name2 = file.getName().substring(0, file.getName().lastIndexOf("."));
            String extension2 =
                file.getName()
                    .substring(file.getName().lastIndexOf(".") + 1, file.getName().length());
            File file2 = new File(file.getParent() + "/" + name2 + "_small." + extension2);
            if (extension2.toLowerCase().equals("jpg")
                || extension2.toLowerCase().equals("png")
                || extension2.toLowerCase().equals("gif")) {
              jjPicture.doChangeSizeOfPic(file, file2, 250);
            }
          }
        }
      }
    } catch (Exception ex) {
      Server.ErrorHandler(ex);
    }
    out.flush();
    out.close();
  }