コード例 #1
0
 public Object cache(Class clas, K key) throws InstantiationException, IllegalAccessException {
   Object instance;
   if (cacheMap.containsKey(key)) {
     instance = cacheMap.get(key).getInstance(clas);
   } else {
     Cache cache = new Cache();
     instance = cache.getInstance(clas);
     cacheMap.put(key, cache);
   }
   return instance;
 }
コード例 #2
0
ファイル: CacheTest.java プロジェクト: alexrios/memcached
  @SuppressWarnings("static-access")
  @Before
  public void setup() {
    cache = cache.getInstance();
    words = new ArrayList<String>();

    words.add("first");
    words.add("second");
    words.add("third");

    cache.set("words", twoSeconds, words);
  }
コード例 #3
0
 @SuppressWarnings("unchecked")
 public Object getInstance(Line line, Class clas)
     throws InstantiationException, IllegalAccessException {
   Fixture annotation = (Fixture) clas.getAnnotation(Fixture.class);
   Lifespan lifespan = annotation.lifespan();
   Object instance;
   if (lifespan == Lifespan.FULL_SUITE) {
     instance = fullSuiteCache.getInstance(clas);
   } else if (lifespan == Lifespan.FEATURE) {
     Feature feature = line.getScenario().getFeature();
     instance = featureCache.cache(clas, feature);
   } else if (lifespan == Lifespan.SCENARIO) {
     Scenario scenario = line.getScenario();
     instance = scenarioCache.cache(clas, scenario);
   } else {
     LOG.info("create new instance of '{}'", clas);
     instance = clas.newInstance();
   }
   return instance;
 }
コード例 #4
0
ファイル: Constant.java プロジェクト: aphay/Xishicanyin
 public static final String wxGetJsapiTicket() {
   Cache cache = Cache.getInstance();
   long now = new Date().getTime() / 1000;
   if (!cache.exist("wxJsapiTicket")
       || now - (long) cache.get("wxJsapiTicketTime") > Constant.W_EXPIRE_IN) {
     String accessToken = Constant.wxGetAccessToken();
     if (accessToken == null) {
       return null;
     }
     String url = Constant.W_GET_JSAPI_TICKET + "?access_token=" + accessToken + "&type=jsapi";
     String ret = Web.sendGet(url);
     JSONObject json = JSONObject.fromObject(ret);
     if (json.containsKey("errcode") && json.getInt("errcode") != 0) {
       return null;
     }
     cache.set("wxJsapiTicket", json.getString("ticket"));
     cache.set("wxJsapiTicketTime", now);
     Constant.W_EXPIRE_IN = json.getInt("expires_in") - 200;
   }
   return (String) cache.get("wxJsapiTicket");
 }
コード例 #5
0
ファイル: Constant.java プロジェクト: aphay/Xishicanyin
 // 获取微信accessToken和JsapiTicket缓存
 public static final String wxGetAccessToken() {
   Cache cache = Cache.getInstance();
   long now = new Date().getTime() / 1000;
   if (!cache.exist("wxAccessToken")
       || now - (long) cache.get("wxAccessTokenTime") > Constant.W_EXPIRE_IN) {
     String url =
         Constant.W_GET_ACCESS_TOKEN_URL
             + "?grant_type=client_credential&appid="
             + Constant.W_APP_ID
             + "&secret="
             + Constant.W_APP_SECRET;
     String ret = Web.sendGet(url);
     JSONObject json = JSONObject.fromObject(ret);
     if (json.containsKey("errcode") && json.getInt("errcode") != 0) {
       return null;
     }
     cache.set("wxAccessToken", json.getString("access_token"));
     cache.set("wxAccessTokenTime", now);
     Constant.W_EXPIRE_IN = json.getInt("expires_in") - 200;
   }
   return (String) cache.get("wxAccessToken");
 }
コード例 #6
0
/** @author Garrett */
public class AreaOfInterestDAO {

  /////////////////////////////////////////////
  ///   Singleton code

  private static AreaOfInterestDAO instance = null;
  private Cache cache = Cache.getInstance();
  private ConnectionPool cp = ConnectionPool.getInstance();

  /** Creates pkg new instance of SkeletonDAO */
  private AreaOfInterestDAO() {} // constructor

  /** Retrieves the single instance of this class */
  public static synchronized AreaOfInterestDAO getInstance() {
    if (instance == null) {
      instance = new AreaOfInterestDAO();
    }
    return instance;
  } // getInstance

  ////////////////////////////////////////////
  ///   CREATE methods

  /** Creates pkg new pkg in the database */
  public AreaOfInterest create(String id) throws DataException {
    // create new BO, set whether in the DB or not
    AreaOfInterest pkg = new AreaOfInterest(id);
    pkg.setObjectAlreadyInDB(false);

    // put into the cache
    cache.put(pkg.id, pkg);

    // return the new object
    return pkg;
  } // create

  ////////////////////////////////////////////
  ///   READ methods

  /** Reads an existing pkg from the database */
  public AreaOfInterest read(String id) throws DataException {
    // check cache
    AreaOfInterest pkg = (AreaOfInterest) cache.get(id);
    if (pkg != null) {
      return pkg;
    }

    // get pkg jdbc connection
    Connection conn = cp.get();
    try {
      // call the other read method
      pkg = read(id, conn);
    } catch (Exception ex) {
      throw new DataException("can't read AreaOfInterest", ex);
    } finally {
      cp.release(conn);
    }

    // use pkg finally clause to release the connection
    // return the object
    return pkg;
  }

  /** Internal method to read an existing pkg from the database */
  synchronized AreaOfInterest read(String id, Connection conn) throws Exception {
    // check cache
    AreaOfInterest pkg = (AreaOfInterest) cache.get(id);
    if (pkg != null) {
      return pkg;
    }
    // pull from database and populate the object
    PreparedStatement pstmt =
        conn.prepareStatement("SELECT * FROM AreaOfInterest WHERE guid LIKE ?");
    pstmt.setString(1, id);
    ResultSet rs = pstmt.executeQuery();
    pkg = new AreaOfInterest(id);
    if (rs.next()) {
      pkg.setObjectAlreadyInDB(true);
      pkg.setDirty(false);
      pkg.setDescription(rs.getString(2));

    } else {
      throw new DataException("bad AreaOfInterest read");
    }
    pkg.setDirty(false);
    pkg.setObjectAlreadyInDB(true);
    // put in the cache

    cache.put(pkg.getId(), pkg);

    // return the object

    return pkg;
  } // read

  /////////////////////////////////////////////
  ///   UPDATE methods

  /** Saves an existing pkg in the database */
  public void save(AreaOfInterest pkg) throws DataException {

    // get pkg jdbc connection
    Connection conn = cp.get();

    try {
      save(pkg, conn);
      // commit
      conn.commit();
    } catch (Exception e) {
      try {
        conn.rollback();
      } catch (SQLException ex) {
        throw new DataException("can't roll back", e);
      }
      throw new DataException("Problem saving AreaOfInterest", e);
    } finally {
      ConnectionPool.getInstance().release(conn);
    }
  } // update

  /** Internal method to update pkg pkg in the database */
  void save(AreaOfInterest pkg, Connection conn) throws Exception {
    // update the cache
    cache.put(pkg.getId(), pkg);

    // if not dirty, return
    if (!pkg.isDirty() && pkg.isObjectAlreadyInDB()) {
      return;
    }

    // call either update() or insert()
    if (pkg.isObjectAlreadyInDB()) {
      update(pkg, conn);
    } else {
      insert(pkg, conn);
    }
  } // save

  /** Saves an existing pkg to the database */
  private void update(AreaOfInterest pkg, Connection conn) throws Exception {
    PreparedStatement pstmt =
        conn.prepareStatement("UPDATE AreaOfInterest SET description=? WHERE guid LIKE ?");

    pstmt.setString(1, pkg.getDescription());
    pstmt.setString(2, pkg.getId());

    int numUpd = pstmt.executeUpdate();

    if (numUpd == 1) {
      pkg.setObjectAlreadyInDB(true);
      pkg.setDirty(false);
    } else {
      throw new DataException("bad AreaOfInterest update");
    }

    pstmt.close();
  }

  /** Inserts pkg new pkg into the database */
  private void insert(AreaOfInterest pkg, Connection conn) throws Exception {
    PreparedStatement pstmt = conn.prepareStatement("INSERT INTO AreaOfInterest VALUES (?,?)");
    pstmt.setString(1, pkg.getId());
    pstmt.setString(2, pkg.getDescription());

    int numUpd = pstmt.executeUpdate();

    if (numUpd == 1) {
      pkg.setObjectAlreadyInDB(true);
      pkg.setDirty(false);
    } else {
      throw new DataException("bad AreaOfInterest update");
    }
    pstmt.close();
  }

  /////////////////////////////////////////////////
  ///   DELETE methods

  /** We do not support deleting of business objects in this application */
  public void delete(Accounting pkg) throws DataException {
    throw new UnsupportedOperationException(
        "Nice try. The delete function is not supported in this application.");
  }

  ////////////////////////////////////////////////
  ///   SEARCH methods

  // additional search methods go here.  examples are
  // getByName, getByProductCode, etc.

  public java.util.List<AreaOfInterest> getAll() throws DataException {
    // get a jdbc connection

    Connection conn = cp.get();
    LinkedList<AreaOfInterest> areas = new LinkedList();
    PreparedStatement pstmt;
    try {
      pstmt = conn.prepareStatement("SELECT guid FROM areaOfInterest");
      ResultSet rs = pstmt.executeQuery();
      while (rs.next()) {
        String myGuid = rs.getString("guid");
        AreaOfInterest a;
        try {
          a = read(myGuid, conn);
        } catch (Exception ex) {
          throw new DataException("bad read areas");
        }
        areas.add(a);
      }
    } catch (SQLException ex) {
      throw new DataException("bad read all areas");
    } finally {
      cp.release(conn);
    }
    return areas;
  }
}
コード例 #7
0
ファイル: ServerExecEnv.java プロジェクト: kouzant/ID2212
  public ServerExecEnv(String[] args) {
    ArgumentsParser argsParser = new ArgumentsParser(args);
    ExecutorService threadPool = Executors.newCachedThreadPool();

    try {
      CommandLine cmd = argsParser.parseArgs();

      serverId = cmd.getOptionValue("id");
      searchPath = cmd.getOptionValue("searchPath");
      Cache.getInstance().setSearchPath(searchPath);

      // Add server id to log4j lookup map
      MainMapLookup.setMainArguments(new String[] {"id", serverId});

      if (cmd.hasOption("agentPort")) {
        agentPort = Integer.parseInt(cmd.getOptionValue("agentPort"));
      } else {
        agentPort = 8080;
      }

      if (cmd.hasOption("basePort")) {
        basePort = Integer.parseInt(cmd.getOptionValue("basePort"));
      } else {
        basePort = 9090;
      }

      LOG.info(
          "Starting server {} at agent port: {} and base port: {}",
          new Object[] {serverId, agentPort, basePort});

      Cache.getInstance().setAgentPort(agentPort);

      try {
        local = new PeerAgent(InetAddress.getLocalHost(), basePort, agentPort);

        // Discovered peers
        PeerStorage peerStorage = new PeerStorage(local, SAMPLE_SIZE);

        // Start the services
        agentServer = new AgentServer(agentPort, peerStorage);
        baseServer = new BaseServer(basePort, peerStorage);
        threadPool.execute(agentServer);
        threadPool.execute(baseServer);

        discoveryService = new Discovery(local, peerStorage);

        if (cmd.hasOption("bootstrap")) {
          String bootstrap = cmd.getOptionValue("bootstrap");
          Integer bootstrapPort = 9090;
          if (cmd.hasOption("bootstrapPort")) {
            bootstrapPort = Integer.parseInt(cmd.getOptionValue("bootstrapPort"));
          }

          // Initialize discovery service
          discoveryService.connectBootstrap(InetAddress.getByName(bootstrap), bootstrapPort);
        }
      } catch (UnknownHostException ex) {
        LOG.fatal(ex.getMessage());
      }

      threadPool.execute(discoveryService);
    } catch (ParseException ex) {
      LOG.error(ex.getMessage());
    }
  }