Search in sources :

Example 11 with Campaign

use of com.xrtb.common.Campaign in project XRTB by benmfaul.

the class MyReader method testSetup.

@BeforeClass
public static void testSetup() {
    try {
        DbTools tools = new DbTools("localhost:3000");
        tools.clear();
        tools.loadDatabase("database.json");
        if (server == null) {
            server = new RTBServer("./Campaigns/payday.json");
            int wait = 0;
            while (!server.isReady() && wait < 10) {
                Thread.sleep(1000);
                wait++;
            }
            if (wait == 10) {
                fail("Server never started");
            }
            Thread.sleep(1000);
        } else {
            Configuration c = Configuration.getInstance();
            c.campaignsList.clear();
            User u = DataBaseObject.getInstance().get("ben");
            for (Campaign camp : u.campaigns) {
                c.addCampaign("ben", camp.adId);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.toString());
    }
}
Also used : RTBServer(com.xrtb.bidder.RTBServer) User(com.xrtb.db.User) Campaign(com.xrtb.common.Campaign) Configuration(com.xrtb.common.Configuration) DbTools(com.xrtb.tools.DbTools) BeforeClass(org.junit.BeforeClass)

Example 12 with Campaign

use of com.xrtb.common.Campaign in project XRTB by benmfaul.

the class AddShutdownHook method handle.

/**
	 * Handle the HTTP request. Basically a list of if statements that
	 * encapsulate the various HTTP requests to be handled. The server makes no
	 * distinction between POST and GET and ignores DELETE>
	 * <p>
	 * >
	 * 
	 * @throws IOException
	 *             if there is an error reading a resource.
	 * @throws ServletException
	 *             if the container encounters a servlet problem.
	 */
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    response.addHeader("Access-Control-Allow-Origin", "*");
    response.addHeader("Access-Control-Allow-Headers", "Content-Type");
    InputStream body = request.getInputStream();
    String type = request.getContentType();
    BidRequest br = null;
    ;
    String json = "{}";
    String id = "";
    Campaign campaign = null;
    boolean unknown = true;
    RTBServer.handled++;
    int code = RTBServer.BID_CODE;
    baseRequest.setHandled(true);
    long time = System.currentTimeMillis();
    boolean isGzip = false;
    response.setHeader("X-INSTANCE", config.instanceName);
    if (request.getHeader("Content-Encoding") != null && request.getHeader("Content-Encoding").equals("gzip"))
        isGzip = true;
    /*
		 * Uncomment to inspect headers if (1 == 1) { Enumeration headerNames =
		 * request.getHeaderNames(); StringBuilder sb = new
		 * StringBuilder("Header, Target: "); sb.append(target); while
		 * (headerNames.hasMoreElements()) { String headerName = (String)
		 * headerNames.nextElement(); String value =
		 * request.getHeader(headerName); sb.append(headerName);
		 * sb.append(": "); sb.append(value); sb.append("\n"); } try {
		 * Controller.getInstance().sendLog(2, "Header Info", sb.toString()); }
		 * catch (Exception e) { } }
		 */
    // System.out.println("------------>" + target);
    /**
		 * This set of if's handle the bid request transactions.
		 */
    BidRequest x = null;
    try {
        /**
			 * Convert the uri to a bid request object based on the exchange..
			 */
        BidResponse bresp = null;
        x = RTBServer.exchanges.get(target);
        if (x != null) {
            if (BidRequest.compilerBusy()) {
                baseRequest.setHandled(true);
                response.setHeader("X-REASON", "Server initializing");
                response.setStatus(RTBServer.NOBID_CODE);
                return;
            }
            RTBServer.request++;
            if (x == null) {
                json = "Wrong target: " + target + " is not configured.";
                code = RTBServer.NOBID_CODE;
                Controller.getInstance().sendLog(2, "Handler:handle:error", json);
                RTBServer.error++;
                System.out.println("=============> Wrong target: " + target + " is not configured.");
                baseRequest.setHandled(true);
                response.setStatus(code);
                response.setHeader("X-REASON", json);
                response.getWriter().println("{}");
                return;
            } else {
                unknown = false;
                if (isGzip)
                    body = new GZIPInputStream(body);
                br = x.copy(body);
                br.incrementRequests();
                id = br.getId();
                if (Configuration.getInstance().logLevel == -6) {
                    synchronized (Handler.class) {
                        dumpRequestInfo(target, request);
                        System.out.println(br.getOriginal());
                        RTBServer.nobid++;
                        Controller.getInstance().sendNobid(new NobidResponse(br.id, br.getExchange()));
                        response.setStatus(br.returnNoBidCode());
                        response.setContentType(br.returnContentType());
                        baseRequest.setHandled(true);
                        response.setHeader("X-REASON", "debugging");
                        return;
                    }
                }
                if (br.blackListed) {
                    if (br.id.equals("123") || Configuration.getInstance().printNoBidReason) {
                        Controller.getInstance().sendLog(1, "BidRequest:setup:blacklisted", br.id + ", site/app.domain = " + br.siteDomain);
                    }
                    RTBServer.nobid++;
                    Controller.getInstance().sendNobid(new NobidResponse(br.id, br.getExchange()));
                    response.setStatus(br.returnNoBidCode());
                    response.setContentType(br.returnContentType());
                    response.setHeader("X-REASON", "master-black-list");
                    baseRequest.setHandled(true);
                    br.writeNoBid(response, time);
                    Controller.getInstance().sendRequest(br, false);
                    return;
                }
                if (!br.forensiqPassed()) {
                    code = RTBServer.NOBID_CODE;
                    RTBServer.nobid++;
                    RTBServer.fraud++;
                    Controller.getInstance().sendNobid(new NobidResponse(br.id, br.getExchange()));
                    Controller.getInstance().publishFraud(br.fraudRecord);
                }
                if (RTBServer.server.getThreadPool().isLowOnThreads()) {
                    if (br.id.equals("123")) {
                        Controller.getInstance().sendLog(3, "RTBSerrver:handler", "Server throttled, low on threads");
                    } else {
                        code = RTBServer.NOBID_CODE;
                        json = "Server throttling";
                        RTBServer.nobid++;
                        response.setStatus(br.returnNoBidCode());
                        response.setContentType(br.returnContentType());
                        baseRequest.setHandled(true);
                        br.writeNoBid(response, time);
                        Controller.getInstance().sendRequest(br, false);
                        return;
                    }
                }
                if (CampaignSelector.getInstance().size() == 0) {
                    if (br.id.equals("123")) {
                        Controller.getInstance().sendLog(3, "RTBSerrver:handler", "No campaigns loaded");
                    }
                    json = br.returnNoBid("No campaigns loaded");
                    code = RTBServer.NOBID_CODE;
                    RTBServer.nobid++;
                    Controller.getInstance().sendNobid(new NobidResponse(br.id, br.getExchange()));
                } else if (RTBServer.stopped || RTBServer.paused) {
                    if (br.id.equals("123")) {
                        Controller.getInstance().sendLog(3, "RTBSerrver:handler", "Server stopped");
                    }
                    json = br.returnNoBid("Server stopped");
                    code = RTBServer.NOBID_CODE;
                    RTBServer.nobid++;
                    Controller.getInstance().sendNobid(new NobidResponse(br.id, br.getExchange()));
                } else if (!checkPercentage()) {
                    json = br.returnNoBid("Server throttled");
                    if (br.id.equals("123")) {
                        Controller.getInstance().sendLog(3, "RTBSerrver:handler", "Percentage throttled");
                    }
                    code = RTBServer.NOBID_CODE;
                    RTBServer.nobid++;
                    Controller.getInstance().sendNobid(new NobidResponse(br.id, br.getExchange()));
                } else {
                    // they are handled here.
                    if (br.notABidRequest()) {
                        code = br.getNonBidReturnCode();
                        json = br.getNonBidRespose();
                    } else {
                        bresp = CampaignSelector.getInstance().getMaxConnections(br);
                        // log.add("select");
                        if (bresp == null) {
                            code = RTBServer.NOBID_CODE;
                            json = br.returnNoBid("No matching campaign");
                            code = RTBServer.NOBID_CODE;
                            RTBServer.nobid++;
                            Controller.getInstance().sendNobid(new NobidResponse(br.id, br.getExchange()));
                        } else {
                            code = RTBServer.BID_CODE;
                            if (!bresp.isNoBid()) {
                                br.incrementBids();
                                //if (Configuration.requstLogStrategy == Configuration.REQUEST_STRATEGY_BIDS)
                                //	Controller.getInstance().sendRequest(br);
                                Controller.getInstance().sendBid(br, bresp);
                                Controller.getInstance().recordBid(bresp);
                                Controller.getInstance().sendRequest(br, true);
                                RTBServer.bid++;
                            }
                        }
                    }
                }
            // log.dump();
            }
            time = System.currentTimeMillis() - time;
            response.setHeader("X-TIME", Long.toString(time));
            RTBServer.xtime += time;
            // "application/json;charset=utf-8");
            response.setContentType(br.returnContentType());
            if (code == 204) {
                response.setHeader("X-REASON", json);
                if (Configuration.getInstance().printNoBidReason)
                    System.out.println("No bid: " + json);
                response.setStatus(br.returnNoBidCode());
            }
            baseRequest.setHandled(true);
            if (code == 200) {
                RTBServer.totalBidTime.addAndGet(time);
                RTBServer.bidCountWindow.incrementAndGet();
                response.setStatus(code);
                // a no-bid or bid
                if (bresp != null)
                    bresp.writeTo(response);
            } else {
                br.writeNoBid(response, time);
                // Send the request to the log, if it was suppressed
                Controller.getInstance().sendRequest(br, false);
            }
            return;
        }
        // //////////////////////////////////////////////////////////////////////
        if (target.contains("/rtb/win")) {
            StringBuffer url = request.getRequestURL();
            String queryString = request.getQueryString();
            response.setStatus(HttpServletResponse.SC_OK);
            json = "";
            if (queryString != null) {
                url.append('?');
                url.append(queryString);
            }
            String requestURL = url.toString();
            try {
                json = WinObject.getJson(requestURL);
                if (json == null) {
                }
                RTBServer.win++;
            } catch (Exception error) {
                response.setHeader("X-ERROR", "Error processing win response");
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                Controller.getInstance().sendLog(2, "Handler:handle", "Bad win response " + requestURL);
                error.printStackTrace();
            }
            response.setContentType("text/html;charset=utf-8");
            baseRequest.setHandled(true);
            response.getWriter().println(json);
            return;
        }
        if (target.contains("/pixel")) {
            Controller.getInstance().publishPixel(target);
            response.setContentType("image/bmp;charset=utf-8");
            response.setStatus(HttpServletResponse.SC_OK);
            baseRequest.setHandled(true);
            response.getWriter().println("");
            RTBServer.pixels++;
            return;
        }
        if (target.contains("/redirect")) {
            Controller.getInstance().publishClick(target);
            StringBuffer url = request.getRequestURL();
            String queryString = request.getQueryString();
            String[] params = null;
            if (queryString != null)
                params = queryString.split("url=");
            baseRequest.setHandled(true);
            if (params != null) {
                response.sendRedirect(URLDecoder.decode(params[1], "UTF-8"));
            }
            RTBServer.clicks++;
            return;
        }
        if (target.contains("pinger")) {
            response.setStatus(200);
            response.setContentType("text/html;charset=utf-8");
            baseRequest.setHandled(true);
            response.getWriter().println("OK");
            return;
        }
        if (target.contains("summary")) {
            response.setContentType("text/javascript;charset=utf-8");
            response.setStatus(HttpServletResponse.SC_OK);
            baseRequest.setHandled(true);
            response.getWriter().println(RTBServer.getSummary());
            return;
        }
        if (target.contains("favicon")) {
            // don't count this useless turd.
            RTBServer.handled--;
            response.setStatus(HttpServletResponse.SC_OK);
            baseRequest.setHandled(true);
            response.getWriter().println("");
            return;
        }
        if (RTBServer.adminHandler != null) {
            baseRequest.setHandled(true);
            response.setStatus(404);
            Controller.getInstance().sendLog(2, "Handler:handle", "Error: wrong request for admin login:" + getIpAddress(request) + ", target = " + target);
            RTBServer.error++;
        } else {
            AdminHandler admin = new AdminHandler();
            admin.handle(target, baseRequest, request, response);
            return;
        }
    } catch (Exception error) {
        //
        if (error.toString().contains("Parse")) {
            if (br != null) {
                br.incrementErrors();
                try {
                    Controller.getInstance().sendLog(1, "Handler:handle", "Error: Bad JSON from " + br.getExchange() + ": " + error.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        if (error.toString().contains("Aerospike")) {
            AerospikeHandler.reset();
        }
        ////////////////////////////////////////////////////////////////////////////
        RTBServer.error++;
        String exchange = target;
        if (x != null) {
            x.incrementErrors();
            exchange = x.getExchange();
        }
        StringWriter errors = new StringWriter();
        error.printStackTrace(new PrintWriter(errors));
        if (errors.toString().contains("fasterxml")) {
            try {
                Controller.getInstance().sendLog(4, "Handler:handle", "Error: bad JSON data from " + exchange + ", error = " + error.toString());
            } catch (Exception e) {
                error.printStackTrace();
            }
        }
        //else
        //error.printStackTrace();
        response.setStatus(RTBServer.NOBID_CODE);
    }
}
Also used : GZIPInputStream(java.util.zip.GZIPInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) AerospikeHandler(com.aerospike.redisson.AerospikeHandler) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) SessionHandler(org.eclipse.jetty.server.session.SessionHandler) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) BidRequest(com.xrtb.pojo.BidRequest) GZIPInputStream(java.util.zip.GZIPInputStream) Campaign(com.xrtb.common.Campaign) StringWriter(java.io.StringWriter) NobidResponse(com.xrtb.pojo.NobidResponse) BidResponse(com.xrtb.pojo.BidResponse) PrintWriter(java.io.PrintWriter)

Example 13 with Campaign

use of com.xrtb.common.Campaign in project XRTB by benmfaul.

the class CampaignSelector method getMaxConnections.

public BidResponse getMaxConnections(BidRequest br) throws Exception {
    // Don't proces if there was an error forming the original bid request.
    if (br.notABidRequest())
        return null;
    // The impression we selected
    Impression impression;
    // RunRecord record = new RunRecord("Campaign-Selector");
    if (br.blackListed)
        return null;
    long xtime = System.currentTimeMillis();
    Campaign test = null;
    SelectedCreative select = null;
    int kount = 0;
    List<Campaign> list = new ArrayList<Campaign>(config.campaignsList);
    Collections.shuffle(list);
    List<SelectedCreative> candidates = new ArrayList();
    boolean exchangeIsAdx = br.getExchange().equals("adx");
    while (kount < list.size()) {
        try {
            test = list.get(kount);
        } catch (Exception error) {
            Controller.getInstance().sendLog(3, "CampaignSelector:getMaxConnections", "Campaign was stale, in the selection list");
            return null;
        }
        if (test.isAdx == exchangeIsAdx) {
            CampaignProcessor p = new CampaignProcessor(test, br, null, null);
            // executor.execute(p);
            p.run();
            select = p.getSelectedCreative();
            if (select != null) {
                if (Configuration.getInstance().multibid)
                    candidates.add(select);
                else
                    break;
            }
        }
        kount++;
    }
    if (select == null && candidates.size() == 0)
        return null;
    xtime = System.currentTimeMillis() - xtime;
    // BidResponse winner = br.buildNewBidResponse(select.getCampaign(),
    // select.getCreative(), (int)xtime);
    BidResponse winner = null;
    if (!Configuration.getInstance().multibid)
        winner = br.buildNewBidResponse(select.getImpression(), select.getCampaign(), select.getCreative(), select.getPrice(), select.getDealId(), (int) xtime);
    else {
        winner = br.buildNewBidResponse(select.getImpression(), candidates, (int) xtime);
    }
    winner.capSpec = select.capSpec;
    try {
        if (Configuration.getInstance().printNoBidReason)
            Controller.getInstance().sendLog(Configuration.getInstance().logLevel, "CampaignProcessor:run:campaign-selected-winner", select.campaign.adId + "/" + select.creative.impid);
    } catch (Exception error) {
    }
    return winner;
}
Also used : Campaign(com.xrtb.common.Campaign) ArrayList(java.util.ArrayList) Impression(com.xrtb.pojo.Impression) BidResponse(com.xrtb.pojo.BidResponse)

Example 14 with Campaign

use of com.xrtb.common.Campaign in project XRTB by benmfaul.

the class CampaignSelector method getSpecific.

/**
	 * Creates a forced bid response on the specified bid request. owner,
	 * campaign and creative.
	 * 
	 * @param br
	 *            BidRequest. The request from the exchange.
	 * @param owner
	 *            String. The account owner of the campaign.
	 * @param campaignName
	 *            String. The campaign adid.
	 * @param creativeName
	 *            String. The creative id in the campaign.
	 * @return BidResponse. The response from the
	 */
public BidResponse getSpecific(BidRequest br, String owner, String campaignName, String creativeName) throws Exception {
    long xtime = System.currentTimeMillis();
    Campaign camp = null;
    Creative creative = null;
    for (Campaign c : config.campaignsList) {
        if (c.owner.equals(owner) && c.adId.equals(campaignName)) {
            camp = c;
            break;
        }
    }
    if (camp == null) {
        System.out.println("Can't find specification " + owner + "/" + campaignName);
        return null;
    }
    for (Creative cr : camp.creatives) {
        if (cr.impid.equals(creativeName)) {
            creative = cr;
            break;
        }
    }
    if (creative == null) {
        System.out.println("Can't find creative " + creative + " for " + owner + "/" + campaignName);
        return null;
    }
    String h = creative.strH;
    String w = creative.strW;
    int oldH = creative.h;
    int oldW = creative.w;
    Impression imp = br.getImpression(0);
    creative.strW = "" + imp.w;
    creative.strH = "" + imp.h;
    creative.w = imp.w;
    creative.h = imp.h;
    try {
        for (int i = 0; i < camp.attributes.size(); i++) {
            Node n = camp.attributes.get(i);
            if (n.test(br) == false) {
                if (Configuration.getInstance().printNoBidReason)
                    Controller.getInstance().sendLog(5, "CampaignProcessor:run:attribute-failed", camp.adId + "/" + creative.impid + ": " + n.hierarchy + " doesn't match the bidrequest");
                creative.strH = h;
                creative.strW = w;
                creative.w = oldW;
                creative.h = oldH;
                // don't bid
                return null;
            }
        }
    } catch (Exception error) {
        error.printStackTrace();
    }
    xtime = System.currentTimeMillis() - xtime;
    BidResponse winner = br.buildNewBidResponse(imp, camp, creative, creative.price, null, (int) xtime);
    creative.strH = h;
    creative.strW = w;
    creative.w = oldW;
    creative.h = oldH;
    return winner;
}
Also used : Campaign(com.xrtb.common.Campaign) Creative(com.xrtb.common.Creative) Node(com.xrtb.common.Node) Impression(com.xrtb.pojo.Impression) BidResponse(com.xrtb.pojo.BidResponse)

Example 15 with Campaign

use of com.xrtb.common.Campaign in project XRTB by benmfaul.

the class WebCampaign method showCreative.

/**
	 * Creates a sample output from a campaign creative.
	 * 
	 * @param m
	 *            Map. The command parameters.
	 * @return String. The JSON encoded return from the command.
	 * @throws Exception
	 *             on aerorpike/cache2k errors.
	 */
public String showCreative(Map m) throws Exception {
    Map rets = new HashMap();
    rets.put("creative", "YOU ARE HERE");
    String adid = (String) m.get("adid");
    String crid = (String) m.get("impid");
    String user = (String) m.get("name");
    for (Campaign campaign : Configuration.getInstance().campaignsList) {
        if (campaign.owner.equals(user) && campaign.adId.equals(adid)) {
            for (Creative c : campaign.creatives) {
                if (c.impid.equals(crid)) {
                    rets.put("creative", c.createSample(campaign));
                    return getString(rets);
                }
            }
        }
    }
    rets.put("creative", "No such creative");
    return getString(rets);
}
Also used : Campaign(com.xrtb.common.Campaign) AddCampaign(com.xrtb.commands.AddCampaign) DeleteCampaign(com.xrtb.commands.DeleteCampaign) Creative(com.xrtb.common.Creative) HashMap(java.util.HashMap) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

Campaign (com.xrtb.common.Campaign)27 User (com.xrtb.db.User)13 ArrayList (java.util.ArrayList)9 Test (org.junit.Test)9 Configuration (com.xrtb.common.Configuration)7 List (java.util.List)7 Creative (com.xrtb.common.Creative)6 RTBServer (com.xrtb.bidder.RTBServer)5 Node (com.xrtb.common.Node)5 BidRequest (com.xrtb.pojo.BidRequest)5 DbTools (com.xrtb.tools.DbTools)5 HashMap (java.util.HashMap)5 Map (java.util.Map)5 JsonNode (com.fasterxml.jackson.databind.JsonNode)4 AddCampaign (com.xrtb.commands.AddCampaign)4 DeleteCampaign (com.xrtb.commands.DeleteCampaign)4 SelectedCreative (com.xrtb.bidder.SelectedCreative)3 BidResponse (com.xrtb.pojo.BidResponse)3 HttpPostGet (com.xrtb.common.HttpPostGet)2 Bid (com.xrtb.pojo.Bid)2