/**
   * Finds the {@link DataSet} that contains the given file. This methods will also performs some
   * checks to make sure the given file is a valid file in the data set.
   *
   * <p>All the information is set in a {@link FileValidity} object that is returned. If an instance
   * is passed, then this object is filled instead, and returned.
   *
   * <p>{@link FileValidity} contains information about the changed file including: - is it from an
   * known set, is it an ignored file, or is it unknown? - what data set does it belong to - what
   * source folder in the data set does it belong to.
   *
   * <p>"belong" means that the DataSet has a source file/folder that is the root folder of this
   * file. The folder and/or file doesn't have to exist.
   *
   * @param file the file to check
   * @param fileValidity an optional FileValidity to fill. If null a new one is returned.
   * @return a new FileValidity or the one given as a parameter.
   */
  public FileValidity<S> findDataSetContaining(
      @NonNull File file, @Nullable FileValidity<S> fileValidity) {
    if (fileValidity == null) {
      fileValidity = new FileValidity<S>();
    }

    if (mDataSets.isEmpty()) {
      fileValidity.status = FileValidity.FileStatus.UNKNOWN_FILE;
      return fileValidity;
    }

    if (DataSet.isIgnored(file)) {
      fileValidity.status = FileValidity.FileStatus.IGNORED_FILE;
      return fileValidity;
    }

    for (S dataSet : mDataSets) {
      File sourceFile = dataSet.findMatchingSourceFile(file);

      if (sourceFile != null) {
        fileValidity.dataSet = dataSet;
        fileValidity.sourceFile = sourceFile;
        fileValidity.status =
            dataSet.isValidSourceFile(sourceFile, file)
                ? FileValidity.FileStatus.VALID_FILE
                : FileValidity.FileStatus.IGNORED_FILE;
        return fileValidity;
      }
    }

    fileValidity.status = FileValidity.FileStatus.UNKNOWN_FILE;
    return fileValidity;
  }
 @Override
 public Double getValue(S solution) {
   if (getConstraintIndex() >= solution.getNumberOfConstraints())
     throw new IllegalArgumentException(
         "Solution does not have " + getConstraintIndex() + 1 + " constraints.");
   return solution.getConstraint(getConstraintIndex());
 }
Esempio n. 3
0
  @Override
  public <S> Entry<S> loadSaga(Class<S> sagaType, String sagaIdentifier) {
    EntityManager entityManager = entityManagerProvider.getEntityManager();
    List<SerializedSaga> serializedSagaList =
        entityManager
            .createNamedQuery(LOAD_SAGA_NAMED_QUERY, SerializedSaga.class)
            .setParameter("sagaId", sagaIdentifier)
            .setParameter("sagaType", getSagaTypeName(sagaType))
            .setMaxResults(1)
            .getResultList();
    if (serializedSagaList == null || serializedSagaList.isEmpty()) {
      return null;
    }

    SerializedSaga serializedSaga = serializedSagaList.get(0);
    S loadedSaga = serializer.deserialize(serializedSaga);
    if (injector != null) {
      injector.injectResources(loadedSaga);
    }
    Set<AssociationValue> associationValues =
        loadAssociationValues(entityManager, sagaType, sagaIdentifier);
    if (logger.isDebugEnabled()) {
      logger.debug(
          "Loaded saga id [{}] of type [{}]", sagaIdentifier, loadedSaga.getClass().getName());
    }
    return new EntryImpl<>(associationValues, loadedSaga);
  }
Esempio n. 4
0
 @SuppressWarnings("unchecked")
 public static <S, T> CollectionRemovedFromEvent<S, T> newEvent(
     final Class<? extends CollectionRemovedFromEvent<S, T>> type,
     final S source,
     final Identifier identifier,
     final T value)
     throws InstantiationException, IllegalAccessException, IllegalArgumentException,
         InvocationTargetException, NoSuchMethodException, SecurityException {
   final Constructor<?>[] constructors = type.getConstructors();
   for (final Constructor<?> constructor : constructors) {
     final Class<?>[] parameterTypes = constructor.getParameterTypes();
     if (parameterTypes.length != 3) {
       continue;
     }
     if (!parameterTypes[0].isAssignableFrom(source.getClass())) {
       continue;
     }
     if (!parameterTypes[1].isAssignableFrom(Identifier.class)) {
       continue;
     }
     if (value != null && !parameterTypes[2].isAssignableFrom(value.getClass())) {
       continue;
     }
     final Object event = constructor.newInstance(source, identifier, value);
     return (CollectionRemovedFromEvent<S, T>) event;
   }
   throw new NoSuchMethodException(
       type.getName()
           + ".<init>(? super "
           + source.getClass().getName()
           + ", "
           + Identifier.class.getName()
           + ", java.lang.Object)");
 }
 /** 强制出票 */
 public String batchForcePrint() {
   Map<String, Object> map = new HashMap<String, Object>();
   try {
     AdminUser adminUser = getAdminUser();
     if (null == adminUser) {
       throw new WebDataException("你还没有登录!");
     }
     if (this.id == null) {
       throw new DataException("方案ID不能为空.");
     }
     S s = kenoService.forcePrint(this.id);
     // 记录操作日志
     eventLogManager.saveSimpleEventLog(
         null,
         getLottery(),
         adminUser,
         EventLogType.ForcePrint,
         "方案为ID:" + s.getId() + "方案号为+" + s.getSchemeNumber());
     map.put("success", true);
     map.put("msg", "强制出票成功");
   } catch (ServiceException e) {
     e.printStackTrace();
     map.put("success", false);
     map.put("msg", e.getMessage());
   } catch (Exception e) {
     e.printStackTrace();
     map.put("success", false);
     map.put("msg", "强制出票发生异常!");
   }
   Struts2Utils.renderJson(map);
   return null;
 }
 /**
  * Removes the specified service from this service manager, stopping and terminating it as
  * required. If this service manager is in a started state then the service will be stopped. After
  * removal, the service will be terminated.
  */
 public <S extends Service<T>> void removeService(S s) {
   if (started) {
     s.stop();
   }
   services.remove(s);
   s.terminate(getParent());
 }
Esempio n. 7
0
  /**
   * Runs a range query on the local machine by iterating over the whole file.
   *
   * @param fs - FileSystem that contains input file
   * @param file - path to the input file
   * @param queryRange - The range to look in
   * @param shape - An instance of the shape stored in file
   * @param output - Output is sent to this collector. If <code>null</code>, output is not collected
   *     and only the number of results is returned.
   * @return number of results found
   * @throws IOException
   */
  public static <S extends Shape> long rangeQueryLocal(
      FileSystem fs, Path file, Shape queryRange, S shape, ResultCollector<S> output)
      throws IOException {
    long file_size = fs.getFileStatus(file).getLen();
    ShapeRecordReader<S> shapeReader = new ShapeRecordReader<S>(fs.open(file), 0, file_size);

    long resultCount = 0;
    Prism cell = shapeReader.createKey();

    while (shapeReader.next(cell, shape)) {
      if (shape.isIntersected(queryRange)) {
        boolean report_result;
        if (cell.isValid()) {
          // Check for duplicate avoidance
          Prism intersection_mbr = queryRange.getMBR().getIntersection(shape.getMBR());
          report_result =
              cell.contains(intersection_mbr.t1, intersection_mbr.x1, intersection_mbr.y1);
        } else {
          report_result = true;
        }
        if (report_result) {
          resultCount++;
          if (output != null) {
            output.collect(shape);
          }
        }
      }
    }
    shapeReader.close();
    return resultCount;
  }
 /**
  * Adds the specified service and initializes it. If the service manager has already been started
  * then the service will also be started.
  */
 public <S extends Service<T>> void addService(S s) {
   services.add(s);
   s.initialize(getParent());
   if (started) {
     s.start();
   }
 }
Esempio n. 9
0
  @SuppressWarnings({"unchecked", "rawtypes"})
  @Override
  protected boolean executeMoveImplem(S solution, IMove move) {
    if (!(move instanceof TwoOptMove)) {
      throw new IllegalArgumentException("The move must be of type TwoOptMove");
    }

    boolean r;

    TwoOptMove twoOptMove = (TwoOptMove) move;

    IRoute rI = solution.getRoute(twoOptMove.getRouteI());
    IRoute rJ = null;
    int i = twoOptMove.getI();
    int j = twoOptMove.getJ();

    // Intra route move
    if (twoOptMove.getRouteI() == twoOptMove.getRouteJ()) {
      // Remove (nodeI,nodeI+1) and (nodeJ,nodeJ+1)
      // Reconnect nodeI with nodeJ and nodeI+1 with nodeJ+1
      rI.reverseSubRoute(i + 1, j);

      // rI.updateCost(-twoOptMove.getImprovement());

      r = true;
      // Inter route move
    } else {
      rJ = solution.getRoute(twoOptMove.getRouteJ());

      // Auxiliary method to solve type safety problems
      r = executeMove(rI, rJ, i, j, twoOptMove.isStar());
    }
    return r;
  }
  /**
   * Process a new session : - initialize it - create its chain - fire the CREATED listeners if any
   *
   * @param session The session to create
   * @return true if the session has been registered
   */
  private boolean addNow(S session) {
    boolean registered = false;

    try {
      init(session);
      registered = true;

      // Build the filter chain of this session.
      IoFilterChainBuilder chainBuilder = session.getService().getFilterChainBuilder();
      chainBuilder.buildFilterChain(session.getFilterChain());

      // DefaultIoFilterChain.CONNECT_FUTURE is cleared inside here
      // in AbstractIoFilterChain.fireSessionOpened().
      // Propagate the SESSION_CREATED event up to the chain
      IoServiceListenerSupport listeners =
          ((AbstractIoService) session.getService()).getListeners();
      listeners.fireSessionCreated(session);
    } catch (Throwable e) {
      ExceptionMonitor.getInstance().exceptionCaught(e);

      try {
        destroy(session);
      } catch (Exception e1) {
        ExceptionMonitor.getInstance().exceptionCaught(e1);
      } finally {
        registered = false;
      }
    }

    return registered;
  }
  @Override
  @SuppressWarnings("unchecked")
  public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {

    S serverChannel = (S) ctx.getAttachment();

    T childChannel = createChildChannel(serverChannel, e.getChannel());
    fireChannelOpen(childChannel);

    ChannelAddress localAddress = serverChannel.getLocalAddress();
    childChannel.setLocalAddress(localAddress);
    childChannel.setBound();
    fireChannelBound(childChannel, localAddress);

    ctx.setAttachment(childChannel);

    ctx.sendUpstream(e);

    // TODO: fire CONNECTED_BARRIER event to next pipeline
    // then fire CONNECTED event when future completes successfully
    ChannelAddress remoteAddress = localAddress.newEphemeralAddress();
    childChannel.setRemoteAddress(remoteAddress);
    childChannel.setConnected();
    fireChannelConnected(childChannel, remoteAddress);
  }
  @Override
  public <S extends StreamDefinition> S save(S entity) {
    try {
      Map<String, String> map = new HashMap<>();
      map.put(DEFINITION_KEY, entity.getDefinition());

      map.put(
          MODULE_DEFINITIONS_KEY, objectWriter.writeValueAsString(entity.getModuleDefinitions()));

      CuratorFramework client = zkConnection.getClient();
      String path = Paths.build(Paths.STREAMS, entity.getName());
      byte[] binary = ZooKeeperUtils.mapToBytes(map);

      BackgroundPathAndBytesable<?> op =
          client.checkExists().forPath(path) == null ? client.create() : client.setData();

      op.forPath(path, binary);

      logger.trace("Saved stream {} with properties {}", path, map);

      StreamDefinitionRepositoryUtils.saveDependencies(moduleDependencyRepository, entity);
    } catch (Exception e) {
      // NodeExistsException indicates that we tried to create the
      // path just after another thread/jvm successfully created it
      ZooKeeperUtils.wrapAndThrowIgnoring(e, NodeExistsException.class);
    }
    return entity;
  }
  @Override
  public S merge(@Nullable S parentType) {
    if (parentType == null) {
      //noinspection unchecked
      return (S) this;
    }

    super.merge(parentType);

    if (_minimum == null) {
      _minimum = parentType.getMinimum();
    }

    if (_minimumExclusive == null) {
      _minimumExclusive = parentType.getMinimumExclusive();
    }

    if (_maximum == null) {
      _maximum = parentType.getMaximum();
    }

    if (_maximumExclusive == null) {
      _maximumExclusive = parentType.getMaximumExclusive();
    }

    if (_divisibleBy == null) {
      _divisibleBy = parentType.getDivisibleBy();
    }

    //noinspection unchecked
    return (S) this;
  }
Esempio n. 14
0
 @Override
 public void loadAllEntries() {
   final Connection connection = getConnectionpool().getConnection();
   if (connection == null) return;
   Statement query = null;
   try {
     query = connection.createStatement();
     final ResultSet result = query.executeQuery("SELECT * FROM `" + tableName + "` WHERE 1=1");
     while (result.next())
       try {
         final S data = constructor.newInstance(result, columnNames);
         datas.put(data.getName().toLowerCase(), data);
       } catch (final InvocationTargetException e) {
         shortPrintStackTrace(e, e.getCause());
       } catch (final Exception e) {
         e.printStackTrace();
       }
     result.close();
   } catch (final SQLException e) {
   } finally {
     if (query != null)
       try {
         query.close();
       } catch (final Exception e) {
       }
     getConnectionpool().releaseConnection(connection);
   }
 }
  /**
   * Post merge clean up.
   *
   * <p>- Remove the removed items. - Clear the state of all the items (this allow newly overridden
   * items to lose their WRITTEN state) - Set the items that are part of the new merge to be WRITTEN
   * to allow the next merge to be incremental.
   */
  private void postMergeCleanUp() {
    ListMultimap<String, I> itemMap = ArrayListMultimap.create();

    // remove all removed items, and copy the rest in the full map while resetting their state.
    for (S dataSet : mDataSets) {
      ListMultimap<String, I> map = dataSet.getDataMap();

      List<String> keys = Lists.newArrayList(map.keySet());
      for (String key : keys) {
        List<I> list = map.get(key);
        for (int i = 0; i < list.size(); ) {
          I item = list.get(i);
          if (item.isRemoved()) {
            list.remove(i);
          } else {
            //noinspection unchecked
            itemMap.put(key, (I) item.resetStatus());
            i++;
          }
        }
      }
    }

    // for the last items (the one that have been written into the consumer), set their
    // state to WRITTEN
    for (String key : itemMap.keySet()) {
      List<I> itemList = itemMap.get(key);
      itemList.get(itemList.size() - 1).resetStatusToWritten();
    }
  }
    /** Returns null if not supported. */
    private Clob masterClob() throws PersistException {
      Clob masterClob = mMasterClob;

      if (mMasterClobLoaded) {
        return masterClob;
      }

      S master = mMasterStorage.prepare();
      mReplica.copyPrimaryKeyProperties(master);

      try {
        // FIXME: handle missing master with resync
        master.load();

        if (master.isPropertySupported(mClobName)) {
          masterClob = (Clob) master.getPropertyValue(mClobName);
          if (masterClob == null) {
            // FIXME: perform resync, but still throw exception
            throw new PersistNoneException("Master Clob is null: " + mClobName);
          }
        }

        mMasterClob = masterClob;
        mMasterClobLoaded = true;

        return masterClob;
      } catch (FetchException e) {
        throw e.toPersistException();
      }
    }
Esempio n. 17
0
 public static void main(String[] args) {
   T t = new T();
   System.out.println("t.z()=" + t.z() + when("t", t));
   S s = new S();
   System.out.println("s.z()=" + s.z() + when("s", s));
   s = t;
   System.out.println("s.z()=" + s.z() + when("s", s));
 }
Esempio n. 18
0
 /**
  * Transforms all tokens that are represented by this list.
  *
  * @param visitor The visitor to apply to all tokens.
  * @return A list containing the transformed tokens.
  */
 public TokenList<S> accept(
     GenericTypeDescription.Visitor<? extends GenericTypeDescription> visitor) {
   List<S> tokens = new ArrayList<S>(this.tokens.size());
   for (S token : this.tokens) {
     tokens.add(token.accept(visitor));
   }
   return new TokenList<S>(tokens);
 }
Esempio n. 19
0
  public static class ResourceSpec {
    public static IComponentSpec getInstance() {
      return S.getResourceSpec();
    }

    public static final JsResource RESOURCE = S.getJsResource();
    public static final IJsResourceRef REF = S.getJsResourceRef();
  }
 // ----------------------------------------------------------------------
 // ASF: Achivement Scalarization Function
 // I implement here a effcient version of it, which only receives the index
 // of the objective which uses 1.0; the rest will use 0.00001. This is
 // different to the one impelemented in C++
 // ----------------------------------------------------------------------
 private double ASF(S s, int index) {
   double max_ratio = Double.NEGATIVE_INFINITY;
   for (int i = 0; i < s.getNumberOfObjectives(); i++) {
     double weight = (index == i) ? 1.0 : 0.000001;
     max_ratio = Math.max(max_ratio, s.getObjective(i) / weight);
   }
   return max_ratio;
 }
 protected S processNextStart() {
   while (true) {
     final S element = this.starts.next();
     if (this.predicate.evaluate(element.getProperty(this.key), this.value)) {
       return element;
     }
   }
 }
 @JsonApiSave
 public <S extends Project> S save(S entity) {
   if (entity.getId() == null) {
     entity.setId(ID_GENERATOR.getAndIncrement());
   }
   REPOSITORY.put(entity.getId(), entity);
   return entity;
 }
Esempio n. 23
0
 private void validateForPrioritize(S s) {
   if (s.strict()) {
     throw new IllegalArgumentException(s.name() + ": not prioritizable: is strict");
   }
   if (!this.range.contains(s)) {
     throw new IllegalArgumentException(s.name() + ": not contained or is backup");
   }
 }
Esempio n. 24
0
 private boolean containsName(List<S> source, String strategyName) {
   for (S s : source) {
     if (s.name().equals(strategyName)) {
       return true;
     }
   }
   return false;
 }
Esempio n. 25
0
 @Override
 public void save(final S entry) {
   if (entry == null) return;
   super.save(entry);
   entries.put(
       entry.getName(),
       ChatHelper.listingString(DATASEPARATOR, entry.saveToFlatDatabase()) + LINESEPERATOR);
   asyncSaveDatabase();
 }
Esempio n. 26
0
 private <T, S extends ResponseObjectBuilder<T>> T parseMap(
     S builder, Map<String, Reply> response) {
   for (Map.Entry<String, Reply> entry : response.entrySet()) {
     String method = buildSetterName(entry.getKey());
     Class valueType = getObjectClass(entry.getValue());
     builder.set(method, entry.getValue(), valueType);
   }
   return builder.build();
 }
  /** {@inheritDoc} */
  public void write(S session, WriteRequest writeRequest) {
    WriteRequestQueue writeRequestQueue = session.getWriteRequestQueue();

    writeRequestQueue.offer(session, writeRequest);

    if (!session.isWriteSuspended()) {
      this.flush(session);
    }
  }
  protected AbstractDocumentServiceIT(final List<S> indexes) {
    this.indexes = new ArrayList<>(indexes);

    indexesArray = new String[indexes.size()];
    int i = 0;
    for (final S index : indexes) {
      indexesArray[i++] = index.toString();
    }
  }
  public void add(int index, S section) {
    SectionViewer<? extends Section> viewer = section.getViewer();

    try {
      sections.add(index, section);
      section.setViewer(this.viewer);
    } catch (Exception ignored) {
      section.setViewer(viewer);
    }
  }
Esempio n. 30
0
  void addSubscription(S subscription) {

    RegistryItem<String, S> subscriptionItem =
        new RegistryItem<String, S>(
            subscription.getSubscriptionId(),
            subscription,
            subscription.getActualDurationSeconds());

    subscriptionItems.add(subscriptionItem);
  }