Example #1
0
 /**
  * Registers a collection.
  *
  * @param col Collection to be registered.
  */
 protected void register(final DexIterable<? extends Element> col) {
   if (sessionData.get().collection == null) {
     sessionData.get().collection = new ArrayList<DexIterable<? extends Element>>();
   }
   sessionData.get().collection.add(col);
   // System.out.println("> register " + sess + ":" + col);
 }
  // YYYY = four-digit year
  // MM = two-digit month (01=January, etc.)
  // DD = two-digit day of month (01 through 31)
  // hh = two digits of hour (00 through 23) (am/pm NOT allowed)
  // mm = two digits of minute (00 through 59)
  // ss = two digits of second (00 through 59)
  // s = one or more digits representing a decimal fraction of a second
  // TZD = time zone designator (Z or +hh:mm or -hh:mm)
  public static Date parse(String input) throws java.text.ParseException {

    // NOTE: SimpleDateFormat uses GMT[-+]hh:mm for the TZ which breaks
    // things a bit. Before we go on we have to repair this.

    // this is zero time so we need to add that TZ indicator for
    if (input.endsWith("Z")) {
      input = input.substring(0, input.length() - 1) + "GMT-00:00";
    } else {
      final int inset = 6;

      final String s0 = input.substring(0, input.length() - inset);
      final String s1 = input.substring(input.length() - inset, input.length());

      input = s0 + "GMT" + s1;
    }

    try {
      return normalDf.get().parse(input);
    } catch (ParseException e) {
      // modification by gnip4j. the data collector (at least with
      // facebook feed) sends
      // some date with - in the time part.
      return hackDf.get().parse(input);
    }
  }
 public static void rollbackTransaction() throws Exception {
   if (tranConnection.get() == null) {
     throw new Exception("Can't rollback: this thread isn't currently in a " + "transaction");
   }
   tranConnection.get().rollback();
   tranConnection.set(null);
 }
  // private synchronized boolean makeWithdrawal(int withdrawalAmount) {
  private synchronized void makeWithdrawal(int withdrawalAmount) {

    if (account.getAccountBalance() >= withdrawalAmount) {
      System.out.println("\n+ Account balance is sufficient enough to make a withdrawl...");
      System.out.println(Thread.currentThread().getName() + " is about to make an withdrawal.");

      Random random = new Random();
      int sleepTime = random.nextInt(500) + 510;
      System.out.println("+ Sleeping for - " + sleepTime);
      // Thread.sleep(sleepTime);

      System.out.println(
          "+ Wake-up Call - " + Thread.currentThread().getName() + " just WOKE UP...");

      TOTAL_WITHDRAWN.set(TOTAL_WITHDRAWN.get() + account.withdrawal(10));
      System.out.println(
          "+ Total Withdrawal by "
              + Thread.currentThread().getName()
              + " = "
              + TOTAL_WITHDRAWN.get());
      System.out.println("+ Account Balance = " + account.getAccountBalance() + "\n");

    } else {
      System.out.println(
          "+ WARNING: Sorry "
              + Thread.currentThread().getName()
              + ", insufficient account balance!!!");
    }
  }
  @Override
  protected URL buildUrl(String resource, String query)
      throws URISyntaxException, MalformedURLException {

    int uriport = 0;
    if ("http".equals(proto) && port == 80) {
      // Default port
      uriport = -1;
    } else if ("https".equals(proto) && port == 443) {
      uriport = -1;
    } else {
      uriport = port;
    }

    String host = null;

    if (mode == LBMode.ROUND_ROBIN_THREADS) {
      // Bind thread to a specific host
      if (threadHost.get() == null) {
        threadHost.set(hosts.get((int) (requestCount++ % hosts.size())));
        l4j.info("Thread bound to " + threadHost.get());
      }
      host = threadHost.get();
    } else {
      host = hosts.get((int) (requestCount++ % hosts.size()));
    }

    URI uri = new URI(proto, null, host, uriport, resource, query, null);
    URL u = uri.toURL();
    l4j.debug("URL: " + u);
    return u;
  }
Example #6
0
 /** @see LoopIterationListener#iterationStart(LoopIterationEvent) */
 @Override
 public void iterationStart(LoopIterationEvent event) {
   // Cannot use getThreadContext() as not cloned per thread
   JMeterVariables variables = JMeterContextService.getContext().getVariables();
   long start = getStart();
   long end = getEnd();
   long increment = getIncrement();
   if (!isPerUser()) {
     synchronized (this) {
       if (globalCounter == Long.MIN_VALUE || globalCounter > end) {
         globalCounter = start;
       }
       variables.put(getVarName(), formatNumber(globalCounter));
       globalCounter += increment;
     }
   } else {
     long current = perTheadNumber.get().longValue();
     if (isResetOnThreadGroupIteration()) {
       int iteration = variables.getIteration();
       Long lastIterationNumber = perTheadLastIterationNumber.get();
       if (iteration != lastIterationNumber.longValue()) {
         // reset
         current = getStart();
       }
       perTheadLastIterationNumber.set(Long.valueOf(iteration));
     }
     variables.put(getVarName(), formatNumber(current));
     current += increment;
     if (current > end) {
       current = start;
     }
     perTheadNumber.set(Long.valueOf(current));
   }
 }
 protected SmiMib getMib() {
   // this is a rather ugly hack to mimic JUnit4 @BeforeClass, without having to annotate all test
   // methods:
   if (m_mib.get() == null || m_testClass.get() != getClass()) {
     try {
       SmiParser parser = createParser();
       StopWatch stopWatch = new StopWatch();
       stopWatch.start();
       SmiMib mib = parser.parse();
       stopWatch.stop();
       m_log.info("Parsing time: " + stopWatch.getTotalTimeSeconds() + " s");
       if (mustParseSuccessfully()) {
         assertTrue(((SmiDefaultParser) parser).getProblemEventHandler().isOk());
         assertEquals(
             0,
             ((SmiDefaultParser) parser)
                 .getProblemEventHandler()
                 .getSeverityCount(ProblemSeverity.ERROR));
       }
       m_mib.set(mib);
       m_testClass.set(getClass());
     } catch (Exception e) {
       throw new RuntimeException(e);
     }
   }
   return m_mib.get();
 }
 public static WebDriver getDriver() {
   if (currentRequestedDriver.get() != null) {
     return getWebdriverManager().getWebdriver(currentRequestedDriver.get());
   } else {
     return getWebdriverManager().getWebdriver();
   }
 }
Example #9
0
 public static Locale getLocale() {
   if (curLocale.get() != null) {
     return (Locale) curLocale.get();
   }
   setLocale(new Locale("zh", "CN"));
   return (Locale) curLocale.get();
 }
Example #10
0
 static void dispatchAction(Action action) {
   LockingTransaction trans = LockingTransaction.getRunning();
   if (trans != null) trans.enqueue(action);
   else if (nested.get() != null) {
     nested.set(nested.get().cons(action));
   } else action.agent.enqueue(action);
 }
Example #11
0
  public static SessionMap<Object, Object> getCurrentSession() {

    if (testSessionThreadLocal.get() == null) {
      testSessionThreadLocal.set(new TestSessionVariables());
    }
    return testSessionThreadLocal.get();
  }
Example #12
0
 protected Session getSession() throws LoginException, RepositoryException {
   if (session.get() == null) {
     Session session = repository.login(new SimpleCredentials("admin", "admin".toCharArray()));
     this.session.set(session);
   }
   return session.get();
 }
Example #13
0
 @Override
 void send(String data) {
   try {
     mDataOutputStream.get().write(data);
     mDataOutputStream.get().newLine();
     if (isFlushOutput) {
       mDataOutputStream.get().flush();
     }
     if (debug) {
       System.out.println(data);
     }
   } catch (IOException e) {
     // try to reconnect. if failed then just throw exception
     try {
       Socket socket = new Socket(mCollectorHost, mCollectorPort);
       OutputStream outputStream = socket.getOutputStream();
       mDataOutputStream =
           new ThreadLocal<BufferedWriter>() {
             @Override
             protected BufferedWriter initialValue() {
               return new BufferedWriter(new OutputStreamWriter(outputStream));
             }
           };
     } catch (IOException e1) {
       e1.printStackTrace();
     }
   }
 }
Example #14
0
 /**
  * Unregisters a collection.
  *
  * @param col Collection to be unregistered
  */
 protected void unregister(final DexIterable<? extends Element> col) {
   if (sessionData.get().collection == null) {
     throw new IllegalStateException("Session with no collections");
   }
   sessionData.get().collection.remove(col);
   // System.out.println("< unregister " + sess + ":" + col);
 }
  private void putUpdateStoredBlock(StoredBlock storedBlock, boolean wasUndoable)
      throws SQLException {
    try {
      PreparedStatement s =
          conn.get()
              .prepareStatement(
                  "INSERT INTO headers(hash, chainWork, height, header, wasUndoable)"
                      + " VALUES(?, ?, ?, ?, ?)");
      // We skip the first 4 bytes because (on prodnet) the minimum target has 4 0-bytes
      byte[] hashBytes = new byte[28];
      System.arraycopy(storedBlock.getHeader().getHash().getBytes(), 3, hashBytes, 0, 28);
      s.setBytes(1, hashBytes);
      s.setBytes(2, storedBlock.getChainWork().toByteArray());
      s.setInt(3, storedBlock.getHeight());
      s.setBytes(4, storedBlock.getHeader().unsafeRimbitSerialize());
      s.setBoolean(5, wasUndoable);
      s.executeUpdate();
      s.close();
    } catch (SQLException e) {
      // It is possible we try to add a duplicate StoredBlock if we upgraded
      // In that case, we just update the entry to mark it wasUndoable
      if (!(e.getSQLState().equals(POSTGRES_DUPLICATE_KEY_ERROR_CODE)) || !wasUndoable) throw e;

      PreparedStatement s =
          conn.get().prepareStatement("UPDATE headers SET wasUndoable=? WHERE hash=?");
      s.setBoolean(1, true);
      // We skip the first 4 bytes because (on prodnet) the minimum target has 4 0-bytes
      byte[] hashBytes = new byte[28];
      System.arraycopy(storedBlock.getHeader().getHash().getBytes(), 3, hashBytes, 0, 28);
      s.setBytes(2, hashBytes);
      s.executeUpdate();
      s.close();
    }
  }
 void foo() {
   i.set(new Integer(((Integer) i.get()).intValue() + 1));
   i.set(new Integer(((Integer) i.get()).intValue() + 1));
   i.set(new Integer(((Integer) i.get()).intValue() - 1));
   i.set(new Integer(((Integer) i.get()).intValue() - 1));
   if (((Integer) i.get()).intValue() == 0) ;
 }
  @Override
  public WebDriver getDriver(String hub, Capabilities capabilities) {
    String newKey = createKey(capabilities, hub);
    if (tlDriver.get() == null) {
      createNewDriver(capabilities, hub);

    } else {
      String key = driverToKeyMap.get(tlDriver.get());
      if (key == null) {
        // The driver was dismissed
        createNewDriver(capabilities, hub);

      } else {
        if (!newKey.equals(key)) {
          // A different flavour of WebDriver is required
          dismissDriver(tlDriver.get());
          createNewDriver(capabilities, hub);

        } else {
          // Check the browser is alive
          try {
            tlDriver.get().getCurrentUrl();
          } catch (Throwable t) {
            createNewDriver(capabilities, hub);
          }
        }
      }
    }
    return tlDriver.get();
  }
  @Before
  @Override
  public void setUp() throws Exception {
    System.setProperty("skipStartingCamelContext", "true");
    System.setProperty("registerBlueprintCamelContextEager", "true");

    String symbolicName = getClass().getSimpleName();
    if (isCreateCamelContextPerClass()) {
      // test is per class, so only setup once (the first time)
      boolean first = threadLocalBundleContext.get() == null;
      if (first) {
        threadLocalBundleContext.set(createBundleContext());
      }
      bundleContext = threadLocalBundleContext.get();
    } else {
      bundleContext = createBundleContext();
    }

    super.setUp();

    // start context when we are ready
    log.debug("Staring CamelContext: {}", context.getName());
    context.start();

    // must wait for blueprint container to be published then the namespace parser is complete and
    // we are ready for testing
    log.debug("Waiting for BlueprintContainer to be published with symbolicName: {}", symbolicName);
    getOsgiService(
        BlueprintContainer.class, "(osgi.blueprint.container.symbolicname=" + symbolicName + ")");
  }
Example #19
0
 public static FarmDomain getInstance() {
   if (null == farmDomain || null == farmDomain.get()) {
     farmDomain = new ThreadLocal<FarmDomain>();
     farmDomain.set(new FarmDomain());
   }
   return farmDomain.get();
 }
  @Override
  public TopicUpdateResponse postTopic(String queryUri, Topic topic) {
    try {
      Payload topicPayload = new StringPayload(gson.get().toJson(topic, Topic.class));
      HttpResponse response = httpClient.post(queryUri, topicPayload);
      if (response.statusCode() >= 400) {
        throw new BadResponseException(
            "Error POSTing topic "
                + topic.getTitle()
                + " "
                + topic.getNamespace()
                + " "
                + topic.getValue()
                + " code: "
                + response.statusCode()
                + ", message: "
                + response.statusLine());
      }
      WriteResponseWrapper responseWrapper =
          gson.get().fromJson(response.body(), WriteResponseWrapper.class);

      return new TopicUpdateResponse(
          responseWrapper.getAtlasResponse().getId(), response.header(LOCATION));
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
  public static String formatFileTime(long time, Context context) {

    Date currentDate = new Date(System.currentTimeMillis());
    Date convertableDate = new Date(time);

    String convertedDate = dateInstanceGetter.get().format(convertableDate);
    String convertedTime = timeInstanceGetter.get().format(convertableDate);
    /*if (currentDate.getYear() == convertableDate.getYear()) {
        if (currentDate.getMonth() == convertableDate.getMonth()) {
            if (currentDate.getDay() == convertableDate.getDay()) {
                if (currentDate.getHours() == convertableDate.getHours()) {
                    if (currentDate.getMinutes() == convertableDate.getMinutes()) {
                        return context.getString(R.string.picker_time_minute_ago);
                    }
                    int minutesAgo = currentDate.getMinutes() - convertableDate.getMinutes();
                    return context.getResources().getQuantityString(R.plurals.picker_time_minutes_ago, minutesAgo, minutesAgo);
                    // to do android-i18n-plurals implementation

                } else {
                    if (currentDate.getHours() - 1 == convertableDate.getHours()) {
                        return context.getString(R.string.picker_time_hour_ago);
                    }
                }
                return context.getString(R.string.picker_time_today_at, convertedTime);
            } else {
                if (currentDate.getDay() - 1 == convertableDate.getDay()) {
                    return context.getString(R.string.picker_time_yesterday_at, convertedTime);
                }
            }
        }
        int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NO_YEAR;
        convertedDate = DateUtils.formatDateTime(context, time, flags);
    }*/
    return context.getString(R.string.picker_time_at, convertedDate, convertedTime);
  }
Example #22
0
 @Test
 public void testWebsocketStreamCallbackAsynchronously() {
   this.server =
       vertx.createHttpServer(new HttpServerOptions().setPort(HttpTestBase.DEFAULT_HTTP_PORT));
   AtomicInteger done = new AtomicInteger();
   ServerWebSocketStream stream = server.websocketStream();
   stream.handler(req -> {});
   ThreadLocal<Object> stack = new ThreadLocal<>();
   stack.set(true);
   stream.endHandler(
       v -> {
         assertTrue(Vertx.currentContext().isEventLoopContext());
         assertNull(stack.get());
         if (done.incrementAndGet() == 2) {
           testComplete();
         }
       });
   server.listen(
       ar -> {
         assertTrue(Vertx.currentContext().isEventLoopContext());
         assertNull(stack.get());
         ThreadLocal<Object> stack2 = new ThreadLocal<>();
         stack2.set(true);
         server.close(
             v -> {
               assertTrue(Vertx.currentContext().isEventLoopContext());
               assertNull(stack2.get());
               if (done.incrementAndGet() == 2) {
                 testComplete();
               }
             });
         stack2.set(null);
       });
   await();
 }
Example #23
0
 public static void main(String[] args) {
   if (tl.get() == null) {
     System.out.println("线程变量中没有值");
     tl.set("设置main线程中的变量值");
   }
   System.out.println(tl.get());
 }
Example #24
0
 @Test
 public void testMultipleServerClose() {
   this.server =
       vertx.createHttpServer(new HttpServerOptions().setPort(HttpTestBase.DEFAULT_HTTP_PORT));
   AtomicInteger times = new AtomicInteger();
   // We assume the endHandler and the close completion handler are invoked in the same context
   // task
   ThreadLocal stack = new ThreadLocal();
   stack.set(true);
   server
       .websocketStream()
       .endHandler(
           v -> {
             assertNull(stack.get());
             assertTrue(Vertx.currentContext().isEventLoopContext());
             times.incrementAndGet();
           });
   server.close(
       ar1 -> {
         assertNull(stack.get());
         assertTrue(Vertx.currentContext().isEventLoopContext());
         server.close(
             ar2 -> {
               server.close(
                   ar3 -> {
                     assertEquals(1, times.get());
                     testComplete();
                   });
             });
       });
   await();
 }
Example #25
0
  /**
   * Open a connection for the current thread.
   *
   * @return A valid SQL connection
   */
  @SuppressWarnings("deprecation")
  public Connection getConnection() {
    try {
      // do we have a present JPAContext for this db-config in current thread?
      JPAConfig jpaConfig = JPA.getJPAConfig(dbConfigName);
      if (jpaConfig != null) {
        JPAContext jpaContext = jpaConfig.getJPAContext();
        return ((org.hibernate.ejb.EntityManagerImpl) jpaContext.em()).getSession().connection();
      }

      // do we have a current raw connection bound to thread?
      if (localConnection.get() != null) {
        return localConnection.get();
      }

      // must create connection
      Connection connection = datasource.getConnection();
      localConnection.set(connection);
      return connection;
    } catch (SQLException ex) {
      throw new DatabaseException("Cannot obtain a new connection (" + ex.getMessage() + ")", ex);
    } catch (NullPointerException e) {
      if (datasource == null) {
        throw new DatabaseException(
            "No database found. Check the configuration of your application.", e);
      }
      throw e;
    }
  }
Example #26
0
  public void releaseSchemaWriteLock(final boolean iSave) {
    try {
      if (modificationCounter.get().intValue() == 1) {
        // if it is embedded storage modification of schema is done by internal methods otherwise it
        // is done by
        // by sql commands and we need to reload local replica

        if (iSave)
          if (getDatabase().getStorage().getUnderlying() instanceof OAbstractPaginatedStorage)
            saveInternal();
          else reload();
        else snapshot = new OImmutableSchema(this);

        version++;
      }
    } finally {
      rwSpinLock.releaseWriteLock();
      modificationCounter.get().decrement();
    }

    assert modificationCounter.get().intValue() >= 0;

    if (modificationCounter.get().intValue() == 0
        && getDatabase().getStorage().getUnderlying() instanceof OStorageProxy) {
      getDatabase().getStorage().reload();
    }
  }
 /** get a connection */
 public static Connection getConnection() throws Exception {
   if (tranConnection.get() != null) {
     return tranConnection.get();
   } else {
     return eds.getConnection();
   }
 }
Example #28
0
  @Override
  public Object convert(
      Object existingDestinationFieldValue,
      Object sourceFieldValue,
      Class<?> destinationClass,
      Class<?> sourceClass) {
    try {
      if (currentExchange.get() == null) {
        throw new IllegalStateException("Current exchange has not been set for ExpressionMapper");
      }

      Expression exp;

      // Resolve the language being used for this expression and evaluate
      Exchange exchange = currentExchange.get();
      Language expLang = exchange.getContext().resolveLanguage(getLanguagePart());
      String scheme = getSchemePart();
      if (scheme != null
          && (scheme.equalsIgnoreCase("classpath")
              || scheme.equalsIgnoreCase("file")
              || scheme.equalsIgnoreCase("http"))) {
        String path = getPathPart();
        try {
          exp = expLang.createExpression(resolveScript(scheme + ":" + path));
        } catch (IOException e) {
          throw new IllegalStateException("Expression script specified but not found", e);
        }
      } else {
        exp = expLang.createExpression(getExpressionPart());
      }
      return exp.evaluate(exchange, destinationClass);
    } finally {
      done();
    }
  }
 public static void commitTransaction() throws Exception {
   if (tranConnection.get() == null) {
     throw new Exception("Can't commit: this thread isn't currently in a " + "transaction");
   }
   tranConnection.get().commit();
   tranConnection.set(null);
 }
  @Override
  public Session findSession(String id) throws IOException {
    RedisSession session = null;

    if (null == id) {
      currentSessionIsPersisted.set(false);
      currentSession.set(null);
      currentSessionSerializationMetadata.set(null);
      currentSessionId.set(null);
    } else if (id.equals(currentSessionId.get())) {
      session = currentSession.get();
    } else {
      byte[] data = loadSessionDataFromRedis(id);
      if (data != null) {
        DeserializedSessionContainer container = sessionFromSerializedData(id, data);
        session = container.session;
        currentSession.set(session);
        currentSessionSerializationMetadata.set(container.metadata);
        currentSessionIsPersisted.set(true);
        currentSessionId.set(id);
      } else {
        currentSessionIsPersisted.set(false);
        currentSession.set(null);
        currentSessionSerializationMetadata.set(null);
        currentSessionId.set(null);
      }
    }

    return session;
  }