private void loadPlugins(Object source, Set<String> loadedPlugins, Iterable<String> plugins) {
    for (String plugin : plugins) {
      if (loadedPlugins.contains(plugin)) {
        SpongeImpl.getLogger().warn("Skipping duplicate plugin class {} from {}", plugin, source);
        continue;
      }

      try {
        Class<?> pluginClass = Class.forName(plugin);
        VanillaPluginContainer container = new VanillaPluginContainer(source, pluginClass);
        registerPlugin(container);
        loadedPlugins.add(plugin);
        SpongeImpl.getGame()
            .getEventManager()
            .registerListeners(container, container.getInstance().get());

        SpongeImpl.getLogger()
            .info(
                "Loaded plugin: {} {} (from {})",
                container.getName(),
                container.getVersion(),
                source);
      } catch (Throwable e) {
        SpongeImpl.getLogger().error("Failed to load plugin: {} (from {})", plugin, source, e);
      }
    }
  }
 @SuppressWarnings("unchecked")
 protected static boolean post(
     Event event,
     List<RegisteredListener<?>> listeners,
     boolean beforeModifications,
     boolean forced) {
   ModContainer oldContainer =
       ((IMixinLoadController) SpongeMod.instance.getController()).getActiveModContainer();
   for (@SuppressWarnings("rawtypes") RegisteredListener listener : listeners) {
     ((IMixinLoadController) SpongeMod.instance.getController())
         .setActiveModContainer((ModContainer) listener.getPlugin());
     try {
       if (forced
           || (!listener.isBeforeModifications() && !beforeModifications)
           || (listener.isBeforeModifications() && beforeModifications)) {
         listener.handle(event);
       }
     } catch (Throwable e) {
       SpongeImpl.getLogger()
           .error(
               "Could not pass {} to {}",
               event.getClass().getSimpleName(),
               listener.getPlugin(),
               e);
     }
   }
   ((IMixinLoadController) SpongeMod.instance.getController()).setActiveModContainer(oldContainer);
   return event instanceof Cancellable && ((Cancellable) event).isCancelled();
 }
  public void loadPlugins() throws IOException {
    for (PluginContainer container : SpongeVersion.getComponents()) {
      registerPlugin(container);
    }

    Set<String> plugins;
    Set<String> loadedPlugins = new HashSet<>();

    if (SCAN_CLASSPATH) {
      SpongeImpl.getLogger().info("Scanning classpath for plugins...");

      // Find plugins on the classpath
      plugins = PluginScanner.scanClassPath(Launch.classLoader);
      if (!plugins.isEmpty()) {
        loadPlugins("classpath", loadedPlugins, plugins);
      }
    }

    try (DirectoryStream<Path> dir =
        Files.newDirectoryStream(SpongeImpl.getPluginsDir(), ARCHIVE_FILTER)) {
      for (Path jar : dir) {
        // Search for plugins in the JAR
        plugins = PluginScanner.scanZip(jar);

        if (!plugins.isEmpty()) {
          // Add plugin to the classpath
          Launch.classLoader.addURL(jar.toUri().toURL());

          // Load the plugins
          loadPlugins(jar, loadedPlugins, plugins);
        }
      }
    }
  }
 private static void invokeCustomRegistration(RegistryModule module, Method method) {
   try {
     if (isCustomProperPhase(module)) {
       method.invoke(module);
     }
   } catch (IllegalAccessException | InvocationTargetException e) {
     SpongeImpl.getLogger()
         .error(
             "Error when calling custom catalog registration for module: "
                 + module.getClass().getCanonicalName(),
             e);
   }
 }
  public boolean post(
      Event spongeEvent,
      net.minecraftforge.fml.common.eventhandler.Event forgeEvent,
      IEventListener[] listeners) {
    checkNotNull(forgeEvent, "forgeEvent");

    if (spongeEvent == null) { // Fired by Forge
      spongeEvent = ((IMixinEvent) forgeEvent).createSpongeEvent();
    }
    RegisteredListener.Cache listenerCache = getHandlerCache(spongeEvent);
    // Fire events to plugins before modifications
    for (Order order : Order.values()) {
      post(spongeEvent, listenerCache.getListenersByOrder(order), true, false);
    }

    // If there are no forge listeners for event, skip sync
    if (listeners.length > 0) {
      // sync plugin data for Mods
      ((IMixinEvent) forgeEvent).syncDataToForge(spongeEvent);

      for (IEventListener listener : listeners) {
        try {
          listener.invoke(forgeEvent);
        } catch (Throwable throwable) {
          SpongeImpl.getLogger().catching(throwable);
        }
      }

      // sync Forge data for Plugins
      ((IMixinEvent) spongeEvent).syncDataToSponge(forgeEvent);
    }

    // Fire events to plugins after modifications (default)
    for (Order order : Order.values()) {
      post(spongeEvent, listenerCache.getListenersByOrder(order), false, false);
    }

    // sync plugin data for Forge
    ((IMixinEvent) forgeEvent).syncDataToForge(spongeEvent);

    if (spongeEvent instanceof Cancellable) {
      if (((Cancellable) spongeEvent).isCancelled()) {
        forgeEvent.setCanceled(true);
      }
    }
    return forgeEvent.isCancelable() && forgeEvent.isCanceled();
  }
 @SuppressWarnings("unchecked")
 private static Map<String, ?> getCatalogMap(RegistryModule module) {
   for (Field field : module.getClass().getDeclaredFields()) {
     RegisterCatalog annotation = field.getAnnotation(RegisterCatalog.class);
     if (annotation != null) {
       try {
         field.setAccessible(true);
         return (Map<String, ?>) field.get(module);
       } catch (Exception e) {
         SpongeImpl.getLogger()
             .error(
                 "Failed to retrieve a registry field from module: "
                     + module.getClass().getCanonicalName());
       }
     }
   }
   throw new IllegalStateException(
       "Registry module does not have a catalog map! Registry: "
           + module.getClass().getCanonicalName());
 }
 public static Location<World> findFirstMatchingBlock(
     Entity entity, AxisAlignedBB bb, Predicate<Block> predicate) {
   int i = MathHelper.floor_double(bb.minX);
   int j = MathHelper.floor_double(bb.maxX + 1.0D);
   int k = MathHelper.floor_double(bb.minY);
   int l = MathHelper.floor_double(bb.maxY + 1.0D);
   int i1 = MathHelper.floor_double(bb.minZ);
   int j1 = MathHelper.floor_double(bb.maxZ + 1.0D);
   for (int k1 = i; k1 < j; ++k1) {
     for (int l1 = k; l1 < l; ++l1) {
       for (int i2 = i1; i2 < j1; ++i2) {
         BlockPos blockPos = new BlockPos(k1, l1, i2);
         if (predicate.test(entity.worldObj.getBlockState(blockPos).getBlock())) {
           return new Location<>((World) entity.worldObj, k1, l1, i2);
         }
       }
     }
   }
   SpongeImpl.getLogger().error("Could not find a Source block!");
   return ((org.spongepowered.api.entity.Entity) entity).getLocation();
 }
Example #8
0
 // @formatter:on
 @Inject(method = "<init>", at = @At("RETURN"))
 public void onConstructed(
     ISaveHandler saveHandlerIn,
     WorldInfo info,
     WorldProvider providerIn,
     Profiler profilerIn,
     boolean client,
     CallbackInfo ci) {
   if (info == null) {
     SpongeImpl.getLogger()
         .warn(
             "World constructed without a WorldInfo! This will likely cause problems. Subsituting dummy info.",
             new RuntimeException("Stack trace:"));
     this.worldInfo =
         new WorldInfo(
             new WorldSettings(0, WorldSettings.GameType.NOT_SET, false, false, WorldType.DEFAULT),
             "sponge$dummy_world");
   }
   this.worldContext = new Context(Context.WORLD_KEY, this.worldInfo.getWorldName());
   if (SpongeImpl.getGame().getPlatform().getType() == Platform.Type.SERVER) {
     this.worldBorder.addListener(new PlayerBorderListener(providerIn.getDimensionId()));
   }
   this.activeConfig = SpongeHooks.getActiveConfig((net.minecraft.world.World) (Object) this);
 }
Example #9
0
  private String getResponse(HttpURLConnection con) throws IOException {
    InputStream is = null;
    try {
      is = con.getInputStream();
      ByteArrayOutputStream bos = new ByteArrayOutputStream();

      byte[] b = new byte[1024];
      int bytesRead;
      while ((bytesRead = is.read(b)) != -1) {
        bos.write(b, 0, bytesRead);
      }
      return bos.toString();

    } catch (IOException ex) {
      this.sender.sendMessage(
          Text.of(TextColors.RED, "Error uploading timings, check your logs for more information"));
      SpongeImpl.getLogger().warn(con.getResponseMessage(), ex);
      return null;
    } finally {
      if (is != null) {
        is.close();
      }
    }
  }
Example #10
0
  @Override
  public Optional<Entity> createEntity(EntityType type, Vector3d position) {
    checkNotNull(type, "The entity type cannot be null!");
    checkNotNull(position, "The position cannot be null!");

    Entity entity = null;

    Class<? extends Entity> entityClass = type.getEntityClass();
    double x = position.getX();
    double y = position.getY();
    double z = position.getZ();

    if (entityClass.isAssignableFrom(EntityPlayerMP.class)
        || entityClass.isAssignableFrom(EntityDragonPart.class)) {
      // Unable to construct these
      return Optional.empty();
    }

    net.minecraft.world.World world = (net.minecraft.world.World) (Object) this;

    // Not all entities have a single World parameter as their constructor
    if (entityClass.isAssignableFrom(EntityLightningBolt.class)) {
      entity = (Entity) new EntityLightningBolt(world, x, y, z);
    } else if (entityClass.isAssignableFrom(EntityEnderPearl.class)) {
      EntityArmorStand tempEntity = new EntityArmorStand(world, x, y, z);
      tempEntity.posY -= tempEntity.getEyeHeight();
      entity = (Entity) new EntityEnderPearl(world, tempEntity);
      ((EnderPearl) entity).setShooter(ProjectileSource.UNKNOWN);
    }

    // Some entities need to have non-null fields (and the easiest way to
    // set them is to use the more specialised constructor).
    if (entityClass.isAssignableFrom(EntityFallingBlock.class)) {
      entity = (Entity) new EntityFallingBlock(world, x, y, z, Blocks.sand.getDefaultState());
    } else if (entityClass.isAssignableFrom(EntityItem.class)) {
      entity = (Entity) new EntityItem(world, x, y, z, new ItemStack(Blocks.stone));
    }

    if (entity == null) {
      try {
        entity = ConstructorUtils.invokeConstructor(entityClass, this);
        ((net.minecraft.entity.Entity) entity).setPosition(x, y, z);
      } catch (Exception e) {
        SpongeImpl.getLogger().error(ExceptionUtils.getStackTrace(e));
      }
    }

    // TODO - replace this with an actual check
    /*
    if (entity instanceof EntityHanging) {
        if (((EntityHanging) entity).facingDirection == null) {
            // TODO Some sort of detection of a valid direction?
            // i.e scan immediate blocks for something to attach onto.
            ((EntityHanging) entity).facingDirection = EnumFacing.NORTH;
        }
        if (!((EntityHanging) entity).onValidSurface()) {
            return Optional.empty();
        }
    }*/

    // Last chance to fix null fields
    if (entity instanceof EntityPotion) {
      // make sure EntityPotion.potionDamage is not null
      ((EntityPotion) entity).getPotionDamage();
    } else if (entity instanceof EntityPainting) {
      // This is default when art is null when reading from NBT, could
      // choose a random art instead?
      ((EntityPainting) entity).art = EnumArt.KEBAB;
    }

    return Optional.ofNullable(entity);
  }
Example #11
0
  @Override
  public void run() {
    this.sender.sendMessage(Text.of(TextColors.GREEN, "Preparing Timings Report..."));

    this.out.add("data", JSONUtil.mapArray(this.history, TimingHistory::export));

    String response = null;
    try {
      HttpURLConnection con =
          (HttpURLConnection) new URL("http://timings.aikar.co/post").openConnection();
      con.setDoOutput(true);
      con.setRequestProperty(
          "User-Agent",
          "Sponge/" + getServerName() + "/" + InetAddress.getLocalHost().getHostName());
      con.setRequestMethod("POST");
      con.setInstanceFollowRedirects(false);

      OutputStream request =
          new GZIPOutputStream(con.getOutputStream()) {

            {
              this.def.setLevel(7);
            }
          };

      request.write(JSONUtil.toString(this.out).getBytes("UTF-8"));
      request.close();

      response = getResponse(con);

      if (con.getResponseCode() != 302) {
        this.sender.sendMessage(
            Text.of(
                TextColors.RED,
                "Upload Error: " + con.getResponseCode() + ": " + con.getResponseMessage()));
        this.sender.sendMessage(Text.of(TextColors.RED, "Check your logs for more information"));
        if (response != null) {
          SpongeImpl.getLogger().fatal(response);
        }
        return;
      }

      String location = con.getHeaderField("Location");
      this.sender.sendMessage(
          Text.of(
              TextColors.GREEN,
              "View Timings Report: ",
              TextActions.openUrl(new URL(location)),
              location));
      if (!(this.sender instanceof ConsoleSource)) {
        SpongeImpl.getLogger().info("View Timings Report: " + location);
      }

      if (response != null && !response.isEmpty()) {
        SpongeImpl.getLogger().info("Timing Response: " + response);
      }
    } catch (IOException ex) {
      this.sender.sendMessage(
          Text.of(TextColors.RED, "Error uploading timings, check your logs for more information"));
      if (response != null) {
        SpongeImpl.getLogger().fatal(response);
      }
      SpongeImpl.getLogger().fatal("Could not paste timings", ex);
    }
  }
Example #12
0
  TimingHistory() {
    this.endTime = System.currentTimeMillis() / 1000;
    this.startTime = TimingsManager.historyStart / 1000;
    if (timedTicks % 1200 != 0 || MINUTE_REPORTS.isEmpty()) {
      this.minuteReports = MINUTE_REPORTS.toArray(new MinuteReport[MINUTE_REPORTS.size() + 1]);
      this.minuteReports[this.minuteReports.length - 1] = new MinuteReport();
    } else {
      this.minuteReports = MINUTE_REPORTS.toArray(new MinuteReport[MINUTE_REPORTS.size()]);
    }
    long ticks = 0;
    for (MinuteReport mp : this.minuteReports) {
      ticks += mp.ticksRecord.timed;
    }
    this.totalTicks = ticks;
    this.totalTime = FULL_SERVER_TICK.record.totalTime;
    this.entries = new TimingHistoryEntry[TimingsManager.HANDLERS.size()];

    int i = 0;
    for (TimingHandler handler : TimingsManager.HANDLERS) {
      this.entries[i++] = new TimingHistoryEntry(handler);
    }

    final Map<EntityType, Counter> entityCounts =
        MRUMapCache.of(LoadingMap.of(Maps.newHashMap(), Counter.loader()));
    final Map<BlockType, Counter> tileEntityCounts =
        MRUMapCache.of(LoadingMap.of(Maps.newHashMap(), Counter.loader()));
    // Information about all loaded chunks/entities
    this.worlds =
        JSONUtil.mapArrayToObject(
            SpongeImpl.getGame().getServer().getWorlds(),
            (world) -> {
              return JSONUtil.singleObjectPair(
                  String.valueOf(worldMap.get(world.getName())),
                  JSONUtil.mapArray(
                      world.getLoadedChunks(),
                      (chunk) -> {
                        entityCounts.clear();
                        tileEntityCounts.clear();

                        for (Entity entity : chunk.getEntities()) {
                          if (entity.getType() == null) {
                            SpongeImpl.getLogger().error("Entity is not registered {}", entity);
                            continue;
                          }
                          entityCounts.get(entity.getType()).increment();
                        }

                        for (TileEntity tileEntity : chunk.getTileEntities()) {
                          tileEntityCounts.get(tileEntity.getBlock().getType()).increment();
                        }

                        if (tileEntityCounts.isEmpty() && entityCounts.isEmpty()) {
                          return null;
                        }
                        return JSONUtil.arrayOf(
                            chunk.getPosition().getX(),
                            chunk.getPosition().getZ(),
                            JSONUtil.mapArrayToObject(
                                entityCounts.entrySet(),
                                (entry) -> {
                                  if (entry.getKey() == EntityTypes.UNKNOWN) {
                                    return null;
                                  }
                                  this.entityTypeSet.add(entry.getKey());
                                  return JSONUtil.singleObjectPair(
                                      ((SpongeEntityType) entry.getKey()).entityTypeId,
                                      entry.getValue().count());
                                }),
                            JSONUtil.mapArrayToObject(
                                tileEntityCounts.entrySet(),
                                (entry) -> {
                                  this.blockTypeSet.add(entry.getKey());
                                  return JSONUtil.singleObjectPair(
                                      Block.getIdFromBlock((Block) entry.getKey()),
                                      entry.getValue().count());
                                }));
                      }));
            });
  }