Пример #1
0
  public Connection executeBatch() throws Sql2oException {
    long start = System.currentTimeMillis();
    try {
      logExecution();
      PreparedStatement statement = buildPreparedStatement();
      connection.setBatchResult(statement.executeBatch());
      this.currentBatchRecords = 0;
      try {
        connection.setKeys(this.returnGeneratedKeys ? statement.getGeneratedKeys() : null);
        connection.setCanGetKeys(this.returnGeneratedKeys);
      } catch (SQLException sqlex) {
        throw new Sql2oException(
            "Error while trying to fetch generated keys from database. If you are not expecting any generated keys, fix this error by setting the fetchGeneratedKeys parameter in the createQuery() method to 'false'",
            sqlex);
      }
    } catch (Throwable e) {
      this.connection.onException();
      throw new Sql2oException("Error while executing batch operation: " + e.getMessage(), e);
    } finally {
      closeConnectionIfNecessary();
    }

    long end = System.currentTimeMillis();
    logger.debug(
        "total: {} ms; executed batch [{}]",
        new Object[] {end - start, this.getName() == null ? "No name" : this.getName()});

    return this.connection;
  }
  /**
   * Removes an attribute from the servlet context.
   *
   * @param name the name of the attribute to remove.
   */
  public void removeAttribute(String name) {
    Object oldValue;

    synchronized (_attributes) {
      oldValue = _attributes.remove(name);
    }

    // Call any listeners
    if (_applicationAttributeListeners != null) {
      ServletContextAttributeEvent event;

      event = new ServletContextAttributeEvent(this, name, oldValue);

      for (int i = 0; i < _applicationAttributeListeners.size(); i++) {
        ServletContextAttributeListener listener;

        Object objListener = _applicationAttributeListeners.get(i);
        listener = (ServletContextAttributeListener) objListener;

        try {
          listener.attributeRemoved(event);
        } catch (Throwable e) {
          log.log(Level.FINE, e.toString(), e);
        }
      }
    }
  }
Пример #3
0
 /** ** Main client thread loop */
 public void run() {
   this.setRunStatus(THREAD_RUNNING);
   this.threadStarted();
   try {
     this.openSocket();
     this.inputThread = new InputThread(this.socket, this.readTimeout, this.ioThreadLock);
     this.outputThread = new OutputThread(this.socket, this.ioThreadLock);
     this.inputThread.start();
     this.outputThread.start();
     synchronized (this.ioThreadLock) {
       while (this.inputThread.isRunning() || this.outputThread.isRunning()) {
         try {
           this.ioThreadLock.wait();
         } catch (Throwable t) {
         }
       }
     }
   } catch (NoRouteToHostException nrthe) {
     Print.logInfo("Client:ControlThread - Unable to reach " + this.host + ":" + this.port);
     nrthe.printStackTrace();
   } catch (Throwable t) {
     Print.logInfo("Client:ControlThread - " + t);
     t.printStackTrace();
   } finally {
     this.closeSocket();
   }
   this.setRunStatus(THREAD_STOPPED);
   this.threadStopped();
 }
  public final Response executeCommand(
      Object inputPar,
      UserSessionParameters userSessionPars,
      HttpServletRequest request,
      HttpServletResponse response,
      HttpSession userSession,
      ServletContext context) {
    ArrayList vos = (ArrayList) inputPar;
    try {

      ItemDiscounts bean =
          (ItemDiscounts) JAIOBeanFactory.getInstance().getBean(ItemDiscounts.class);
      Response answer =
          bean.deleteItemDiscounts(
              vos,
              ((JAIOUserSessionParameters) userSessionPars).getServerLanguageId(),
              userSessionPars.getUsername());

      return answer;
    } catch (Throwable ex) {
      Logger.error(
          userSessionPars.getUsername(),
          this.getClass().getName(),
          "executeCommand",
          "Error while processing request",
          ex);
      return new ErrorResponse(ex.getMessage());
    }
  }
Пример #5
0
  protected boolean navigationClick(final int status, int time) {
    System.out.println("***** navigationClick *****");
    System.out.println("status=" + Integer.toHexString(status));
    if ((status & (KeypadListener.STATUS_FOUR_WAY | KeypadListener.STATUS_TRACKWHEEL)) == 0) {
      if (status != 0) Logger.log("navClick ignored status " + Integer.toHexString(status));
      return true;
    }

    boolean used = false;

    try {
      if (c_on_navigation_click == 0)
        c_on_navigation_click = CibylCallTable.getAddressByName("rim_on_navigation_click");
    } catch (Throwable t) {
      Logger.log("Exception in navigationClick: " + t);
      t.printStackTrace();

      System.exit(0);
    }

    if (c_on_navigation_click != 0) {
      UIWorker.addUIEvent(c_on_navigation_click, status, time, 0, 0, true);
    }

    return true;
  }
Пример #6
0
 public void run() {
   while (true) {
     TransactionContext context = hazelcast.newTransactionContext();
     context.beginTransaction();
     Set<Integer> setAllInvolvedPMs = new HashSet<Integer>(9);
     try {
       Order order = qOrders.take();
       countOrdersProcessed.incrementAndGet();
       List<Integer> lsAccounts = order.lsAccounts;
       int accountQuantity = order.quantity / lsAccounts.size();
       //                    for (Integer account : lsAccounts) {
       //                        String key = account + "," + order.instrumentId;
       //                        updatePosition(key, order, account, accountQuantity);
       //                    }
       String key = order.portfolioManagerId + "," + order.instrumentId;
       updatePosition(key, order, order.portfolioManagerId, order.quantity);
       context.commitTransaction();
       //                    setAllInvolvedPMs.addAll(lsAccounts);
       setAllInvolvedPMs.add(order.portfolioManagerId);
       for (Integer involvedPM : setAllInvolvedPMs) {
         mapNewOrders.put(involvedPM, order.instrumentId);
       }
     } catch (Throwable t) {
       t.printStackTrace();
       context.rollbackTransaction();
     }
   }
 }
  /** Tests sending a request from a ClientTransaction. */
  public void testSendRequest() {
    try {
      Request invite = createTiInviteRequest(null, null, null);
      RequestEvent receivedRequestEvent = null;
      ClientTransaction tran = null;
      try {
        tran = tiSipProvider.getNewClientTransaction(invite);
        eventCollector.collectRequestEvent(riSipProvider);
        tran.sendRequest();
        waitForMessage();
        receivedRequestEvent = eventCollector.extractCollectedRequestEvent();
        assertNotNull("The sent request was not received by the RI!", receivedRequestEvent);
        assertNotNull(
            "The sent request was not received by the RI!", receivedRequestEvent.getRequest());
      } catch (TransactionUnavailableException exc) {
        throw new TiUnexpectedError(
            "A TransactionUnavailableException was thrown while trying to "
                + "create a new client transaction",
            exc);
      } catch (SipException exc) {
        exc.printStackTrace();
        fail("The SipException was thrown while trying to send the request.");
      } catch (TooManyListenersException exc) {
        throw new TckInternalError(
            "A  TooManyListenersException was thrown while trying "
                + "to add a SipListener to an RI SipProvider",
            exc);
      }
    } catch (Throwable exc) {
      exc.printStackTrace();
      fail(exc.getClass().getName() + ": " + exc.getMessage());
    }

    assertTrue(new Exception().getStackTrace()[0].toString(), true);
  }
Пример #8
0
  public Object intercept(
      Object obj, java.lang.reflect.Method method, Object[] args, MethodProxy proxy)
      throws Throwable {
    printIdent(ident);
    System.out.println(method);
    for (int i = 0; i < args.length; i++) {
      printIdent(ident);
      System.out.print("arg" + (i + 1) + ": ");
      if (obj == args[i]) System.out.println("this");
      else System.out.println(args[i]);
    }
    ident++;

    Object retValFromSuper = null;
    try {
      retValFromSuper = proxy.invokeSuper(obj, args);
      ident--;
    } catch (Throwable t) {
      ident--;
      printIdent(ident);
      System.out.println("throw " + t);
      System.out.println();
      throw t.fillInStackTrace();
    }

    printIdent(ident);
    System.out.print("return ");
    if (obj == retValFromSuper) System.out.println("this");
    else System.out.println(retValFromSuper);

    if (ident == 1) System.out.println();

    return retValFromSuper;
  }
Пример #9
0
 public static void main(String[] args) {
   int errorCount = 0;
   for (int i = 0; i < NTESTS; i++) {
     try {
       System.out.println("Test " + i + ":");
       test(i);
     } catch (Throwable e) {
       errorCount++;
       boolean first = true;
       do {
         System.err.println(first ? "Exception:" : "Caused by:");
         first = false;
         e.printStackTrace();
         Throwable nexte;
         nexte = e.getCause();
         if (nexte == null) { // old JMX
           if (e instanceof MBeanException) nexte = ((MBeanException) e).getTargetException();
         }
         e = nexte;
       } while (e != null);
     }
   }
   if (errorCount == 0) {
     System.out.println("All ModelMBean tests successfuly passed");
     System.out.println("Bye! Bye!");
     // JTReg doesn't like System.exit(0);
     return;
   } else {
     System.err.println("ERROR: " + errorCount + " tests failed");
     System.exit(errorCount);
   }
 }
  /** Clears the idle connections in the pool. */
  @Override
  public void clear() {
    ArrayList<ManagedPoolItem> pool = _connectionPool;

    if (pool == null) return;

    ArrayList<ManagedPoolItem> clearItems = new ArrayList<ManagedPoolItem>();

    synchronized (_connectionPool) {
      _idlePool.clear();

      clearItems.addAll(pool);

      pool.clear();
    }

    for (int i = 0; i < clearItems.size(); i++) {
      ManagedPoolItem poolItem = clearItems.get(i);

      try {
        poolItem.destroy();
      } catch (Throwable e) {
        log.log(Level.WARNING, e.toString(), e);
      }
    }
  }
Пример #11
0
  public void runPreProcess() {

    Authorization auth = new glguerin.authkit.imp.macosx.MacOSXAuthorization();
    Privilege priv = new Privilege("system.privilege.admin");
    // see kAuthorizationRightExecute in the AuthorizationTags.h from Security.framework
    int count = 0;
    boolean succeed = false;
    do {
      try {
        auth.authorize(priv, true);
        succeed = true;
        break;
      } catch (Throwable t) {
        System.out.println("Throwable " + t);
      }
      count++;
    } while (count <= 3);

    if (succeed) {
      String preinstallPath = createTemporaryPreinstallFile();
      if (preinstallPath == null) return;
      String[] progArray = {preinstallPath, System.getProperty("user.name")};
      try {
        Process p = auth.execPrivileged(progArray);
        Thread.sleep(1000L);
      } catch (Throwable t) {
        System.out.println("Throwable " + t);
        t.printStackTrace();
      }
    }
  }
Пример #12
0
  public static final void fireEvent(GenericEvent e, Method m, Vector listeners)
      throws PropertyVetoException {
    Object[] snapshot = null;

    synchronized (listeners) {
      snapshot = new Object[listeners.size()];
      listeners.copyInto(snapshot);
    }

    // leighd 04/14/99 - modified for event debugging
    if (gDebugEvents) Engine.debugLog("Event : " + e.toString());

    Object params[] = new Object[] {e};

    for (int i = 0; i < snapshot.length; i++) {
      if ((e instanceof Consumable) && ((Consumable) e).isConsumed()) {
        // leighd 04/14/99
        // note that we don't catch the consumption of the
        // event until we've passed through the loop again,
        // so we reference i-1
        if (gDebugEvents) Engine.debugLog("Consumed By : " + snapshot[i - 1]);
        return;
      }
      try {
        m.invoke(snapshot[i], params);
      } catch (IllegalAccessException iae) {
        iae.printStackTrace();
      } catch (InvocationTargetException ite) {
        Throwable t = ite.getTargetException();
        if (t instanceof PropertyVetoException) throw ((PropertyVetoException) t);
        else t.printStackTrace();
      }
    }
  }
Пример #13
0
 /**
  * Returns an string array representation of the specified throwable.
  *
  * @param th throwable
  * @return string array
  */
 private static String[] toArray(final Throwable th) {
   final StackTraceElement[] st = th.getStackTrace();
   final String[] obj = new String[st.length + 1];
   obj[0] = th.toString();
   for (int i = 0; i < st.length; i++) obj[i + 1] = "  " + st[i];
   return obj;
 }
 private static FancyDial getInstance(TextureAtlasSprite icon) {
   if (instances.containsKey(icon)) {
     return instances.get(icon);
   }
   ResourceLocation resource = setupInfo.remove(icon);
   instances.put(icon, null);
   if (resource == null) {
     return null;
   }
   PropertiesFile properties = PropertiesFile.get(logger, resource);
   if (properties == null) {
     return null;
   }
   try {
     FancyDial instance = new FancyDial(icon, properties);
     if (instance.ok) {
       instances.put(icon, instance);
       return instance;
     }
     instance.finish();
   } catch (Throwable e) {
     e.printStackTrace();
   }
   return null;
 }
  /** Checks the specific method for consistency. */
  public static void checkMgen(MethodGen mgen) {

    if (skip_checks) return;

    try {
      mgen.toString();
      mgen.getLineNumberTable(mgen.getConstantPool());

      InstructionList ilist = mgen.getInstructionList();
      if (ilist == null || ilist.getStart() == null) return;
      CodeExceptionGen[] exceptionHandlers = mgen.getExceptionHandlers();
      for (CodeExceptionGen gen : exceptionHandlers) {
        assert ilist.contains(gen.getStartPC())
            : "exception handler "
                + gen
                + " has been forgotten in "
                + mgen.getClassName()
                + "."
                + mgen.getName();
      }
      MethodGen nmg = new MethodGen(mgen.getMethod(), mgen.getClassName(), mgen.getConstantPool());
      nmg.getLineNumberTable(mgen.getConstantPool());
    } catch (Throwable t) {
      System.out.printf("failure in method %s.%s\n", mgen.getClassName(), mgen.getName());
      t.printStackTrace();
      throw new Error(t);
    }
  }
Пример #16
0
 /** Sends a single invite request and checks whether it arrives normally at the other end. */
 public void testSendRequest() {
   try {
     // create an empty invite request.
     Request invite = createTiInviteRequest(null, null, null);
     Request receivedRequest = null;
     try {
       // Send using TI and collect using RI
       eventCollector.collectRequestEvent(riSipProvider);
       waitForMessage();
       tiSipProvider.sendRequest(invite);
       waitForMessage();
       RequestEvent receivedRequestEvent = eventCollector.extractCollectedRequestEvent();
       assertNotNull("The sent request was not received at the other end!", receivedRequestEvent);
       assertNotNull(
           "The sent request was not received at the other end!",
           receivedRequestEvent.getRequest());
     } catch (TooManyListenersException ex) {
       throw new TckInternalError(
           "The following exception was thrown while trying to add "
               + "a SipListener to an RI SipProvider",
           ex);
     } catch (SipException ex) {
       ex.printStackTrace();
       fail("A SipException exception was thrown while " + "trying to send a request.");
     }
   } catch (Throwable exc) {
     exc.printStackTrace();
     fail(exc.getClass().getName() + ": " + exc.getMessage());
   }
   assertTrue(new Exception().getStackTrace()[0].toString(), true);
 }
  /** Checks all of the methods in gen for consistency */
  public static void checkMgens(final ClassGen gen) {

    if (skip_checks) return;

    Method[] methods = gen.getMethods();
    for (int i = 0; i < methods.length; i++) {
      Method method = methods[i];
      // System.out.println ("Checking method " + method + " in class "
      // + gen.getClassName());
      checkMgen(new MethodGen(method, gen.getClassName(), gen.getConstantPool()));
    }

    if (false) {
      Throwable t = new Throwable();
      t.fillInStackTrace();
      StackTraceElement[] ste = t.getStackTrace();
      StackTraceElement caller = ste[1];
      System.out.printf(
          "%s.%s (%s line %d)",
          caller.getClassName(),
          caller.getMethodName(),
          caller.getFileName(),
          caller.getLineNumber());
      for (int ii = 2; ii < ste.length; ii++)
        System.out.printf(" [%s line %d]", ste[ii].getFileName(), ste[ii].getLineNumber());
      System.out.printf("\n");
      dump_methods(gen);
    }
  }
Пример #18
0
  static boolean doTest(int N, double __expected) {
    long startTime = System.currentTimeMillis();
    Throwable exception = null;
    RedPaint instance = new RedPaint();
    double __result = 0.0;
    try {
      __result = instance.expectedCells(N);
    } catch (Throwable e) {
      exception = e;
    }
    double elapsed = (System.currentTimeMillis() - startTime) / 1000.0;

    if (exception != null) {
      System.err.println("RUNTIME ERROR!");
      exception.printStackTrace();
      return false;
    } else if (doubleEquals(__expected, __result)) {
      System.err.println("PASSED! " + String.format("(%.2f seconds)", elapsed));
      return true;
    } else {
      System.err.println("FAILED! " + String.format("(%.2f seconds)", elapsed));
      System.err.println("           Expected: " + __expected);
      System.err.println("           Received: " + __result);
      return false;
    }
  }
  public final void showError(@NotNull String message, @NotNull Throwable e) {
    if (getProject().isDisposed()) {
      return;
    }

    while (e instanceof InvocationTargetException) {
      if (e.getCause() == null) {
        break;
      }
      e = e.getCause();
    }

    ErrorInfo info = new ErrorInfo();
    info.myMessage = info.myDisplayMessage = message;
    info.myThrowable = e;
    configureError(info);

    if (info.myShowMessage) {
      showErrorPage(info);
    }
    if (info.myShowLog) {
      LOG.error(
          LogMessageEx.createEvent(
              info.myDisplayMessage,
              info.myMessage + "\n" + ExceptionUtil.getThrowableText(info.myThrowable),
              new Attachment(myFile)));
    } else {
      LOG.info(info.myDisplayMessage + "\n" + info.myMessage, info.myThrowable);
    }
  }
Пример #20
0
  /**
   * Cancel the client selection.
   *
   * @return boolean
   */
  public boolean performCancel() {
    final List<WizardFragment> list = getAllWizardFragments();
    IRunnableWithProgress runnable =
        new IRunnableWithProgress() {
          public void run(IProgressMonitor monitor) throws InvocationTargetException {
            try {
              Iterator<WizardFragment> iterator = list.iterator();
              while (iterator.hasNext())
                executeTask((WizardFragment) iterator.next(), CANCEL, monitor);
            } catch (CoreException ce) {
              throw new InvocationTargetException(ce);
            }
          }
        };

    Throwable t = null;
    try {
      if (getContainer() != null) getContainer().run(true, true, runnable);
      else runnable.run(new NullProgressMonitor());
      return true;
    } catch (InvocationTargetException te) {
      t = te.getCause();
    } catch (Exception e) {
      t = e;
    }
    PHPUiPlugin.log(
        new Status(
            IStatus.ERROR, PHPUiPlugin.ID, 0, "Error cancelling task wizard", t)); // $NON-NLS-1$

    if (t instanceof CoreException) {
      openError(t.getLocalizedMessage(), ((CoreException) t).getStatus());
    } else openError(t.getLocalizedMessage());

    return false;
  }
Пример #21
0
  /**
   * Processes a packet read from either the multicast or unicast socket. Needs to be synchronized
   * because mcast or unicast socket reads can be concurrent
   */
  void handleIncomingUdpPacket(byte[] data) {
    ByteArrayInputStream inp_stream;
    ObjectInputStream inp;
    Message msg = null;
    List l; // used if bundling is enabled

    try {
      // skip the first n bytes (default: 4), this is the version info
      inp_stream = new ByteArrayInputStream(data, VERSION_LENGTH, data.length - VERSION_LENGTH);
      inp = new ObjectInputStream(inp_stream);
      if (enable_bundling) {
        l = new List();
        l.readExternal(inp);
        for (Enumeration en = l.elements(); en.hasMoreElements(); ) {
          msg = (Message) en.nextElement();
          try {
            handleMessage(msg);
          } catch (Throwable t) {
            Trace.error("UDP.handleIncomingUdpPacket()", "failure: " + t.toString());
          }
        }
      } else {
        msg = new Message();
        msg.readExternal(inp);
        handleMessage(msg);
      }
    } catch (Throwable e) {
      Trace.error("UDP.handleIncomingUdpPacket()", "exception=" + Trace.getStackTrace(e));
    }
  }
Пример #22
0
 /**
  * Use reflection to invoke the requested method. Cache the method object to speed up the process
  * will be invoked
  *
  * @param methodName The method to call.
  * @param params The arguments passed to the called method.
  */
 private Object doPrivileged(final String methodName, Object[] params) {
   try {
     return invokeMethod(context, methodName, params);
   } catch (Throwable t) {
     throw new RuntimeException(t.getMessage());
   }
 }
Пример #23
0
  @Override
  public StepExecutionResult executeImplementation(StepExecutionContext context)
      throws MuseExecutionError {
    StepConfiguration config = getConfiguration();
    HashMap<String, Object> values = new HashMap<>();
    for (String name : config.getSourceNames()) {
      MuseValueSource source = getValueSource(config, name, false, context.getProject());
      values.put(name, getValue(source, context, true, Object.class));
    }

    try {
      JavascriptRunner runner = new JavascriptStepRunner();
      runner.evalScript(_origin);

      Object result = runner.invokeFunction(EXECUTE_FUNCTION, context, values);
      if (result instanceof StepExecutionResult) return (StepExecutionResult) result;
      else
        context.raiseEvent(
            new ScriptFailureEvent(
                "Script did not return a StepExecutionResult. Instead, it returned: " + result,
                null)); // TODO do something better than n/a
    } catch (Throwable t) {
      LOG.error("unable to execute script: ", t);
      context.raiseEvent(
          new ScriptFailureEvent(
              "Script threw an exception: " + t.getMessage(),
              t)); // TODO do something better than n/a
    }
    return new BasicStepExecutionResult(StepExecutionStatus.FAILURE);
  }
 /**
  * Method called to create a "default instance" of the bean, currently only needed for obtaining
  * default field values which may be used for suppressing serialization of fields that have "not
  * changed".
  *
  * @param fixAccess If true, method is allowed to fix access to the default constructor (to be
  *     able to call non-public constructor); if false, has to use constructor as is.
  * @return Instance of class represented by this descriptor, if suitable default constructor was
  *     found; null otherwise.
  */
 public Object instantiateBean(boolean fixAccess) {
   AnnotatedConstructor ac = _classInfo.getDefaultConstructor();
   if (ac == null) {
     return null;
   }
   if (fixAccess) {
     ac.fixAccess();
   }
   try {
     return ac.getAnnotated().newInstance();
   } catch (Exception e) {
     Throwable t = e;
     while (t.getCause() != null) {
       t = t.getCause();
     }
     if (t instanceof Error) throw (Error) t;
     if (t instanceof RuntimeException) throw (RuntimeException) t;
     throw new IllegalArgumentException(
         "Failed to instantiate bean of type "
             + _classInfo.getAnnotated().getName()
             + ": ("
             + t.getClass().getName()
             + ") "
             + t.getMessage(),
         t);
   }
 }
Пример #25
0
  private void checkOrientationChanged(int w, int h) {
    // calculate current orientation based on width and height
    int isLandscape = w > h ? 1 : 0;
    if (isLandscape == isLandscapeScreen) {
      return;
    }
    if (!isUIWorkerInit) {
      // verify that UIWorker is initialized
      isUIWorkerInit = UIWorker.isInit();
      if (!isUIWorkerInit) return;
    }
    isLandscapeScreen = isLandscape;
    try {
      if (c_on_orientation_change == 0)
        c_on_orientation_change = CibylCallTable.getAddressByName("rim_on_orientation_change");
    } catch (Throwable t) {
      Logger.log("Exception in checkOrientationChanged: " + t);
      t.printStackTrace();

      System.exit(0);
    }

    if (c_on_orientation_change != 0) {
      UIWorker.addUIEvent(c_on_orientation_change, isLandscape, 0, 0, 0, true);
    }
  }
  public String getAlternativeISBN(String isbnToModify) {

    String isbnToReturn = isbnToModify;

    try {
      if (!this.isNormalizable(isbnToModify)) {
        return isbnToModify;
      }

      String tIsbnToModify = this.normalizeISBN(isbnToModify);

      if (this.isValidISBN10(tIsbnToModify)) {

        // String isbnToReturn1  = this.isbnShortToLong(tIsbnToModify);
        // String isbnTorReturn2 = this.isbnShortToLongVuFind(tIsbnToModify);
        // assert isbnToReturn1.equalsIgnoreCase(isbnTorReturn2);

        isbnToReturn = this.isbnShortToLongVuFind(tIsbnToModify);

      } else if (this.isValidISBN13(tIsbnToModify)) {

        isbnToReturn = this.isbnLongToShort(tIsbnToModify);
      }
    } catch (Throwable ex) {

      // todo: activate logging
      System.out.println(ex.getMessage());
      // isbnToReturn = isbnToModify;

    }

    return isbnToReturn;
  }
Пример #27
0
 public static <T> void assertUnorderedCollection(
     Collection<? extends T> collection, Consumer<T>... checkers) {
   Assert.assertNotNull(collection);
   if (collection.size() != checkers.length) {
     Assert.fail(toString(collection));
   }
   Set<Consumer<T>> checkerSet = new HashSet<Consumer<T>>(Arrays.asList(checkers));
   int i = 0;
   Throwable lastError = null;
   for (final T actual : collection) {
     boolean flag = true;
     for (final Consumer<T> condition : checkerSet) {
       Throwable error = accepts(condition, actual);
       if (error == null) {
         checkerSet.remove(condition);
         flag = false;
         break;
       } else {
         lastError = error;
       }
     }
     if (flag) {
       lastError.printStackTrace();
       Assert.fail("Incorrect element(" + i + "): " + actual);
     }
     i++;
   }
 }
Пример #28
0
  public static void testVariableSubstitution() {
    String val = "hello world", replacement;
    replacement = Util.substituteVariable(val);
    Assert.assertEquals(val, replacement);

    val = "my name is ${user.name}";
    replacement = Util.substituteVariable(val);
    Assert.assertNotSame(val, replacement);
    assert !(val.equals(replacement));

    val = "my name is ${user.name} and ${user.name}";
    replacement = Util.substituteVariable(val);
    assert !(val.equals(replacement));
    Assert.assertEquals(-1, replacement.indexOf("${"));

    val = "my name is ${unknown.var:Bela Ban}";
    replacement = Util.substituteVariable(val);
    assert replacement.contains("Bela Ban");
    Assert.assertEquals(-1, replacement.indexOf("${"));

    val = "my name is ${unknown.var}";
    replacement = Util.substituteVariable(val);
    assert replacement.contains("${");

    val = "here is an invalid ${argument because it doesn't contains a closing bracket";
    try {
      replacement = Util.substituteVariable(val);
      assert false : "should be an IllegalArgumentException";
    } catch (Throwable t) {
      Assert.assertEquals(IllegalArgumentException.class, t.getClass());
    }
  }
Пример #29
0
    public void run() {
      StringBuffer data = new StringBuffer();
      Print.logDebug("Client:InputThread started");

      while (true) {
        data.setLength(0);
        boolean timeout = false;
        try {
          if (this.readTimeout > 0L) {
            this.socket.setSoTimeout((int) this.readTimeout);
          }
          ClientSocketThread.socketReadLine(this.socket, -1, data);
        } catch (InterruptedIOException ee) { // SocketTimeoutException ee) {
          // error("Read interrupted (timeout) ...");
          if (getRunStatus() != THREAD_RUNNING) {
            break;
          }
          timeout = true;
          // continue;
        } catch (Throwable t) {
          Print.logError("Client:InputThread - " + t);
          t.printStackTrace();
          break;
        }
        if (!timeout || (data.length() > 0)) {
          ClientSocketThread.this.handleMessage(data.toString());
        }
      }

      synchronized (this.threadLock) {
        this.isRunning = false;
        Print.logDebug("Client:InputThread stopped");
        this.threadLock.notify();
      }
    }
Пример #30
0
  protected void initializeLogging() {
    if (settings.getGrailsHome() == null) {
      return;
    }

    try {
      Class<?> cls =
          Thread.currentThread()
              .getContextClassLoader()
              .loadClass("org.apache.log4j.PropertyConfigurator");
      Method configure = cls.getMethod("configure", URL.class);
      configure.setAccessible(true);
      File f =
          new File(settings.getGrailsHome() + "/grails-scripts/src/main/scripts/log4j.properties");
      if (f.exists()) {
        configure.invoke(cls, f.toURI().toURL());
      } else {
        f = new File(settings.getGrailsHome() + "/scripts/log4j.properties");
        configure.invoke(cls, f.toURI().toURL());
      }
    } catch (Throwable e) {
      console.verbose(
          "Log4j was not found on the classpath and will not be used for command line logging. Cause "
              + e.getClass().getName()
              + ": "
              + e.getMessage());
    }
  }