Skip to content

Instantly share code, notes, and snippets.

@ThomasGaubert
Created December 23, 2011 06:07
Show Gist options
  • Save ThomasGaubert/1513337 to your computer and use it in GitHub Desktop.
Save ThomasGaubert/1513337 to your computer and use it in GitHub Desktop.
MapPad Ads
package com.sk89q.mappad.apps;
import java.awt.Color;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import org.bukkit.entity.Player;
import org.bukkit.map.MapCanvas;
import org.bukkit.map.MapPalette;
import com.sk89q.mappad.AbstractApplication;
import com.sk89q.mappad.MapPad;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException;
import com.sk89q.rebar.util.MapCanvasUtil;
public class AdApp extends AbstractApplication {
private static final Logger logger = Logger.getLogger(ImgurBrowser.class.getCanonicalName());
private static AdManager manager = new AdManager();
private int lastImageHash = -1;
private boolean hasDrawn = false;
private Random rand = new Random();
public AdApp(MapPad mapPad, Player player) {
super(mapPad, player);
}
public void draw(MapCanvas canvas) {
int index = rand.nextInt(manager.getLength());
Image image = manager.getImage(index);
if (image == null && lastImageHash == -1 && !hasDrawn) {
MapCanvasUtil.clear(canvas, Color.BLACK);
MapCanvasUtil.drawText(canvas, 30, 50, "No ads loaded", MapPalette.LIGHT_GRAY);
MapCanvasUtil.drawText(canvas, 40, 58, "Use >help", MapPalette.LIGHT_GRAY);
MapCanvasUtil.drawText(canvas, 0, 120, "AdSheet 0.1 - TexasGamer", MapPalette.LIGHT_GRAY);
drawTitle(canvas,"AdSheet");
lastImageHash = 0;
} else if (image != null && image.hashCode() != lastImageHash && !hasDrawn) {
MapCanvasUtil.clear(canvas, Color.WHITE);
canvas.drawImage(0, TITLE_HEIGHT, image);
lastImageHash = image.hashCode();
String playerName = manager.getPlayerName(index);
print("Advertisement purchased by " + playerName);
// TODO: Deduct 1 credit from playerName
print("** 1 credit deducted from " + playerName +"'s account **");
drawTitle(canvas, "AdSheet");
hasDrawn = true;
}
}
public void accept(CommandContext context) throws CommandException {
if (context.matches("help")) {
print(">buy <imgur code> <credits> to purchase. Ads are displayed at random. Fees: 1 credit per view");
}
if (context.matches("buy")) {
if (context.argsLength() < 2) {
throw new CommandException("Imgur ID and credit amount required");
}
String id = context.getString(0);
if (!id.matches("^[A-Za-z0-9\\-]+$")) {
throw new CommandException("Invalid Imgur ID " + id + " entered");
}
if (manager.request(id, getPlayer())) {
MapPad.print(getPlayer(), "Loading " + id + "...");
} else {
throw new CommandException("Please wait a few seconds and try again.");
}
}
}
public void quit() {
// TODO Auto-generated method stub
hasDrawn = false;
}
private static class AdManager {
private boolean busy = false;
private long lastSuccessfulRequest = 0;
private int lastImageIndex = -1;
private Image[] image = new Image[5]; // # of ads to store
private String[] playerName = new String[5]; // # of ads to store
public boolean request(String id, Player player) {
synchronized(this) {
if (busy || (System.currentTimeMillis() - lastSuccessfulRequest < 2000)) {
return false;
} else {
busy = true;
}
}
Thread thread = new Thread(new AdFetcher(this, id, player));
thread.start();
return true;
}
public Image getImage(int index) {
return image[index];
}
public String getPlayerName(int index) {
return playerName[index];
}
public int getLength(){
return image.length;
}
public void failRequest() {
synchronized(this) {
busy = false;
}
}
public void setImage(Image newImage, Player player) {
synchronized(this) {
busy = false;
lastSuccessfulRequest = System.currentTimeMillis();
}
lastImageIndex++;
image[lastImageIndex] = newImage;
playerName[lastImageIndex] = player.getName();
}
}
private static class AdFetcher implements Runnable {
private String id;
private AdManager manager;
private Player player;
public AdFetcher(AdManager manager, String id, Player player) {
this.manager = manager;
this.id = id;
this.player = player;
}
public void run() {
try {
URL url = new URL("http://i.imgur.com/" + id + ".png");
logger.info("AdSheet: Loading " + url.toString() + " for " + player.getName());
URLConnection conn = url.openConnection();
conn.setConnectTimeout(2000);
conn.setReadTimeout(10000);
BufferedImage image = ImageIO.read(conn.getInputStream());
manager.setImage(image.getScaledInstance(128, 128 - TITLE_HEIGHT, BufferedImage.SCALE_FAST), player);
logger.info("AdSheet: Loaded " + url.toString() + " successfully");
} catch (FileNotFoundException e) {
logger.log(Level.WARNING, "ImgurBrowser: Failed to load image from Imgur", e);
MapPad.print(player, "Image " + id + " was not found on Imgur.com");
manager.failRequest();
} catch (IOException e) {
logger.log(Level.WARNING, "ImgurBrowser: Failed to load image from Imgur", e);
MapPad.print(player, "Image " + id + " could not load: " + e.getMessage());
manager.failRequest();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment