Example #1
0
  public void mapdata(Message msg) {
    long now = System.currentTimeMillis();
    int pktid = msg.int32();
    int off = msg.uint16();
    int len = msg.uint16();
    Defrag fragbuf;
    synchronized (fragbufs) {
      if ((fragbuf = fragbufs.get(pktid)) == null) {
        fragbuf = new Defrag(len);
        fragbufs.put(pktid, fragbuf);
      }
      fragbuf.add(msg.blob, 8, msg.blob.length - 8, off);
      fragbuf.last = now;
      if (fragbuf.done()) {
        mapdata2(fragbuf.msg());
        fragbufs.remove(pktid);
      }

      /* Clean up old buffers */
      for (Iterator<Map.Entry<Integer, Defrag>> i = fragbufs.entrySet().iterator(); i.hasNext(); ) {
        Map.Entry<Integer, Defrag> e = i.next();
        Defrag old = e.getValue();
        if (now - old.last > 10000) i.remove();
      }
    }
  }
Example #2
0
  /**
   * Generates views based on annotations found in a repository class. If the repository class
   * extends org.ektorp.support.CouchDbRepositorySupport its handled type will also examined for
   * annotations eligible for view generation.
   *
   * @param repository
   * @return a Map with generated views.
   */
  public Map<String, DesignDocument.View> generateViews(final Object repository) {
    final Map<String, DesignDocument.View> views = new HashMap<String, DesignDocument.View>();
    final Class<?> repositoryClass = repository.getClass();

    final Class<?> handledType =
        repository instanceof CouchDbRepositorySupport<?>
            ? ((CouchDbRepositorySupport<?>) repository).getHandledType()
            : null;

    createDeclaredViews(views, repositoryClass);

    eachMethod(
        repositoryClass,
        new Predicate<Method>() {
          public boolean apply(Method input) {
            if (hasAnnotation(input, GenerateView.class)) {
              generateView(views, input, handledType);
            }
            return false;
          }
        });

    if (handledType != null) {
      views.putAll(generateViewsFromPersistentType(handledType));
    }
    return views;
  }
Example #3
0
  private void generateView(
      Map<String, DesignDocument.View> views, Method me, Class<?> handledType) {
    String name = me.getName();
    if (!name.startsWith("findBy") && !name.equals("getAll")) {
      throw new ViewGenerationException(
          String.format(
              "The method: %s in %s annotated with GenerateView does not conform to the naming convention of 'findByXxxx'",
              name, me.getDeclaringClass()));
    }

    Class<?> type = resolveReturnType(me);
    if (type == null) {
      if (handledType != null) {
        type = handledType;
      } else {
        throw new ViewGenerationException(
            "Could not resolve return type for method: %s in %s",
            me.getName(), me.getDeclaringClass());
      }
    }

    String typeDiscriminator = resolveTypeDiscriminator(type);

    if (name.equals("getAll")) {
      if (typeDiscriminator.length() < 1) {
        throw new ViewGenerationException(
            String.format(
                "Cannot generate 'all' view for %s. No type discriminator could be resolved. Try annotate unique field(s) with @TypeDiscriminator",
                type.getDeclaringClass()));
      }
      views.put("all", generateAllView(typeDiscriminator));
      return;
    }

    String finderName = name.substring(6);
    String fieldName = resolveFieldName(me, finderName);
    Method getter = findMethod(type, "get" + fieldName);
    if (getter == null) {
      // try pluralis
      fieldName += "s";
      getter = findMethod(type, "get" + fieldName);
    }
    if (getter == null) {
      throw new ViewGenerationException(
          "Could not generate view for method %s. No get method found for property %s in %s",
          name, name.substring(6), type);
    }

    fieldName = firstCharToLowerCase(fieldName);

    DesignDocument.View view;
    if (isIterable(getter.getReturnType())) {
      view = generateFindByIterableView(fieldName, typeDiscriminator);
    } else {
      view = generateFindByView(fieldName, typeDiscriminator);
    }

    views.put("by_" + firstCharToLowerCase(finderName), view);
  }
Example #4
0
 public void trimall() {
   synchronized (grids) {
     synchronized (req) {
       grids.clear();
       req.clear();
     }
   }
 }
Example #5
0
 private void addView(
     Map<String, DesignDocument.View> views, View input, Class<?> repositoryClass) {
   if (input.file().length() > 0) {
     views.put(input.name(), loadViewFromFile(views, input, repositoryClass));
   } else {
     views.put(input.name(), DesignDocument.View.of(input));
   }
 }
Example #6
0
 public synchronized List<CardTerminal> list(State state) throws CardException {
   // System.out.println("list");
   if (state == null) {
     throw new NullPointerException();
   }
   try {
     String[] readerNames = SCardListReaders(contextId);
     List<CardTerminal> list = new ArrayList<CardTerminal>(readerNames.length);
     if (stateMap == null) {
       // If waitForChange() has never been called, treat event
       // queries as status queries.
       if (state == CARD_INSERTION) {
         state = CARD_PRESENT;
       } else if (state == CARD_REMOVAL) {
         state = CARD_ABSENT;
       }
     }
     for (String readerName : readerNames) {
       CardTerminal terminal = implGetTerminal(readerName);
       ReaderState readerState;
       switch (state) {
         case ALL:
           list.add(terminal);
           break;
         case CARD_PRESENT:
           if (terminal.isCardPresent()) {
             list.add(terminal);
           }
           break;
         case CARD_ABSENT:
           if (terminal.isCardPresent() == false) {
             list.add(terminal);
           }
           break;
         case CARD_INSERTION:
           readerState = stateMap.get(readerName);
           if ((readerState != null) && readerState.isInsertion()) {
             list.add(terminal);
           }
           break;
         case CARD_REMOVAL:
           readerState = stateMap.get(readerName);
           if ((readerState != null) && readerState.isRemoval()) {
             list.add(terminal);
           }
           break;
         default:
           throw new CardException("Unknown state: " + state);
       }
     }
     return Collections.unmodifiableList(list);
   } catch (PCSCException e) {
     throw new CardException("list() failed", e);
   }
 }
  public Map defaultArguments() {
    Map defaults = new LinkedHashMap();
    Collection values = defaultArguments.values();

    Iterator iter = values.iterator();
    while (iter.hasNext()) {
      ArgumentImpl argument = (ArgumentImpl) iter.next();
      defaults.put(argument.name(), argument.clone());
    }
    return defaults;
  }
Example #8
0
  public synchronized boolean waitForChange(long timeout) throws CardException {
    // System.out.println("enter WaitforChange");
    // Thread.dumpStack();

    if (timeout < 0) {
      throw new IllegalArgumentException("Timeout must not be negative: " + timeout);
    }
    if (stateMap == null) {
      // We need to initialize the state database.
      // Do that with a recursive call, which will return immediately
      // because we pass SCARD_STATE_UNAWARE.
      // After that, proceed with the real call.
      stateMap = new HashMap<String, ReaderState>();
      waitForChange(0);
    }
    if (timeout == 0) {
      timeout = TIMEOUT_INFINITE;
    }
    try {
      String[] readerNames = SCardListReaders(contextId);
      int n = readerNames.length;
      if (n == 0) {
        throw new IllegalStateException("No terminals available");
      }
      int[] status = new int[n];
      ReaderState[] readerStates = new ReaderState[n];
      for (int i = 0; i < readerNames.length; i++) {
        String name = readerNames[i];
        ReaderState state = stateMap.get(name);
        if (state == null) {
          state = new ReaderState();
        }
        readerStates[i] = state;
        status[i] = state.get();
      }
      status = SCardGetStatusChange(contextId, timeout, status, readerNames);
      stateMap.clear(); // remove any readers that are no longer available
      for (int i = 0; i < n; i++) {
        ReaderState state = readerStates[i];
        state.update(status[i]);
        stateMap.put(readerNames[i], state);
      }
      // System.out.println("exit WaitforChange");
      return true;
    } catch (PCSCException e) {
      if (e.code == SCARD_E_TIMEOUT) {
        // System.out.println("exit WaitforChange");
        return false;
      } else {
        throw new CardException("waitForChange() failed", e);
      }
    }
  }
Example #9
0
 public void mapdata2(Message msg) {
   Coord c = msg.coord();
   synchronized (grids) {
     synchronized (req) {
       if (req.containsKey(c)) {
         Grid g = grids.get(c);
         if (g == null) grids.put(c, g = new Grid(c));
         g.fill(msg);
         req.remove(c);
         olseq++;
       }
     }
   }
 }
Example #10
0
 public void trim(Coord ul, Coord lr) {
   synchronized (grids) {
     synchronized (req) {
       for (Iterator<Map.Entry<Coord, Grid>> i = grids.entrySet().iterator(); i.hasNext(); ) {
         Map.Entry<Coord, Grid> e = i.next();
         Coord gc = e.getKey();
         Grid g = e.getValue();
         if ((gc.x < ul.x) || (gc.y < ul.y) || (gc.x > lr.x) || (gc.y > lr.y)) i.remove();
       }
       for (Iterator<Coord> i = req.keySet().iterator(); i.hasNext(); ) {
         Coord gc = i.next();
         if ((gc.x < ul.x) || (gc.y < ul.y) || (gc.x > lr.x) || (gc.y > lr.y)) i.remove();
       }
     }
   }
 }
Example #11
0
  /**
   * Notifies this <tt>ResponseCollector</tt> that a transaction described by the specified
   * <tt>BaseStunMessageEvent</tt> has failed. The possible reasons for the failure include
   * timeouts, unreachable destination, etc.
   *
   * @param event the <tt>BaseStunMessageEvent</tt> which describes the failed transaction and the
   *     runtime type of which specifies the failure reason
   * @see AbstractResponseCollector#processFailure(BaseStunMessageEvent)
   */
  @Override
  protected void processFailure(BaseStunMessageEvent event) {
    TransactionID transactionID = event.getTransactionID();

    logger.finest("A transaction expired: tranid=" + transactionID);
    logger.finest("localAddr=" + hostCandidate);

    /*
     * Clean up for the purposes of the workaround which determines the STUN
     * Request to which a STUN Response responds.
     */
    Request request;

    synchronized (requests) {
      request = requests.remove(transactionID);
    }
    if (request == null) {
      Message message = event.getMessage();

      if (message instanceof Request) request = (Request) message;
    }

    boolean completedResolvingCandidate = true;
    try {
      if (processErrorOrFailure(null, request, transactionID)) completedResolvingCandidate = false;
    } finally {
      if (completedResolvingCandidate) completedResolvingCandidate(request, null);
    }
  }
  /**
   * Closes given {@link #transportManagers} of this <tt>Conference</tt> and removes corresponding
   * channel bundle.
   */
  void closeTransportManager(TransportManager transportManager) {
    synchronized (transportManagers) {
      for (Iterator<IceUdpTransportManager> i = transportManagers.values().iterator();
          i.hasNext(); ) {
        if (i.next() == transportManager) {
          i.remove();
          // Presumably, we have a single association for
          // transportManager.
          break;
        }
      }

      // Close manager
      try {
        transportManager.close();
      } catch (Throwable t) {
        logger.warn(
            "Failed to close an IceUdpTransportManager of" + " conference " + getID() + "!", t);
        // The whole point of explicitly closing the
        // transportManagers of this Conference is to prevent memory
        // leaks. Hence, it does not make sense to possibly leave
        // TransportManagers open because a TransportManager has
        // failed to close.
        if (t instanceof InterruptedException) Thread.currentThread().interrupt();
        else if (t instanceof ThreadDeath) throw (ThreadDeath) t;
      }
    }
  }
Example #13
0
 public void ctick() {
   long now = System.currentTimeMillis();
   int dt = (int) (now - lastctick);
   synchronized (grids) {
     for (Grid g : grids.values()) {
       g.tick(dt);
     }
   }
   lastctick = now;
 }
 void addSelectedArgument(
     String name,
     String label,
     String description,
     String defaultValue,
     boolean mustSpecify,
     List list) {
   defaultArguments.put(
       name, new SelectedArgumentImpl(name, label, description, defaultValue, mustSpecify, list));
 }
Example #15
0
  /**
   * Sends a specific <tt>Request</tt> to the STUN server associated with this
   * <tt>StunCandidateHarvest</tt>.
   *
   * @param request the <tt>Request</tt> to send to the STUN server associated with this
   *     <tt>StunCandidateHarvest</tt>
   * @param firstRequest <tt>true</tt> if the specified <tt>request</tt> should be sent as the first
   *     request in the terms of STUN; otherwise, <tt>false</tt>
   * @return the <tt>TransactionID</tt> of the STUN client transaction through which the specified
   *     <tt>Request</tt> has been sent to the STUN server associated with this
   *     <tt>StunCandidateHarvest</tt>
   * @param transactionID the <tt>TransactionID</tt> of <tt>request</tt> because <tt>request</tt>
   *     only has it as a <tt>byte</tt> array and <tt>TransactionID</tt> is required for the
   *     <tt>applicationData</tt> property value
   * @throws StunException if anything goes wrong while sending the specified <tt>Request</tt> to
   *     the STUN server associated with this <tt>StunCandidateHarvest</tt>
   */
  protected TransactionID sendRequest(
      Request request, boolean firstRequest, TransactionID transactionID) throws StunException {
    if (!firstRequest && (longTermCredentialSession != null))
      longTermCredentialSession.addAttributes(request);

    StunStack stunStack = harvester.getStunStack();
    TransportAddress stunServer = harvester.stunServer;
    TransportAddress hostCandidateTransportAddress = hostCandidate.getTransportAddress();

    if (transactionID == null) {
      byte[] transactionIDAsBytes = request.getTransactionID();

      transactionID =
          (transactionIDAsBytes == null)
              ? TransactionID.createNewTransactionID()
              : TransactionID.createTransactionID(harvester.getStunStack(), transactionIDAsBytes);
    }
    synchronized (requests) {
      try {
        transactionID =
            stunStack.sendRequest(
                request, stunServer, hostCandidateTransportAddress, this, transactionID);
      } catch (IllegalArgumentException iaex) {
        if (logger.isLoggable(Level.INFO)) {
          logger.log(
              Level.INFO,
              "Failed to send "
                  + request
                  + " through "
                  + hostCandidateTransportAddress
                  + " to "
                  + stunServer,
              iaex);
        }
        throw new StunException(StunException.ILLEGAL_ARGUMENT, iaex.getMessage(), iaex);
      } catch (IOException ioex) {
        if (logger.isLoggable(Level.INFO)) {
          logger.log(
              Level.INFO,
              "Failed to send "
                  + request
                  + " through "
                  + hostCandidateTransportAddress
                  + " to "
                  + stunServer,
              ioex);
        }
        throw new StunException(StunException.NETWORK_ERROR, ioex.getMessage(), ioex);
      }

      requests.put(transactionID, request);
    }
    return transactionID;
  }
  /**
   * Returns, the <tt>TransportManager</tt> instance for the channel-bundle with ID
   * <tt>channelBundleId</tt>. If no instance exists and <tt>create</tt> is <tt>true</tt>, one will
   * be created.
   *
   * @param channelBundleId the ID of the channel-bundle for which to return the
   *     <tt>TransportManager</tt>.
   * @param create whether to create a new instance, if one doesn't exist.
   * @return the <tt>TransportManager</tt> instance for the channel-bundle with ID
   *     <tt>channelBundleId</tt>.
   */
  IceUdpTransportManager getTransportManager(String channelBundleId, boolean create) {
    IceUdpTransportManager transportManager;

    synchronized (transportManagers) {
      transportManager = transportManagers.get(channelBundleId);
      if (transportManager == null && create && !isExpired()) {
        try {
          // FIXME: the initiator is hard-coded
          // We assume rtcp-mux when bundle is used, so we make only
          // one component.
          transportManager = new IceUdpTransportManager(this, true, 1);
        } catch (IOException ioe) {
          throw new UndeclaredThrowableException(ioe);
        }
        transportManagers.put(channelBundleId, transportManager);
      }
    }

    return transportManager;
  }
  /** Closes the {@link #transportManagers} of this <tt>Conference</tt>. */
  private void closeTransportManagers() {
    synchronized (transportManagers) {
      for (Iterator<IceUdpTransportManager> i = transportManagers.values().iterator();
          i.hasNext(); ) {
        IceUdpTransportManager transportManager = i.next();

        i.remove();
        closeTransportManager(transportManager);
      }
    }
  }
  /**
   * Adds the channel-bundles of this <tt>Conference</tt> as
   * <tt>ColibriConferenceIQ.ChannelBundle</tt> instances in <tt>iq</tt>.
   *
   * @param iq the <tt>ColibriConferenceIQ</tt> in which to describe.
   */
  void describeChannelBundles(ColibriConferenceIQ iq) {
    synchronized (transportManagers) {
      for (Map.Entry<String, IceUdpTransportManager> entry : transportManagers.entrySet()) {
        ColibriConferenceIQ.ChannelBundle responseBundleIQ =
            new ColibriConferenceIQ.ChannelBundle(entry.getKey());

        entry.getValue().describe(responseBundleIQ);
        iq.addChannelBundle(responseBundleIQ);
      }
    }
  }
 void addIntegerArgument(
     String name,
     String label,
     String description,
     String defaultValue,
     boolean mustSpecify,
     int min,
     int max) {
   defaultArguments.put(
       name,
       new IntegerArgumentImpl(name, label, description, defaultValue, mustSpecify, min, max));
 }
Example #20
0
 public Grid getgrid(Coord gc) {
   synchronized (grids) {
     if ((cached == null) || !cached.gc.equals(cached)) {
       cached = grids.get(gc);
       if (cached == null) {
         request(gc);
         throw (new LoadingMap());
       }
     }
     return (cached);
   }
 }
Example #21
0
  private void generateSetBasedDocRefView(
      Map<String, org.ektorp.support.DesignDocument.View> views,
      Member me,
      DocumentReferences referenceMetaData) {
    String fieldName = firstCharToLowerCase(me.getName());
    String orderBy = referenceMetaData.orderBy();
    String backRef = referenceMetaData.backReference();
    if (backRef.length() == 0) {
      throw new ViewGenerationException(
          String.format(
              "The DocumentReferences annotation in %s must specify a backReference",
              me.getDeclaringClass()));
    }
    String viewName = NameConventions.backReferenceViewName(fieldName);
    String typeDiscriminator = resolveTypeDiscriminatorForBackReference(me);
    if (orderBy.length() > 0) {

      views.put(
          viewName,
          generateDocRefsAsSetWithOrderByView(backRef, fieldName, orderBy, typeDiscriminator));
    } else {
      views.put(viewName, generateDocRefsAsSetView(backRef, fieldName, typeDiscriminator));
    }
  }
  ArgumentImpl argument(String name, Map arguments) throws IllegalConnectorArgumentsException {

    ArgumentImpl argument = (ArgumentImpl) arguments.get(name);
    if (argument == null) {
      throw new IllegalConnectorArgumentsException("Argument missing", name);
    }
    String value = argument.value();
    if (value == null || value.length() == 0) {
      if (argument.mustSpecify()) {
        throw new IllegalConnectorArgumentsException("Argument unspecified", name);
      }
    } else if (!argument.isValid(value)) {
      throw new IllegalConnectorArgumentsException("Argument invalid", name);
    }

    return argument;
  }
Example #23
0
 public void sendreqs() {
   long now = System.currentTimeMillis();
   synchronized (req) {
     for (Iterator<Map.Entry<Coord, Request>> i = req.entrySet().iterator(); i.hasNext(); ) {
       Map.Entry<Coord, Request> e = i.next();
       Coord c = e.getKey();
       Request r = e.getValue();
       if (now - r.lastreq > 1000) {
         r.lastreq = now;
         if (++r.reqs >= 5) {
           i.remove();
         } else {
           Message msg = new Message(Session.MSG_MAPREQ);
           msg.addcoord(c);
           sess.sendmsg(msg);
         }
       }
     }
   }
 }
 public static Palette getPalette(Bitmap bitmap) {
   return CACHE.get(bitmap);
 }
Example #25
0
  /**
   * Notifies this <tt>ResponseCollector</tt> that a STUN response described by the specified
   * <tt>StunResponseEvent</tt> has been received.
   *
   * @param event the <tt>StunResponseEvent</tt> which describes the received STUN response
   * @see ResponseCollector#processResponse(StunResponseEvent)
   */
  @Override
  public void processResponse(StunResponseEvent event) {
    TransactionID transactionID = event.getTransactionID();

    logger.finest("Received a message: tranid= " + transactionID);
    logger.finest("localCand= " + hostCandidate);

    /*
     * Clean up for the purposes of the workaround which determines the STUN
     * Request to which a STUN Response responds.
     */
    synchronized (requests) {
      requests.remove(transactionID);
    }

    // At long last, do start handling the received STUN Response.
    Response response = event.getResponse();
    Request request = event.getRequest();
    boolean completedResolvingCandidate = true;

    try {
      if (response.isSuccessResponse()) {
        // Authentication and Message-Integrity Mechanisms
        if (request.containsAttribute(Attribute.MESSAGE_INTEGRITY)) {
          MessageIntegrityAttribute messageIntegrityAttribute =
              (MessageIntegrityAttribute) response.getAttribute(Attribute.MESSAGE_INTEGRITY);

          /*
           * RFC 5389: If MESSAGE-INTEGRITY was absent, the response
           * MUST be discarded, as if it was never received.
           */
          if (messageIntegrityAttribute == null) return;

          UsernameAttribute usernameAttribute =
              (UsernameAttribute) request.getAttribute(Attribute.USERNAME);

          /*
           * For a request or indication message, the agent MUST
           * include the USERNAME and MESSAGE-INTEGRITY attributes in
           * the message.
           */
          if (usernameAttribute == null) return;
          if (!harvester
              .getStunStack()
              .validateMessageIntegrity(
                  messageIntegrityAttribute,
                  LongTermCredential.toString(usernameAttribute.getUsername()),
                  !request.containsAttribute(Attribute.REALM)
                      && !request.containsAttribute(Attribute.NONCE),
                  event.getRawMessage())) return;
        }

        processSuccess(response, request, transactionID);
      } else {
        ErrorCodeAttribute errorCodeAttr =
            (ErrorCodeAttribute) response.getAttribute(Attribute.ERROR_CODE);

        if ((errorCodeAttr != null) && (errorCodeAttr.getErrorClass() == 4)) {
          try {
            switch (errorCodeAttr.getErrorNumber()) {
              case 1: // 401 Unauthorized
                if (processUnauthorized(response, request, transactionID))
                  completedResolvingCandidate = false;
                break;
              case 38: // 438 Stale Nonce
                if (processStaleNonce(response, request, transactionID))
                  completedResolvingCandidate = false;
                break;
            }
          } catch (StunException sex) {
            completedResolvingCandidate = true;
          }
        }
        if (completedResolvingCandidate && processErrorOrFailure(response, request, transactionID))
          completedResolvingCandidate = false;
      }
    } finally {
      if (completedResolvingCandidate) completedResolvingCandidate(request, response);
    }
  }
 void addBooleanArgument(
     String name, String label, String description, boolean defaultValue, boolean mustSpecify) {
   defaultArguments.put(
       name, new BooleanArgumentImpl(name, label, description, defaultValue, mustSpecify));
 }
Example #27
0
 public void request(Coord gc) {
   synchronized (req) {
     if (!req.containsKey(gc)) req.put(gc, new Request());
   }
 }
 // # Transformation Contract
 @Override
 public final Bitmap transform(Bitmap source) {
   final Palette palette = Palette.generate(source);
   CACHE.put(source, palette);
   return source;
 }
Example #29
0
 public void invalidate(Coord cc) {
   synchronized (req) {
     if (req.get(cc) == null) req.put(cc, new Request());
   }
 }