private static boolean matchSpecifiedExitStatus(
      String currentStepExitStatus, String exitStatusPattern) {

    if (logger.isLoggable(Level.FINER)) {
      logger.finer(
          "matchSpecifiedExitStatus, matching current exitStatus  "
              + currentStepExitStatus
              + " against pattern: "
              + exitStatusPattern);
    }

    GlobPatternMatcherImpl matcher = new GlobPatternMatcherImpl();
    boolean match = matcher.matchWithoutBackslashEscape(currentStepExitStatus, exitStatusPattern);

    if (match) {
      if (logger.isLoggable(Level.FINER)) {
        logger.finer("matchSpecifiedExitStatus, match=YES");
      }
      return true;
    } else {
      if (logger.isLoggable(Level.FINER)) {
        logger.finer("matchSpecifiedExitStatus, match=NO");
      }
      return false;
    }
  }
  public void setCardReference(RobinsonCard card, boolean copyFlags) {
    actingOn = card;
    card.setAffectedBy(this);

    LOGGER.finer(
        "***[RobinsonCard > setCardReference] <"
            + getCardName()
            + "> acting on <"
            + card.getCardName()
            + ">");

    if (copyFlags) {
      LOGGER.finer("***[RobinsonCard > setCardReference] copyFlags is set");

      COPYING_DOUBLE = false;
      COPYING_PHASE = false;

      if (actingOn.getCardAbility() == Ability.DOUBLE_ONE) {
        COPYING_DOUBLE = true;

        LOGGER.finer("***[RobinsonCard > setCardReference] It's a DOUBLE reference");
      } else if (actingOn.getCardAbility() == Ability.PHASE_MINUS_ONE) {
        COPYING_PHASE = true;

        LOGGER.finer("***[RobinsonCard > setCardReference] It's a PHASE reference");
      }
    }
  }
Exemple #3
0
  public void display() {
    int num = inactivebranches.size();
    log.fine("Tree has " + activebranches.size() + " active branches");
    log.fine("Tree has " + inactivebranches.size() + " inactive branches");
    log.fine("Backend reports: " + branches.length + " stored.");
    log.finer("Removing inactive branches");
    for (int i = 0; i < num; i++) {
      log.finest("InactiveBranch: " + inactivebranches.get(i) + " removed");
      theBackend.removeBranch((String) inactivebranches.get(i));
    }

    log.finer("Removing orphaned branches");
    int orphanremovecount = 0;
    for (int i = 0; i < branches.length; i++) {
      if (activebranches.contains(branches[i])) {
        log.finest("Activebranch: " + branches[i] + " retained");
      } else {
        log.finest("OrphanBranch: " + branches[i] + " removed");
        orphanremovecount++;
        theBackend.removeBranch(branches[i]);
      }
    }
    log.fine("Removed " + orphanremovecount + " orphaned branches");
    theBackend.store();
    log.info("Compacted Tree Stored");
  }
  public void readBody(ActionRequestMessage requestMessage, ActionInvocation actionInvocation)
      throws UnsupportedDataException {

    log.fine("Reading body of " + requestMessage + " for: " + actionInvocation);
    if (log.isLoggable(Level.FINER)) {
      log.finer(
          "===================================== SOAP BODY BEGIN ============================================");
      log.finer(requestMessage.getBodyString());
      log.finer(
          "-===================================== SOAP BODY END ============================================");
    }

    String body = getMessageBody(requestMessage);
    try {

      DocumentBuilderFactory factory = createDocumentBuilderFactory();
      factory.setNamespaceAware(true);
      DocumentBuilder documentBuilder = factory.newDocumentBuilder();
      documentBuilder.setErrorHandler(this);

      Document d = documentBuilder.parse(new InputSource(new StringReader(body)));

      Element bodyElement = readBodyElement(d);

      readBodyRequest(d, bodyElement, requestMessage, actionInvocation);

    } catch (Exception ex) {
      throw new UnsupportedDataException("Can't transform message payload: " + ex, ex, body);
    }
  }
  public void writeBody(ActionResponseMessage responseMessage, ActionInvocation actionInvocation)
      throws UnsupportedDataException {

    log.fine("Writing body of " + responseMessage + " for: " + actionInvocation);

    try {

      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      factory.setNamespaceAware(true);
      Document d = factory.newDocumentBuilder().newDocument();
      Element body = writeBodyElement(d);

      if (actionInvocation.getFailure() != null) {
        writeBodyFailure(d, body, responseMessage, actionInvocation);
      } else {
        writeBodyResponse(d, body, responseMessage, actionInvocation);
      }

      if (log.isLoggable(Level.FINER)) {
        log.finer(
            "===================================== SOAP BODY BEGIN ============================================");
        log.finer(responseMessage.getBodyString());
        log.finer(
            "-===================================== SOAP BODY END ============================================");
      }

    } catch (Exception ex) {
      throw new UnsupportedDataException("Can't transform message payload: " + ex, ex);
    }
  }
  /**
   * If resource can be handled
   *
   * @return true if resource can be handled or false if not
   */
  public boolean canHandleResource() {
    String hintServiceType = this.getHintServiceType();
    String resourceUri = this.getResourceUri();

    if (hintServiceType == null || resourceUri == null) {
      LOG.finer("Could NOT handle resrouceuri = " + resourceUri + ", hint = " + _hintServiceType);
      return false;
    }
    if (hintServiceType.equalsIgnoreCase(ResourceLinkBuilder.ServiceType.WMS.name())
        || hintServiceType.equalsIgnoreCase(ResourceLinkBuilder.ServiceType.AIMS.name())) {
      LOG.finer("Could handle resrouceuri " + resourceUri);
      return true;
    }
    if (hintServiceType.equalsIgnoreCase(ResourceLinkBuilder.ServiceType.AGS.name())) {
      if (resourceUri.toLowerCase().contains("/rest")
          && resourceUri.toLowerCase().contains("/mapserver")) {
        this._hintServiceType = "agsrest";
        return true;
      }
      LOG.finer("Could handle resrouceuri " + _resourceUri);
    }
    if (!this.getRegexCanConsumeUrl().equals("")) {
      try {
        if (resourceUri.matches(this.getRegexCanConsumeUrl())) {
          return true;
        }
      } catch (PatternSyntaxException e) {
        LOG.log(Level.WARNING, "Regex not specified correctly " + this.getRegexCanConsumeUrl(), e);
      }
      LOG.finer("Could handle resrouceuri with configured regex " + _resourceUri);
    }
    LOG.finer("Could NOT handle resrouceuri = " + _resourceUri + ", hint = " + _hintServiceType);

    return false;
  }
 @Override
 public void valueChanged(TreeSelectionEvent e) {
   if (LOG.isLoggable(Level.FINER)) {
     LOG.finer("TreeSelectionEvent: " + e.toString());
   }
   // Stop editing the table, if editing is currently in progress
   if (groupTable.getCellEditor() != null) {
     groupTable.getCellEditor().stopCellEditing();
   }
   InitTableModel tableModel = groupTable.getActorTableModel();
   if (groupTree.getLastSelectedPathComponent() != null) {
     if (LOG.isLoggable(Level.FINER)) {
       LOG.finer("Current Selection: " + groupTree.getLastSelectedPathComponent().toString());
     }
     GroupTreeNode node = (GroupTreeNode) groupTree.getLastSelectedPathComponent();
     if (node.isGroup()) { // If current selection is a group, display the actors
       tableModel.setActorList(node.getActorList());
       groupTable.setVisible(true);
     } else { // Otherwise don't show any actors
       groupTable.setVisible(false);
       tableModel.setActorList(null);
     }
   } else {
     if (LOG.isLoggable(Level.FINER)) {
       LOG.finer("Current Selection: null");
     }
     groupTable.setVisible(false);
     tableModel.setActorList(null);
   }
 }
 public boolean checkCorsPreflight(Request request, Response response) {
   log.finer("checkCorsPreflight " + request.getRequestURI());
   if (!request.getMethod().equalsIgnoreCase("OPTIONS")) {
     log.finer("checkCorsPreflight: not options ");
     return false;
   }
   if (request.getHeader("Origin") == null) {
     log.finer("checkCorsPreflight: no origin header");
     return false;
   }
   log.finer("Preflight request returning");
   response.setStatus(HttpServletResponse.SC_OK);
   String origin = request.getHeader("Origin");
   response.setHeader("Access-Control-Allow-Origin", origin);
   response.setHeader("Access-Control-Allow-Credentials", "true");
   String requestMethods = request.getHeader("Access-Control-Request-Method");
   if (requestMethods != null) {
     if (deployment.getCorsAllowedMethods() != null) {
       requestMethods = deployment.getCorsAllowedMethods();
     }
     response.setHeader("Access-Control-Allow-Methods", requestMethods);
   }
   String allowHeaders = request.getHeader("Access-Control-Request-Headers");
   if (allowHeaders != null) {
     if (deployment.getCorsAllowedHeaders() != null) {
       allowHeaders = deployment.getCorsAllowedHeaders();
     }
     response.setHeader("Access-Control-Allow-Headers", allowHeaders);
   }
   if (deployment.getCorsMaxAge() > -1) {
     response.setHeader("Access-Control-Max-Age", Integer.toString(deployment.getCorsMaxAge()));
   }
   return true;
 }
Exemple #9
0
  public Resource[] getResources(Device device) throws ValidationException {
    if (!device.isRoot()) return null;

    Set<Resource> resources = new HashSet();
    List<ValidationError> errors = new ArrayList();

    log.fine("Discovering local resources of device graph");
    Resource[] discoveredResources = device.discoverResources(this);
    for (Resource resource : discoveredResources) {
      log.finer("Discovered: " + resource);
      if (!resources.add(resource)) {
        log.finer("Local resource already exists, queueing validation error");
        errors.add(
            new ValidationError(
                getClass(),
                "resources",
                "Local URI namespace conflict between resources of device: " + resource));
      }
    }
    if (errors.size() > 0) {
      throw new ValidationException(
          "Validation of device graph failed, call getErrors() on exception", errors);
    }
    return resources.toArray(new Resource[resources.size()]);
  }
  /**
   * Look ahead at the next measure, build and determine a suitable SongPhrase to handle it.
   *
   * @param itM an iterator over the measures collection. It must be pointing so that itM.next()
   *     returns the current measure, which will be marked as a repeatStart.
   * @param itMTP an iterator over the measure-track pairs collection. It must be pointing so that
   *     itMTP.next() returns the first track of the current measure
   * @param tracks The tracks definitions
   * @return the next SongPhrase
   */
  private static SongPhrase phraseFactory(
      Song song,
      ListIterator<GPMeasure> itM,
      ListIterator<GPMeasureTrackPair> itMTP,
      List<GPTrack> tracks)
      throws GPFormatException {
    SongPhrase sp = null;

    GPMeasure measure = itM.next(); // peek inside the measure
    // and dispatch to the right
    // factory
    itM.previous(); // rewind before calling the right factory method

    // TODO add getter and setter for GP4Measure.repeatStart
    logger.finer("Measure " + measure.getNumber() + " repeat start " + measure.repeatStart);
    logger.finer(
        "Measure " + measure.getNumber() + " repeat count " + measure.getNumberOfRepetitions());

    // if it's the start of a repeat, then make a repeated phrase
    if (measure.repeatStart) {
      logger.fine("Creating a repeated phrase at " + measure.getNumber());
      sp = makeRepeatedSongPhrase(song, itM, itMTP, tracks);
    }

    // Failing everything else, just return a single measure
    if (sp == null) {
      logger.fine("Creating a measure phrase at " + measure.getNumber());
      sp = makeSongMeasure(song, itM, itMTP, tracks);
    }
    return sp;
  }
Exemple #11
0
 public void trySlap(int player) {
   log.finer(getPlayerName(player) + " is trying to slap: " + topFiveCards());
   if (isSlap()) {
     // successful slap
     log.fine(getPlayerName(player) + " just slapped some cards!");
     pickupPot(player);
     GamePanel.playNoiseSlap();
     gamePanel.addRenderable(
         new RenderableImageKinetic(this, RenderableImageKinetic.SLAP, player));
   } else if (player == topFacecardOwner && isFacecardPickup()) {
     // successful pickup
     log.fine(getPlayerName(player) + " picked up some cards");
     pickupPot(player);
     GamePanel.playNoisePickup();
     gamePanel.addRenderable(
         new RenderableImageKinetic(this, RenderableImageKinetic.PICKUP, player));
     AI.registerEvent(AI.TYPENOTHING); // so the AI will make a move if it is their turn now
   } else if (stackPot.isEmpty()) {
     // if they slapped an empty pot
     // we don't punish them because this probably just means there was a slap, but someone else
     // has already picked it up.
     log.finer(getPlayerName(player) + " slapped an empty pot. (They did not have to burn)");
   } else {
     burn(player);
   }
 }
  private void backfillNodesTables() {
    // If complete ways is set, select all nodes contained by the ways into
    // the node temp table.
    LOG.finer("Selecting all nodes for selected ways.");
    jdbcTemplate.update("CREATE TEMPORARY TABLE bbox_way_nodes (id bigint) ON COMMIT DROP");
    jdbcTemplate.queryForList("SELECT unnest_bbox_way_nodes()");
    jdbcTemplate.update(
        "CREATE TEMPORARY TABLE bbox_missing_way_nodes ON COMMIT DROP AS "
            + "SELECT buwn.id FROM (SELECT DISTINCT bwn.id FROM bbox_way_nodes bwn) buwn "
            + "WHERE NOT EXISTS ("
            + "    SELECT * FROM bbox_nodes WHERE id = buwn.id"
            + ");");
    jdbcTemplate.update(
        "ALTER TABLE ONLY bbox_missing_way_nodes"
            + " ADD CONSTRAINT pk_bbox_missing_way_nodes PRIMARY KEY (id)");
    jdbcTemplate.update("ANALYZE bbox_missing_way_nodes");
    int rowCount =
        jdbcTemplate.update(
            "INSERT INTO bbox_nodes "
                + "SELECT n.* FROM nodes n INNER JOIN bbox_missing_way_nodes bwn ON n.id = bwn.id;");
    LOG.finer(rowCount + " rows affected.");

    LOG.finer("Updating query analyzer statistics on the temporary nodes table.");
    jdbcTemplate.update("ANALYZE bbox_nodes");
  }
  private int populateRelationTables(String whereStr, List<Object> whereObj) {
    // Select all relations containing the nodes or ways into the relation
    // table.
    LOG.finer("Selecting all relation ids containing selected nodes or ways.");
    int rowCount =
        jdbcTemplate.update(
            "CREATE TEMPORARY TABLE bbox_relations ON COMMIT DROP AS"
                + " SELECT r.* FROM relations r"
                + " INNER JOIN ("
                + "    SELECT relation_id FROM ("
                + "        SELECT rm.relation_id AS relation_id FROM relation_members rm"
                + "        INNER JOIN bbox_nodes n ON rm.member_id = n.id WHERE rm.member_type = 'N' "
                + "        UNION "
                + "        SELECT rm.relation_id AS relation_id FROM relation_members rm"
                + "        INNER JOIN bbox_ways w ON rm.member_id = w.id WHERE rm.member_type = 'W'"
                + "     ) rids GROUP BY relation_id"
                + ") rids ON r.id = rids.relation_id "
                + "UNION "
                + "SELECT * FROM relations WHERE "
                + whereStr,
            whereObj.toArray());
    LOG.finer(rowCount + " rows affected.");

    LOG.finer("Adding a primary key to the temporary relations table.");
    jdbcTemplate.update(
        "ALTER TABLE ONLY bbox_relations ADD CONSTRAINT pk_bbox_relations PRIMARY KEY (id)");

    LOG.finer("Updating query analyzer statistics on the temporary relations table.");
    jdbcTemplate.update("ANALYZE bbox_relations");

    return rowCount;
  }
Exemple #14
0
  /**
   * Seek for box with the specified id starting from the current location of filepointer,
   *
   * <p>Note it wont find the box if it is contained with a level below the current level, nor if we
   * are at a parent atom that also contains data and we havent yet processed the data. It will work
   * if we are at the start of a child box even if it not the required box as long as the box we are
   * looking for is the same level (or the level above in some cases).
   *
   * @param raf
   * @param id
   * @throws java.io.IOException
   */
  public static Mp4BoxHeader seekWithinLevel(RandomAccessFile raf, String id) throws IOException {
    logger.finer("Started searching for:" + id + " in file at:" + raf.getChannel().position());

    Mp4BoxHeader boxHeader = new Mp4BoxHeader();
    ByteBuffer headerBuffer = ByteBuffer.allocate(HEADER_LENGTH);
    int bytesRead = raf.getChannel().read(headerBuffer);
    if (bytesRead != HEADER_LENGTH) {
      return null;
    }
    headerBuffer.rewind();
    boxHeader.update(headerBuffer);
    while (!boxHeader.getId().equals(id)) {
      logger.finer("Still searching for:" + id + " in file at:" + raf.getChannel().position());

      // Something gone wrong probably not at the start of an atom so return null;
      if (boxHeader.getLength() < Mp4BoxHeader.HEADER_LENGTH) {
        return null;
      }
      int noOfBytesSkipped = raf.skipBytes(boxHeader.getDataLength());
      logger.finer("Skipped:" + noOfBytesSkipped);
      if (noOfBytesSkipped < boxHeader.getDataLength()) {
        return null;
      }
      headerBuffer.rewind();
      bytesRead = raf.getChannel().read(headerBuffer);
      logger.finer("Header Bytes Read:" + bytesRead);
      headerBuffer.rewind();
      if (bytesRead == Mp4BoxHeader.HEADER_LENGTH) {
        boxHeader.update(headerBuffer);
      } else {
        return null;
      }
    }
    return boxHeader;
  }
  /** Vote using phase-1 of the 2-phase commit. */
  public int prepare(Xid xid) throws XAException {
    if (_endFlags != -1) {
      int endFlags = _endFlags;
      _endFlags = -1;

      if (_isXATransaction) endResource(xid, endFlags);
    }

    if (_isXATransaction) {
      try {
        if (log.isLoggable(Level.FINER)) log.finer("prepare-XA: " + xid + " " + _xaResource);

        int result = _xaResource.prepare(xid);

        if (result == XA_RDONLY) {
          if (_xaResource != null) _isXATransaction = true;

          clearXid();
        }

        return result;
      } catch (XAException e) {
        if (log.isLoggable(Level.FINER))
          log.finer("failed prepare-XA: " + xid + " " + _xaResource + " " + e);

        throw e;
      }
    } else return XA_OK;
  }
Exemple #16
0
  /**
   * Seek for box with the specified id starting from the current location of filepointer,
   *
   * <p>Note it won't find the box if it is contained with a level below the current level, nor if
   * we are at a parent atom that also contains data and we havent yet processed the data. It will
   * work if we are at the start of a child box even if it not the required box as long as the box
   * we are looking for is the same level (or the level above in some cases).
   *
   * @param data
   * @param id
   * @throws java.io.IOException
   */
  public static Mp4BoxHeader seekWithinLevel(ByteBuffer data, String id) throws IOException {
    logger.finer("Started searching for:" + id + " in bytebuffer at" + data.position());

    Mp4BoxHeader boxHeader = new Mp4BoxHeader();
    if (data.remaining() >= Mp4BoxHeader.HEADER_LENGTH) {
      boxHeader.update(data);
    } else {
      return null;
    }
    while (!boxHeader.getId().equals(id)) {
      logger.finer(
          "Found"
              + boxHeader.getId()
              + "Still searching for:"
              + id
              + " in bytebuffer at"
              + data.position());
      // Something gone wrong probably not at the start of an atom so return null;
      if (boxHeader.getLength() < Mp4BoxHeader.HEADER_LENGTH) {
        return null;
      }
      data.position(data.position() + (boxHeader.getLength() - HEADER_LENGTH));
      if (data.remaining() >= Mp4BoxHeader.HEADER_LENGTH) {
        boxHeader.update(data);
      } else {
        return null;
      }
    }
    return boxHeader;
  }
  public static String idToClass(String repid) {
    // debug
    logger.finer("idToClass " + repid);

    if (repid.startsWith("IDL:")) {

      ByteString id = new ByteString(repid);

      try {
        int end = id.lastIndexOf(':');
        ByteString s = end < 0 ? id.substring(4) : id.substring(4, end);

        ByteBuffer bb = new ByteBuffer();

        //
        // reverse order of dot-separated name components up
        // till the first slash.
        //
        int firstSlash = s.indexOf('/');
        if (firstSlash > 0) {
          ByteString prefix = s.substring(0, firstSlash);
          ByteString[] elems = prefix.split('.');

          for (int i = elems.length - 1; i >= 0; i--) {
            bb.append(fixName(elems[i]));
            bb.append('.');
          }

          s = s.substring(firstSlash + 1);
        }

        //
        // Append slash-separated name components ...
        //
        ByteString[] elems = s.split('/');
        for (int i = 0; i < elems.length; i++) {
          bb.append(fixName(elems[i]));
          if (i != elems.length - 1) bb.append('.');
        }

        String result = bb.toString();

        logger.finer("idToClassName " + repid + " => " + result);

        return result;
      } catch (IndexOutOfBoundsException ex) {
        logger.log(Level.FINE, "idToClass " + ex.getMessage(), ex);
        return null;
      }

    } else if (repid.startsWith("RMI:")) {
      int end = repid.indexOf(':', 4);
      return end < 0 ? repid.substring(4) : repid.substring(4, end);
    }

    return null;
  }
Exemple #18
0
  /**
   * The launching point
   *
   * <p>In development, pass the following on the JVM command line:
   * <tt>-Djava.util.logging.config.file=config/logging.properties</tt>
   *
   * <p>On Mac, add the following (otherwise SWT won't work): <tt>-XstartOnFirstThread</tt>
   */
  public static void main(String... args) {
    long startTime = System.currentTimeMillis();

    initSystemProperties();
    Display display;

    try {
      // this defines the Window class and app name on the Mac
      Display.setAppName(Version.NAME);
      display = Display.getDefault();
      LOG.finer("SWT initialized after " + (System.currentTimeMillis() - startTime));
    } catch (UnsatisfiedLinkError e) {
      JOptionPane.showMessageDialog(
          null,
          "Failed to load native code. Probably you are using a binary built for wrong OS or CPU - try downloading both 32-bit and 64-bit binaries");
      return;
    }

    // initialize Labels instance
    Labels.initialize(Locale.getDefault());
    // initialize Config instance
    Config globalConfig = Config.getConfig();
    LOG.finer("Labels and Config initialized after " + (System.currentTimeMillis() - startTime));

    ComponentRegistry componentRegistry = new ComponentRegistry();
    LOG.finer("ComponentRegistry initialized after " + (System.currentTimeMillis() - startTime));

    processCommandLine(args, componentRegistry);

    // create the main window using dependency injection
    MainWindow mainWindow = componentRegistry.getMainWindow();
    LOG.fine("Startup time: " + (System.currentTimeMillis() - startTime));

    while (!mainWindow.isDisposed()) {
      try {
        if (!display.readAndDispatch()) display.sleep();
      } catch (Throwable e) {
        if (e instanceof SWTException && e.getCause() != null) e = e.getCause();

        // display a nice error message
        String localizedMessage = getLocalizedMessage(e);
        Shell parent = display.getActiveShell();
        showMessage(
            parent != null ? parent : mainWindow.getShell(),
            e instanceof UserErrorException ? SWT.ICON_WARNING : SWT.ICON_ERROR,
            Labels.getLabel(e instanceof UserErrorException ? "text.userError" : "text.error"),
            localizedMessage);
      }
    }

    // save config on exit
    globalConfig.store();

    // dispose the native objects
    display.dispose();
  }
  /**
   * Create the expression object given a text representation of it.
   *
   * @param source
   * @param warehouse used to resolve the ECDIS variables.
   */
  public GeoSymAttExpression(String source, VPFAutoFeatureGraphicWarehouse warehouse) {
    // Warehouse must be set first.
    this.warehouse = warehouse;
    exp = findExpression(source);

    if (logger.isLoggable(Level.FINER)) {
      logger.finer("Parsing: " + source);
      logger.finer(this.toString());
    }
  }
Exemple #20
0
  /**
   * Creates a new TDWay from an osmosis way entity using the given NodeResolver.
   *
   * @param way the way
   * @param resolver the resolver
   * @param preferredLanguage the preferred language or null if no preference
   * @return a new TDWay if it is valid, null otherwise
   */
  public static TDWay fromWay(Way way, NodeResolver resolver, String preferredLanguage) {
    if (way == null) return null;

    SpecialTagExtractionResult ster = OSMUtils.extractSpecialFields(way, preferredLanguage);
    short[] knownWayTags = OSMUtils.extractKnownWayTags(way); // NOPMD by bross on 25.12.11 13:04

    // only ways with at least 2 way nodes are valid ways
    if (way.getWayNodes().size() >= 2) {

      boolean validWay = true;
      // retrieve way nodes from data store
      TDNode[] waynodes = new TDNode[way.getWayNodes().size()];
      int i = 0;
      for (WayNode waynode : way.getWayNodes()) {
        // TODO adjust interface to support a method getWayNodes()
        waynodes[i] = resolver.getNode(waynode.getNodeId());
        if (waynodes[i] == null) {
          validWay = false;
          LOGGER.finer("unknown way node: " + waynode.getNodeId() + " in way " + way.getId());
        }
        i++;
      }

      // for a valid way all way nodes must be existent in the input data
      if (validWay) {

        // mark the way as polygon if the first and the last way node are the same
        // and if the way has at least 4 way nodes
        byte shape = LINE;
        if (waynodes[0].getId() == waynodes[waynodes.length - 1].getId()) {
          if (waynodes.length >= GeoUtils.MIN_NODES_POLYGON) {
            shape = SIMPLE_POLYGON;
          } else {
            LOGGER.finer(
                "Found closed polygon with fewer than 4 way nodes. Way-id: " + way.getId());
            return null;
          }
        }

        java.util.Arrays.sort(knownWayTags);

        return new TDWay(
            way.getId(),
            ster.getLayer(),
            ster.getName(),
            ster.getHousenumber(),
            ster.getRef(),
            knownWayTags,
            shape,
            waynodes);
      }
    }

    return null;
  }
  /** starts work on a transaction branch */
  public void start(Xid xid, int flags) throws XAException {
    if (_xid != null) {
      if (log.isLoggable(Level.FINER)) log.finer("connection pool start XA: rejoin " + this);

      return;
    }

    if (flags == TMJOIN && _xid == null) {
      // TMJOIN means the resource manager is managing more than one
      // connection.  The delegates tie the PoolItems managed by
      // the same resource manager together.

      _xid = xid;

      UserTransactionImpl trans = _cm.getTransaction();

      if (trans != null) {
        ManagedPoolItem xaHead = trans.findJoin(this);

        if (xaHead != null) {
          _xaNext = xaHead._xaNext;
          _xaHead = xaHead;
          xaHead._xaNext = this;
        }
      }
    }

    // local transaction optimization
    if (!_isXATransaction && flags != TMJOIN && _localTransaction != null) {
      try {
        if (log.isLoggable(Level.FINER))
          log.finer("begin-local-XA: " + xid + " " + _localTransaction);

        _localTransaction.begin();
      } catch (ResourceException e) {
        throw new XAExceptionWrapper(e);
      }

      _xid = xid;

      return;
    }

    if (_xaResource != null) {
      if (log.isLoggable(Level.FINER)) log.finer("start-XA: " + xid + " " + _xaResource);

      _xaResource.start(xid, flags);
      _isXATransaction = true;
    } else {
      if (log.isLoggable(Level.FINER))
        log.finer("start-XA with non XA resource: " + xid + " " + _xaResource);
    }

    _xid = xid;
  }
Exemple #22
0
 public void tryFlip(int player) {
   if (player == playerTurn && !isFacecardPickup()) {
     // flipping
     GamePanel.playNoiseFlip();
     stackPot.addToTop(playerCards.get(player).removeTopCard());
     log.finer(getPlayerName(player) + " flipped the " + Card.toString(stackPot.getTopCard()));
     if (Card.isFaceCard(stackPot.getTopCard())) {
       topFacecardOwner = player;
       topFacecardMaxSize = Card.getRank(stackPot.getTopCard());
       switch (topFacecardMaxSize) {
         case Card.ACE:
           topFacecardMaxSize = stackPot.size() + 4;
           break;
         case Card.KING:
           topFacecardMaxSize = stackPot.size() + 3;
           break;
         case Card.QUEEN:
           topFacecardMaxSize = stackPot.size() + 2;
           break;
         case Card.JACK:
           topFacecardMaxSize = stackPot.size() + 1;
           break;
         default:
           throw new RuntimeException(
               "This should never happen. A face card was not an ace, king, queen, or jack.");
       }
       turnIncrement();
     } else if (topFacecardOwner == -1) {
       // if no facecards have been played this hand
       turnIncrement();
     }
     if (playerCards.get(player).isEmpty()) {
       log.fine(getPlayerName(player) + " is eliminated because they flipped their last card");
       eliminatePlayer(player);
     }
     if (isSlap()) {
       AI.registerEvent(AI.TYPESLAP);
     } else {
       AI.registerEvent(AI.TYPEFLIP);
     }
   } else {
     // flipping out of turn
     if (playerCards.get(player).isEmpty()) {
       // flipping out of turn but have no cards
       log.finer(
           getPlayerName(player) + " tried to flip a card even though they have no cards...");
     } else {
       // flipping out of turn so burning
       log.fine(getPlayerName(player) + " tried to flip a card illegally and had to burn a card");
       burn(player);
     }
   }
 }
Exemple #23
0
  /** Release reserved resources. This is the opposite of {@link #daemonInit}. */
  synchronized void daemonDestroy(long time, TimeUnit unit) {
    if (primaryServer != null) {
      httpServerShutdown(primaryServer, time, unit);
      log.finer("Completed primary server stop");
      primaryServer = null;
    }

    if (dashboardServer != null) {
      httpServerShutdown(dashboardServer, time, unit);
      log.finer("Completed dashboard stop");
      dashboardServer = null;
    }
  }
 @Override
 public void contextDestroyed(final ServletContextEvent servletContextEvent) {
   super.contextDestroyed(servletContextEvent);
   if (servletContextListeners != null) {
     Iterator<ServletContextListener> it = servletContextListeners.iterator();
     while (it.hasNext()) {
       ServletContextListener listener = it.next();
       logger.finer("Destroy ServletContextListener: " + listener.getClass().getName());
       listener.contextDestroyed(servletContextEvent);
     }
   }
   logger.finer("Destroyed ServletContextListener");
 }
  /** @see org.geotools.arcsde.session.ISessionPool#getSession(boolean) */
  public ISession getSession(final boolean transactional)
      throws IOException, UnavailableConnectionException {
    checkOpen();
    try {
      Session connection = null;
      if (transactional) {
        LOGGER.finest("Borrowing session from pool for transactional access");
        connection = (Session) pool.borrowObject();
      } else {
        synchronized (openSessionsNonTransactional) {
          try {
            if (LOGGER.isLoggable(Level.FINER)) {
              LOGGER.finer("Grabbing session from pool on " + Thread.currentThread().getName());
            }
            connection = (Session) pool.borrowObject();
            if (LOGGER.isLoggable(Level.FINER)) {
              LOGGER.finer("Got session from the pool on " + Thread.currentThread().getName());
            }
          } catch (NoSuchElementException e) {
            if (LOGGER.isLoggable(Level.FINER)) {
              LOGGER.finer("No available sessions in the pool, falling back to queued session");
            }
            connection = openSessionsNonTransactional.remove();
          }

          openSessionsNonTransactional.add(connection);

          if (LOGGER.isLoggable(Level.FINER)) {
            LOGGER.finer(
                "Got session from the in use queue on " + Thread.currentThread().getName());
          }
        }
      }

      connection.markActive();
      return connection;

    } catch (NoSuchElementException e) {
      LOGGER.log(
          Level.WARNING, "Out of connections: " + e.getMessage() + ". Config: " + this.config);
      throw new UnavailableConnectionException(config.getMaxConnections(), this.config);
    } catch (SeException se) {
      ArcSdeException sdee = new ArcSdeException(se);
      LOGGER.log(Level.WARNING, "ArcSDE error getting connection for " + config, sdee);
      throw sdee;
    } catch (Exception e) {
      LOGGER.log(Level.WARNING, "Unknown problem getting connection: " + e.getMessage(), e);
      throw (IOException)
          new IOException("Unknown problem fetching connection from connection pool").initCause(e);
    }
  }
Exemple #26
0
 /** @see jaskell.compiler.JaskellVisitor#visit(Application) */
 public Object visit(Application a) {
   try {
     /* get type of function */
     Expression fun = a.getFunction();
     /* get type deduced from arguments */
     LinkedList l = new LinkedList();
     Iterator it = a.getArgs().iterator();
     while (it.hasNext()) {
       Expression e = (Expression) it.next();
       l.add((Type) e.visit(this));
     }
     Type vt = TypeFactory.freshBinding();
     Type ft = Types.fun(l, vt);
     log.finer("TypeChecker => In application " + a + ", type is " + ft);
     /* apply substitution on both types */
     ft = subst.substitute(ft);
     /* try to unify function type and constructed types */
     Type t = (Type) fun.visit(this);
     log.finer("In application, function " + fun + " :: " + t);
     t = subst.substitute(t);
     log.finer("In application, trying to unify function type " + t + " with body " + ft);
     /*
      * TODO : problem with unification of constrained types
      */
     TypeApplication uni = (TypeApplication) tu.unify(t, ft, typeVariablesMap);
     /* sets type of functional expression - this allows
      * polymorphic functions to receive several types
      * in the same code */
     // fun.setType(uni);
     /* apply arguments type to compute return type */
     log.finer("Done unify application :" + uni);
     it = PrimitiveType.functionIterator(uni);
     Iterator it2 = l.iterator();
     TypeApplication ut = uni;
     while (it2.hasNext()) {
       /* type of argument */
       Type at = (Type) it2.next();
       ut = (TypeApplication) it.next();
       /* try unification */
       tu.unify(((TypeApplication) ut.getDomain()).getRange(), at, new HashMap(typeVariablesMap));
     }
     ft = subst.substitute(ft);
     fun.setType(ft);
     log.finer("Setting type of functional element [" + fun + "] to :" + ft);
     a.setType(ut.getRange());
     return ut.getRange();
   } catch (TypeError te) {
     if (te.getLineCol() == null) te.setLineCol(a.getTag("source"));
     throw te;
   }
 }
  /**
   * Makes sure that the response type is correct. The response type for a NON can be NON or CON.
   * The response type for a CON should either be an ACK with a piggy-backed response or, if an
   * empty ACK has already be sent, a CON or NON with a separate response.
   */
  @Override
  public void sendResponse(final Exchange exchange, final Response response) {

    LOGGER.finer("Send response, failed transmissions: " + exchange.getFailedTransmissionCount());

    // If a response type is set, we do not mess around with it.
    // Only if none is set, we have to decide for one here.

    Type respType = response.getType();
    if (respType == null) {
      Type reqType = exchange.getCurrentRequest().getType();
      if (reqType == Type.CON) {
        if (exchange.getCurrentRequest().isAcknowledged()) {
          // send separate response
          response.setType(Type.CON);
        } else {
          exchange.getCurrentRequest().setAcknowledged(true);
          // send piggy-backed response
          response.setType(Type.ACK);
          response.setMID(exchange.getCurrentRequest().getMID());
        }
      } else {
        // send NON response
        response.setType(Type.NON);
      }

      LOGGER.finest(
          "Switched response message type from "
              + respType
              + " to "
              + response.getType()
              + " (request was "
              + reqType
              + ")");

    } else if (respType == Type.ACK || respType == Type.RST) {
      response.setMID(exchange.getCurrentRequest().getMID());
    }

    if (response.getType() == Type.CON) {
      LOGGER.finer("Scheduling retransmission for " + response);
      prepareRetransmission(
          exchange,
          new RetransmissionTask(exchange, response) {
            public void retransmit() {
              sendResponse(exchange, response);
            }
          });
    }
    super.sendResponse(exchange, response);
  }
  /** commit the resource */
  public void commit(Xid xid, boolean onePhase) throws XAException {
    boolean logFiner = log.isLoggable(Level.FINER);

    try {
      int endFlags = _endFlags;
      _endFlags = -1;

      if (endFlags != -1 && _isXATransaction) {
        boolean isValid = false;

        try {
          endResource(xid, endFlags);
          isValid = true;
        } finally {
          if (!isValid) _xaResource.rollback(xid);
        }
      }

      if (_isXATransaction) {
        if (logFiner) {
          log.finer("commit-XA" + (onePhase ? "-1p: " : ": ") + xid + " " + _xaResource);
        }

        try {
          _xaResource.commit(xid, onePhase);
        } catch (XAException e) {
          if (logFiner) log.finer("commit-XA failed: " + _xaResource + " " + e);

          throw e;
        }
      } else if (_localTransaction != null) {
        if (logFiner) log.finer("commit-local: " + _localTransaction);

        try {
          _localTransaction.commit();
        } catch (ResourceException e) {
          if (logFiner) log.finer("commit failed: " + _localTransaction + " " + e);

          throw new XAExceptionWrapper(e);
        } finally {
          _isLocalTransaction = false;
        }
      } else {
        if (logFiner) log.finer("commit for resource with no XA support: " + this);
      }
    } finally {
      if (_xaResource != null) _isXATransaction = true;

      clearXid();
    }
  }
    private void setupVirginStart() throws FileNotFoundException {
        RAFChunk chunk;
        totalLinkBytesLoaded = 0;
        downloadLink.setDownloadCurrent(0);
        long partSize = getFileSize() / getChunkNum();
        if (connection.getRange() != null) {
            if ((connection.getRange()[1] == connection.getRange()[2] - 1) || (connection.getRange()[1] == connection.getRange()[2])) {
                logger.warning("Chunkload protection. this may cause traffic errors");
                partSize = getFileSize() / getChunkNum();
            } else {
                // Falls schon der 1. range angefordert wurde.... werden die
                // restlichen chunks angepasst
                partSize = (getFileSize() - connection.getLongContentLength()) / (getChunkNum() - 1);
            }
        }
        if (partSize <= 0) {
            logger.warning("Could not get Filesize.... reset chunks to 1");
            setChunkNum(1);
        }
        logger.finer("Start Download in " + getChunkNum() + " chunks. Chunksize: " + partSize);

        createOutputChannel();
        downloadLink.setChunksProgress(new long[chunkNum]);

        addToChunksInProgress(getChunkNum());
        int start = 0;

        long rangePosition = 0;
        if (connection.getRange() != null && connection.getRange()[1] != connection.getRange()[2] - 1) {
            // Erster range schon angefordert

            chunk = new RAFChunk(0, rangePosition = connection.getRange()[1], connection, this, downloadLink);
            rangePosition++;
            logger.finer("Setup chunk 0: " + chunk);
            addChunk(chunk);
            start++;
        }

        for (int i = start; i < getChunkNum(); i++) {
            if (i == getChunkNum() - 1) {
                chunk = new RAFChunk(rangePosition, -1, connection, this, downloadLink);
            } else {
                chunk = new RAFChunk(rangePosition, rangePosition + partSize - 1, connection, this, downloadLink);
                rangePosition = rangePosition + partSize;
            }
            logger.finer("Setup chunk " + i + ": " + chunk);
            addChunk(chunk);
        }

    }
Exemple #30
0
 /**
  * Returns null or throws a TypeError if type cannot be inferred for any definition found.
  * Verifies that main symbol in Main module is typed as <code>IO ()</code>.
  *
  * @see jaskell.compiler.JaskellVisitor#visit(Module)
  */
 public Object visit(Namespace a) {
   // visit definitions
   Iterator it = a.getAllBindings().entrySet().iterator();
   while (it.hasNext()) {
     Map.Entry entry = (Map.Entry) it.next();
     String name = (String) entry.getKey();
     Expression def = (Expression) entry.getValue();
     Type type = (Type) def.visit(this);
     def.setType(type);
     log.finer("TypeChecker => END Visiting " + name);
   }
   log.finer("Substitution map = " + typeVariablesMap);
   return null;
 }