예제 #1
0
 @Override
 protected Tracker clone() {
   Tracker ret = (Tracker) super.clone();
   ret.values = new java.util.HashSet<Integer>(this.values);
   ret.unmodifiable = java.util.Collections.unmodifiableSet(ret.values);
   return ret;
 }
예제 #2
0
파일: Torrent.java 프로젝트: rimmo77/bitlet
  public void tick() {

    peersManager.tick();
    choker.tick();

    Long waitTime = activeTracker.getInterval();
    if (incomingPeerListener.getReceivedConnection() == 0
        || peersManager.getActivePeersNumber() < 4) {
      waitTime = activeTracker.getMinInterval() != null ? activeTracker.getMinInterval() : 60;
    }

    long now = System.currentTimeMillis();
    if (now - activeTracker.getLastRequestTime() >= waitTime * 1000) {

      if (!stopped) {
        try {
          Object peers = trackerRequest(null).get(ByteBuffer.wrap("peers".getBytes()));
          if (peers != null) {
            addPeers(peers);
          }
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
  }
  GoogleAnalyticsIntegration(
      Context context, GoogleAnalytics googleAnalytics, ValueMap settings, Logger logger) {
    this.googleAnalytics = googleAnalytics;
    this.logger = logger;

    String mobileTrackingId = settings.getString("mobileTrackingId");
    tracker = googleAnalytics.newTracker(mobileTrackingId);
    logger.verbose("GoogleAnalytics.getInstance(context).newTracker(%s);", mobileTrackingId);

    boolean anonymizeIp = settings.getBoolean("anonymizeIp", false);
    tracker.setAnonymizeIp(anonymizeIp);
    logger.verbose("tracker.setAnonymizeIp(%s);", anonymizeIp);

    boolean reportUncaughtExceptions = settings.getBoolean("reportUncaughtExceptions", false);
    if (reportUncaughtExceptions) {
      tracker.setUncaughtExceptionReporter(context);
      logger.verbose("Thread.setDefaultUncaughtExceptionHandler(new ExceptionReporter(...));");
    }

    sendUserId = settings.getBoolean("sendUserId", false);
    customDimensions = settings.getValueMap("dimensions");
    if (isNullOrEmpty(customDimensions)) customDimensions = EMPTY;
    customMetrics = settings.getValueMap("metrics");
    if (isNullOrEmpty(customMetrics)) customMetrics = EMPTY;
  }
  @Override
  public void identify(IdentifyPayload identify) {
    if (sendUserId) {
      String userId = identify.userId();
      tracker.set(USER_ID_KEY, userId);
      logger.verbose("tracker.set(%s, %s);", USER_ID_KEY, userId);
    }

    // Set traits, custom dimensions, and custom metrics on the shared tracker.
    for (Map.Entry<String, Object> entry : identify.traits().entrySet()) {
      String trait = entry.getKey();
      if (customDimensions.containsKey(trait)) {
        String dimension =
            customDimensions.getString(trait).replace(DIMENSION_PREFIX, DIMENSION_PREFIX_KEY);
        String value = String.valueOf(entry.getValue());
        tracker.set(dimension, value);
        logger.verbose("tracker.set(%s, %s);", dimension, value);
      }
      if (customMetrics.containsKey(trait)) {
        String metric = customMetrics.getString(trait).replace(METRIC_PREFIX, METRIC_PREFIX_KEY);
        String value = String.valueOf(entry.getValue());
        tracker.set(metric, value);
        logger.verbose("tracker.set(%s, %s);", metric, value);
      }
    }
  }
예제 #5
0
 private void turnInDirection(Tracker tracker, int quater, int numberOfTurns) {
   for (int k = 0; k < numberOfTurns; k++) {
     tracker.trackLine();
     tracker.trackLine();
     tracker.stop();
     tracker.turn(quater);
   }
 }
예제 #6
0
 /** construct a Transaction for use in an offline operation */
 public static LifecycleTransaction offline(
     OperationType operationType, Iterable<SSTableReader> readers) {
   // if offline, for simplicity we just use a dummy tracker
   Tracker dummy = new Tracker(null, false);
   dummy.addInitialSSTables(readers);
   dummy.apply(updateCompacting(emptySet(), readers));
   return new LifecycleTransaction(dummy, operationType, readers);
 }
예제 #7
0
 public void gridnav(Tracker tracker) {
   Button.waitForAnyPress();
   turnInDirection(tracker, -1, 8);
   tracker.turn(-1);
   turnInDirection(tracker, 1, 8);
   turnInDirection(tracker, -2, 4);
   tracker.turn(2);
   turnInDirection(tracker, 2, 4);
 }
예제 #8
0
 @SuppressWarnings("unchecked")
 @Override
 public Tracker clone() {
   Tracker ret = (Tracker) super.clone();
   ret.thisTurn = (java.util.HashMap<Integer, Integer>) this.thisTurn.clone();
   ret.previousTurn = (java.util.HashMap<Integer, Integer>) this.previousTurn.clone();
   ret.unmodifiable = java.util.Collections.unmodifiableMap(ret.previousTurn);
   return ret;
 }
예제 #9
0
    @Override
    public Set evaluate(GameState state, Identified thisObject) {
      Tracker tracker = state.getTracker(Tracker.class);

      // if "a player" cast two or more spells this turn -- a single value
      // in the map must be >= 2
      for (int spellCount : tracker.getValue(state).values())
        if (spellCount >= 2) return NonEmpty.set;
      return Empty.set;
    }
예제 #10
0
 private Throwable unmarkCompacting(Set<SSTableReader> unmark, Throwable accumulate) {
   accumulate = tracker.apply(updateCompacting(unmark, emptySet()), accumulate);
   // when the CFS is invalidated, it will call unreferenceSSTables().  However,
   // unreferenceSSTables only deals
   // with sstables that aren't currently being compacted.  If there are ongoing compactions that
   // finish or are
   // interrupted after the CFS is invalidated, those sstables need to be unreferenced as well, so
   // we do that here.
   accumulate = tracker.dropSSTablesIfInvalid(accumulate);
   return accumulate;
 }
예제 #11
0
 @Test
 public void shouldUpdateDroneLocation() {
   Tracker tracker = new SimpleTrackerFactory().create("drone1", "my tracker");
   trackerData.register((Observer) tracker);
   Assert.assertEquals(1, trackerData.getTrackers().size());
   MapPoint oldPosition = tracker.getCurrentPosition();
   tracker.calculate();
   MapPoint newPosition = tracker.getCurrentPosition();
   System.out.println("........." + oldPosition.getLongitude());
   System.out.println("........." + newPosition.getLatitude());
   Assert.assertNotSame(newPosition, oldPosition);
   Assert.assertSame(oldPosition, tracker.getPositions().get(0));
 }
  @Override
  public void track(TrackPayload track) {
    Properties properties = track.properties();
    String event = track.event();
    String category = properties.category();

    sendProductEvent(event, category, properties);

    if (COMPLETED_ORDER_PATTERN.matcher(event).matches()) {
      List<Product> products = properties.products();
      if (!isNullOrEmpty(products)) {
        for (int i = 0; i < products.size(); i++) {
          Product product = products.get(i);
          ItemHitBuilder hitBuilder = new ItemHitBuilder();
          hitBuilder
              .setTransactionId(properties.orderId())
              .setName(product.name())
              .setSku(product.sku())
              .setPrice(product.price())
              .setQuantity(product.getLong(QUANTITY_KEY, 0))
              .build();
          attachCustomDimensionsAndMetrics(hitBuilder, properties);
          Map<String, String> hit = hitBuilder.build();
          tracker.send(hit);
          logger.verbose("tracker.send(%s);", hit);
        }
      }
      TransactionBuilder transactionBuilder = new TransactionBuilder();
      transactionBuilder
          .setTransactionId(properties.orderId())
          .setCurrencyCode(properties.currency())
          .setRevenue(properties.total())
          .setTax(properties.tax())
          .setShipping(properties.shipping());
      Map<String, String> transaction = transactionBuilder.build();
      tracker.send(transaction);
      logger.verbose("tracker.send(%s);", transaction);
    }

    String label = properties.getString(LABEL_KEY);
    EventHitBuilder eventHitBuilder = new EventHitBuilder();
    eventHitBuilder
        .setAction(event)
        .setCategory(isNullOrEmpty(category) ? DEFAULT_CATEGORY : category)
        .setLabel(label)
        .setValue((int) properties.value());
    attachCustomDimensionsAndMetrics(eventHitBuilder, properties);
    Map<String, String> eventHit = eventHitBuilder.build();
    tracker.send(eventHit);
    logger.verbose("tracker.send(%s);", eventHit);
  }
예제 #13
0
  private Throwable checkpoint(Throwable accumulate) {
    if (logger.isDebugEnabled())
      logger.debug("Checkpointing update:{}, obsolete:{}", staged.update, staged.obsolete);

    if (staged.isEmpty()) return accumulate;

    Set<SSTableReader> toUpdate = toUpdate();
    Set<SSTableReader> fresh = copyOf(fresh());

    // check the current versions of the readers we're replacing haven't somehow been replaced by
    // someone else
    checkNotReplaced(filterIn(toUpdate, staged.update));

    // ensure any new readers are in the compacting set, since we aren't done with them yet
    // and don't want anyone else messing with them
    // apply atomically along with updating the live set of readers
    tracker.apply(
        compose(updateCompacting(emptySet(), fresh), updateLiveSet(toUpdate, staged.update)));

    // log the staged changes and our newly marked readers
    marked.addAll(fresh);
    logged.log(staged);

    // setup our tracker, and mark our prior versions replaced, also releasing our references to
    // them
    // we do not replace/release obsoleted readers, since we may need to restore them on rollback
    accumulate = setReplaced(filterOut(toUpdate, staged.obsolete), accumulate);
    accumulate = release(selfRefs(filterOut(toUpdate, staged.obsolete)), accumulate);

    staged.clear();
    return accumulate;
  }
예제 #14
0
 public EmailAsyncTask(Tracker tracker) {
   mTracker = tracker;
   if (mTracker != null) {
     mTracker.add(this);
   }
   mInnerTask = new InnerTask<Params, Progress, Result>(this);
 }
예제 #15
0
 @Override
 public int hashCode() {
   final int prime = 31;
   int result = 1;
   result = prime * result + ((assignee == null) ? 0 : assignee.hashCode());
   result = prime * result + ((author == null) ? 0 : author.hashCode());
   result = prime * result + ((createdOn == null) ? 0 : createdOn.hashCode());
   result = prime * result + ((customFields == null) ? 0 : customFields.hashCode());
   result = prime * result + ((description == null) ? 0 : description.hashCode());
   result = prime * result + ((doneRatio == null) ? 0 : doneRatio.hashCode());
   result = prime * result + ((dueDate == null) ? 0 : dueDate.hashCode());
   result = prime * result + ((estimatedHours == null) ? 0 : estimatedHours.hashCode());
   result = prime * result + ((id == null) ? 0 : id.hashCode());
   result = prime * result + ((journals == null) ? 0 : journals.hashCode());
   result = prime * result + ((notes == null) ? 0 : notes.hashCode());
   result = prime * result + ((parentId == null) ? 0 : parentId.hashCode());
   result = prime * result + ((priorityId == null) ? 0 : priorityId.hashCode());
   result = prime * result + ((priorityText == null) ? 0 : priorityText.hashCode());
   result = prime * result + ((project == null) ? 0 : project.hashCode());
   result = prime * result + ((relations == null) ? 0 : relations.hashCode());
   result = prime * result + ((spentHours == null) ? 0 : spentHours.hashCode());
   result = prime * result + ((startDate == null) ? 0 : startDate.hashCode());
   result = prime * result + ((statusId == null) ? 0 : statusId.hashCode());
   result = prime * result + ((statusName == null) ? 0 : statusName.hashCode());
   result = prime * result + ((subject == null) ? 0 : subject.hashCode());
   result = prime * result + ((tracker == null) ? 0 : tracker.hashCode());
   result = prime * result + ((updatedOn == null) ? 0 : updatedOn.hashCode());
   return result;
 }
  public void update() {
    for (int i = 0; i < downloadingFiles.size(); i++) {
      DownloadingFile dFile = downloadingFiles.get(i);
      if (dFile.elapsedTime >= dFile.delay) {
        SimulationFile sf = downloadingFiles.get(i).sFile;

        // Simulate Download
        if (sf.LoadAmount < sf.size) {
          sf.LoadAmount += sf.polularity;
        } else // Finished downloading
        {
          downloadingFiles.remove(i);
          sFile.add(sf);

          Random rng = new Random();

          if (rng.nextFloat() <= publishProb) // Check if file is to be published
          {
            tracker.publishFile(this, sf);
          }
        }
      } else {
        dFile.elapsedTime++;
      }
    }
  }
  @Override
  public void screen(ScreenPayload screen) {
    Properties properties = screen.properties();
    String screenName = screen.event();

    sendProductEvent(screenName, screen.category(), properties);

    tracker.setScreenName(screenName);
    logger.verbose("tracker.setScreenName(%s);", screenName);

    ScreenViewHitBuilder hitBuilder = new ScreenViewHitBuilder();
    attachCustomDimensionsAndMetrics(hitBuilder, properties);
    Map<String, String> hit = hitBuilder.build();
    tracker.send(hit);
    logger.verbose("tracker.send(%s);", hit);
  }
예제 #18
0
  /** point of no return: commit all changes, but leave all readers marked as compacting */
  public Throwable doCommit(Throwable accumulate) {
    assert staged.isEmpty() : "must be no actions introduced between prepareToCommit and a commit";

    logger.debug("Committing update:{}, obsolete:{}", staged.update, staged.obsolete);

    // this is now the point of no return; we cannot safely rollback, so we ignore exceptions until
    // we're done
    // we restore state by obsoleting our obsolete files, releasing our references to them, and
    // updating our size
    // and notification status for the obsolete and new files
    accumulate = markObsolete(tracker, logged.obsolete, accumulate);
    accumulate = tracker.updateSizeTracking(logged.obsolete, logged.update, accumulate);
    accumulate = release(selfRefs(logged.obsolete), accumulate);
    accumulate = tracker.notifySSTablesChanged(originals, logged.update, operationType, accumulate);
    return accumulate;
  }
예제 #19
0
 /** Refreshes the autoload data. */
 @Override
 protected void refreshAutoloadData() {
   final Map<String, Map<String, ArrayList<String[]>>> data =
       new TreeMap<String, Map<String, ArrayList<String[]>>>();
   for (String path : getSearchPaths()) {
     Map<String, ArrayList<String[]>> functionMap = Tracker.findDataFunctions(path);
     data.put(path, functionMap);
   }
   setAutoloadData(data);
 }
예제 #20
0
  @Override
  public void onCreate() {
    super.onCreate();

    Tracker.init(this);
    initTraceDroid();

    bus = new Bus();
    settings = new Settings(this);
    passStore = new AndroidFileSystemPassStore(this);
  }
  void onNewFileDetected(int fileID) {
    Random rng = new Random();

    float dieRoll = rng.nextFloat();
    if (dieRoll < downloadProb) {
      SimulationFile temp = tracker.queryAndDwldFile(this, fileID);
      DownloadingFile dFile =
          new DownloadingFile(new SimulationFile(temp.UID, temp.size, temp.polularity));
      downloadingFiles.add(dFile);
    }
  }
예제 #22
0
 private final EmailAsyncTask<Params, Progress, Result> executeInternal(
     Executor executor, boolean cancelPrevious, Params... params) {
   if (cancelPrevious) {
     if (mTracker == null) {
       throw new IllegalStateException();
     } else {
       mTracker.cancelOthers(this);
     }
   }
   mInnerTask.executeOnExecutor(executor, params);
   return this;
 }
예제 #23
0
 /**
  * Gets the collection of search paths.
  *
  * @return the search paths
  */
 @Override
 public Collection<String> getSearchPaths() {
   Collection<String> paths = super.getSearchPaths();
   if (paths.isEmpty() && !initialized) {
     initialized = true;
     for (String next : Tracker.getInitialSearchPaths()) {
       paths.add(next);
       addSearchPath(next);
     }
   }
   return paths;
 }
예제 #24
0
 @Test
 public void testPiwikExceptionHandler() throws Exception {
   Tracker tracker = createTracker();
   assertFalse(Thread.getDefaultUncaughtExceptionHandler() instanceof PiwikExceptionHandler);
   QuickTrack.trackUncaughtExceptions(tracker);
   assertTrue(Thread.getDefaultUncaughtExceptionHandler() instanceof PiwikExceptionHandler);
   try {
     int i = 1 / 0;
     assertNotEquals(i, 0);
   } catch (Exception e) {
     (Thread.getDefaultUncaughtExceptionHandler()).uncaughtException(Thread.currentThread(), e);
   }
   QueryHashMap<String, String> queryParams = parseEventUrl(tracker.getLastEvent());
   validateDefaultQuery(queryParams);
   assertEquals(queryParams.get(QueryParams.EVENT_CATEGORY), "Exception");
   assertTrue(
       queryParams
           .get(QueryParams.EVENT_ACTION)
           .startsWith("org.piwik.sdk.QuickTrackTest/testPiwikExceptionHandler:"));
   assertEquals(queryParams.get(QueryParams.EVENT_NAME), "/ by zero");
   assertEquals(queryParams.get(QueryParams.EVENT_VALUE), "1");
 }
예제 #25
0
파일: Torrent.java 프로젝트: rimmo77/bitlet
  public Map trackerRequest(String event) {

    for (List<Tracker> trackers : trackerTiers) {
      for (Tracker t : trackers) {
        try {
          Map responseDictionary = t.trackerRequest(this, event);
          if (responseDictionary != null) {
            activeTracker = t;
            trackers.remove(t);
            trackers.add(0, t);
            return responseDictionary;
          }
        } catch (Exception e) {
          int ciccio = 2;
          if (Torrent.verbose) {
            addEvent(new Event(this, e.toString(), Level.INFO));
          }
        }
      }
    }

    return null;
  }
예제 #26
0
 /**
  * Sets the selection state of a file. Note that PART_SELECTED is not an option.
  *
  * @param filePath the path to the file
  * @param select true/false to select/deselect the file and all its functions
  */
 @Override
 protected void setFileSelected(String filePath, boolean select) {
   Tracker.autoloadMap.remove(filePath);
   if (!select) {
     String[] function = new String[] {"*"}; // $NON-NLS-1$
     Tracker.autoloadMap.put(filePath, function);
   }
   Tracker.autoloadDataFunctions();
   refreshAutoloadData();
   // reload autoloaded functions into existing panels
   for (String name : getPanelNames()) {
     DataFunctionPanel panel = (DataFunctionPanel) getPanel(name);
     addPanel(name, panel);
   }
 }
예제 #27
0
 public void uncaughtException(Thread thread, Throwable throwable) {
   String s = "UncaughtException";
   if (xZ != null) {
     if (thread != null) {
       s = thread.getName();
     } else {
       s = null;
     }
     s = xZ.getDescription(s, throwable);
   }
   z.V((new StringBuilder()).append("Tracking Exception: ").append(s).toString());
   xY.send((new HitBuilders.ExceptionBuilder()).setDescription(s).setFatal(true).build());
   GoogleAnalytics.getInstance(mContext).dispatchLocalHits();
   if (xX != null) {
     z.V("Passing exception to original handler.");
     xX.uncaughtException(thread, throwable);
   }
 }
예제 #28
0
 @Override
 public void setVisible(boolean vis) {
   super.setVisible(vis);
   if (!vis) {
     // save non-default search paths in Tracker.preferredAutoloadSearchPaths
     Collection<String> searchPaths = getSearchPaths();
     Collection<String> defaultPaths = Tracker.getDefaultAutoloadSearchPaths();
     boolean isDefault = searchPaths.size() == defaultPaths.size();
     for (String next : searchPaths) {
       isDefault = isDefault && defaultPaths.contains(next);
     }
     if (isDefault) {
       Tracker.preferredAutoloadSearchPaths = null;
     } else {
       Tracker.preferredAutoloadSearchPaths =
           searchPaths.toArray(new String[searchPaths.size()]);
     }
   }
 }
  /** Send a product event. */
  void sendProductEvent(String event, String category, Properties properties) {
    if (!PRODUCT_EVENT_NAME_PATTERN.matcher(event).matches()) {
      return;
    }

    ItemHitBuilder itemHitBuilder = new ItemHitBuilder();
    itemHitBuilder
        .setTransactionId(properties.orderId())
        .setCurrencyCode(properties.currency())
        .setName(properties.name())
        .setSku(properties.sku())
        .setCategory(isNullOrEmpty(category) ? DEFAULT_CATEGORY : category)
        .setPrice(properties.price())
        .setQuantity(properties.getLong(QUANTITY_KEY, 0))
        .build();
    attachCustomDimensionsAndMetrics(itemHitBuilder, properties);
    Map<String, String> itemHit = itemHitBuilder.build();
    tracker.send(itemHit);
    logger.verbose("tracker.send(%s);", itemHit);
  }
예제 #30
0
    /**
     * Sets the selection state of a function.
     *
     * @param filePath the path to the file defining the function
     * @param function the function {name, expression, optional descriptor}
     * @param select true to select the function
     */
    @Override
    protected void setFunctionSelected(String filePath, String[] function, boolean select) {

      String[] oldExclusions = Tracker.autoloadMap.get(filePath);
      String[] newExclusions = null;
      if (!select) {
        // create or add entry to newExclusions
        if (oldExclusions == null) {
          newExclusions = new String[] {function[0]};
        } else {
          int n = oldExclusions.length;
          newExclusions = new String[n + 1];
          System.arraycopy(oldExclusions, 0, newExclusions, 0, n);
          newExclusions[n] = function[0];
        }
      } else if (oldExclusions != null) {
        // remove entry
        int n = oldExclusions.length;
        if (n > 1) {
          ArrayList<String> exclusions = new ArrayList<String>();
          for (String f : oldExclusions) {
            if (f.equals(function[0])) continue;
            exclusions.add(f);
          }
          newExclusions = exclusions.toArray(new String[exclusions.size()]);
        }
      }

      Tracker.autoloadMap.remove(filePath);
      if (newExclusions != null) {
        Tracker.autoloadMap.put(filePath, newExclusions);
      }

      Tracker.autoloadDataFunctions();
      refreshAutoloadData();
      // reload autoloaded functions into existing panels
      for (String name : getPanelNames()) {
        DataFunctionPanel panel = (DataFunctionPanel) getPanel(name);
        addPanel(name, panel);
      }
    }