@Override
 public synchronized void write(byte[] ba, int str, int len) {
   try {
     curLength += len;
     if (bytesEndWith(ba, str, len, LINE_SEP)) {
       lineLengths.addLast(new Integer(curLength));
       curLength = 0;
       if (lineLengths.size() > maxLines) {
         textArea.replaceRange(null, 0, lineLengths.removeFirst().intValue());
       }
     }
     for (int xa = 0; xa < 10; xa++) {
       try {
         textArea.append(new String(ba, str, len));
         break;
       } catch (
           Throwable
               thr) { // sometimes throws a java.lang.Error: Interrupted attempt to aquire write
                      // lock
         if (xa == 9) {
           thr.printStackTrace();
         }
       }
     }
     textArea.setCaretPosition(textArea.getText().length());
   } catch (Throwable thr) {
     CharArrayWriter caw = new CharArrayWriter();
     thr.printStackTrace(new PrintWriter(caw, true));
     textArea.append(System.getProperty("line.separator", "\n"));
     textArea.append(caw.toString());
   }
 }
Example #2
0
  public static void printStackTrace(Throwable e, Object context) {
    String header = "DEBUG::";
    header = header + new Date(SystemTime.getCurrentTime()).toString() + "::";
    String className = "?::";
    String methodName = "?::";
    int lineNumber = -1;

    try {
      throw new Exception();
    } catch (Exception f) {
      StackTraceElement[] st = f.getStackTrace();

      for (int i = 1; i < st.length; i++) {
        StackTraceElement first_line = st[i];
        className = first_line.getClassName() + "::";
        methodName = first_line.getMethodName() + "::";
        lineNumber = first_line.getLineNumber();

        // skip stuff generated by the logger

        if (className.indexOf(".logging.") != -1 || className.endsWith(".Debug::")) {

          continue;
        }

        break;
      }
    }

    diagLoggerLogAndOut(header + className + (methodName) + lineNumber + ":", true);

    try {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();

      PrintWriter pw = new PrintWriter(new OutputStreamWriter(baos));

      if (context != null) {
        pw.print("  ");
        pw.println(context);
      }
      pw.print("  ");
      e.printStackTrace(pw);

      pw.close();

      String stack = baos.toString();

      diagLoggerLogAndOut(stack, true);
    } catch (Throwable ignore) {

      e.printStackTrace();
    }
  }
  private void sendProcessingError(Throwable t, ServletResponse response) {

    String stackTrace = getStackTrace(t);

    if (stackTrace != null && !stackTrace.equals("")) {

      try {

        response.setContentType("text/html");
        PrintStream ps = new PrintStream(response.getOutputStream());
        PrintWriter pw = new PrintWriter(ps);
        pw.print("<html>\n<head>\n</head>\n<body>\n"); // NOI18N

        // PENDING! Localize this for next official release
        pw.print("<h1>The resource did not process correctly</h1>\n<pre>\n");
        pw.print(stackTrace);
        pw.print("</pre></body>\n</html>"); // NOI18N
        pw.close();
        ps.close();
        response.getOutputStream().close();
        ;
      } catch (Exception ex) {
      }
    } else {
      try {
        PrintStream ps = new PrintStream(response.getOutputStream());
        t.printStackTrace(ps);
        ps.close();
        response.getOutputStream().close();
        ;
      } catch (Exception ex) {
      }
    }
  }
 private XmlUIElement getXmlUIElementFor(String typeArg) {
   if (typeToClassMappingProp == null) {
     setUpMappingsHM();
   }
   String clsName = (String) typeToClassMappingProp.get(typeArg);
   if ((clsName != null) && !(clsName.equals("*NOTFOUND*")) && !(clsName.equals("*EXCEPTION*"))) {
     try {
       Class cls = Class.forName(clsName);
       return (XmlUIElement) cls.newInstance();
     } catch (Throwable th) {
       typeToClassMappingProp.put(typeArg, "*EXCEPTION*");
       showErrorMessage(
           MessageFormat.format(
               ProvClientUtils.getString(
                   "{0} occurred when trying to get the XmlUIElement for type : {1}"),
               new Object[] {th.getClass().getName(), typeArg}));
       th.printStackTrace();
       return null;
     }
   } else if (clsName == null) {
     typeToClassMappingProp.put(typeArg, "*NOTFOUND*");
     showErrorMessage(
         MessageFormat.format(
             ProvClientUtils.getString(
                 "The type {0} does not have the corresponding XMLUIElement specified in the TypeToUIElementMapping.txt file"),
             new Object[] {typeArg}));
   }
   return null;
 }
 public String toString() {
   try {
     java.io.ByteArrayOutputStream s = new java.io.ByteArrayOutputStream();
     CsvOutputArchive a_ = new CsvOutputArchive(s);
     a_.startRecord(this, "");
     a_.writeString(path, "path");
     {
       a_.startVector(acl, "acl");
       if (acl != null) {
         int len1 = acl.size();
         for (int vidx1 = 0; vidx1 < len1; vidx1++) {
           org.apache.zookeeper.data.ACL e1 = (org.apache.zookeeper.data.ACL) acl.get(vidx1);
           a_.writeRecord(e1, "e1");
         }
       }
       a_.endVector(acl, "acl");
     }
     a_.writeInt(version, "version");
     a_.endRecord(this, "");
     return new String(s.toByteArray(), "UTF-8");
   } catch (Throwable ex) {
     ex.printStackTrace();
   }
   return "ERROR";
 }
Example #6
0
 public void actionPerformed(ActionEvent e) {
   BasePanel panel = frame.basePanel();
   if (panel == null) return;
   TableColumnModel colMod = panel.mainTable.getColumnModel();
   colSetup.setValueAt("" + colMod.getColumn(0).getWidth(), 0, 1);
   for (int i = 1; i < colMod.getColumnCount(); i++) {
     try {
       String name = panel.mainTable.getColumnName(i).toLowerCase();
       int width = colMod.getColumn(i).getWidth();
       // Util.pr(":"+((String)colSetup.getValueAt(i-1, 0)).toLowerCase());
       // Util.pr("-"+name);
       if ((i <= tableRows.size())
           && (((String) colSetup.getValueAt(i, 0)).toLowerCase()).equals(name))
         colSetup.setValueAt("" + width, i, 1);
       else { // Doesn't match; search for a matching col in our table
         for (int j = 0; j < colSetup.getRowCount(); j++) {
           if ((j < tableRows.size())
               && (((String) colSetup.getValueAt(j, 0)).toLowerCase()).equals(name)) {
             colSetup.setValueAt("" + width, j, 1);
             break;
           }
         }
       }
     } catch (Throwable ex) {
       ex.printStackTrace();
     }
     colSetup.revalidate();
     colSetup.repaint();
   }
 }
 public void assertCatch(Throwable ex) {
   try {
     Asserts.assertSame(thrown, ex, "must get the out-of-band exception");
   } catch (Throwable t) {
     ex.printStackTrace();
   }
 }
 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);
   }
 }
    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();
      }
    }
Example #10
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();
      }
    }
  }
 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;
 }
  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();
      }
    }
  }
  private void exportParameters() {
    synchronized (exported_parameters) {
      if (!exported_parameters_dirty) {

        return;
      }

      exported_parameters_dirty = false;

      try {
        TreeMap<String, String> tm = new TreeMap<String, String>();

        Set<String> exported_keys = new HashSet<String>();

        for (String[] entry : exported_parameters.values()) {

          String key = entry[0];
          String value = entry[1];

          exported_keys.add(key);

          if (value != null) {

            tm.put(key, value);
          }
        }

        for (Map.Entry<String, String> entry : imported_parameters.entrySet()) {

          String key = entry.getKey();

          if (!exported_keys.contains(key)) {

            tm.put(key, entry.getValue());
          }
        }

        File parent_dir = new File(SystemProperties.getUserPath());

        File props = new File(parent_dir, "exported_params.properties");

        PrintWriter pw =
            new PrintWriter(new OutputStreamWriter(new FileOutputStream(props), "UTF-8"));

        try {
          for (Map.Entry<String, String> entry : tm.entrySet()) {

            pw.println(entry.getKey() + "=" + entry.getValue());
          }

        } finally {

          pw.close();
        }
      } catch (Throwable e) {

        e.printStackTrace();
      }
    }
  }
Example #14
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;
    }
  }
Example #15
0
 Object createGuiElement(Class cls, EntityPlayer player, World world, int x, int y, int z) {
   try {
     try {
       if (debugGui)
         System.out.printf(
             "BaseMod.createGuiElement: Invoking create method of %s for %s in %s\n",
             cls, player, world);
       return cls.getMethod(
               "create", EntityPlayer.class, World.class, int.class, int.class, int.class)
           .invoke(null, player, world, x, y, z);
     } catch (NoSuchMethodException e) {
       if (debugGui)
         System.out.printf("BaseMod.createGuiElement: Invoking constructor of %s\n", cls);
       return cls.getConstructor(EntityPlayer.class, World.class, int.class, int.class, int.class)
           .newInstance(player, world, x, y, z);
     }
   } catch (Exception e) {
     Throwable cause = e.getCause();
     System.out.printf("BaseMod.createGuiElement: %s: %s\n", e, cause);
     if (cause != null) cause.printStackTrace();
     else e.printStackTrace();
     // throw new RuntimeException(e);
     return null;
   }
 }
Example #16
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 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++;
   }
 }
  private static void assertExceptionOccurred(
      boolean shouldOccur, AbstractExceptionCase exceptionCase, String expectedErrorMsg)
      throws Throwable {
    boolean wasThrown = false;
    try {
      exceptionCase.tryClosure();
    } catch (Throwable e) {
      if (shouldOccur) {
        wasThrown = true;
        final String errorMessage = exceptionCase.getAssertionErrorMessage();
        assertEquals(errorMessage, exceptionCase.getExpectedExceptionClass(), e.getClass());
        if (expectedErrorMsg != null) {
          assertEquals("Compare error messages", expectedErrorMsg, e.getMessage());
        }
      } else if (exceptionCase.getExpectedExceptionClass().equals(e.getClass())) {
        wasThrown = true;

        System.out.println("");
        e.printStackTrace(System.out);

        fail("Exception isn't expected here. Exception message: " + e.getMessage());
      } else {
        throw e;
      }
    } finally {
      if (shouldOccur && !wasThrown) {
        fail(exceptionCase.getAssertionErrorMessage());
      }
    }
  }
Example #19
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;
  }
Example #20
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);
    }
  }
  /** 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);
    }
  }
  /** 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);
  }
Example #23
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();
     }
   }
 }
Example #24
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);
 }
  public static void main(String[] args) {
    try {
      COConfigurationManager.initialise();

      boolean v6 = true;

      // Test connectivity.
      if (true) {
        // System.out.println( "UDP:  " + getSingleton().getExternalIpAddressUDP(null,0,v6));
        // System.out.println( "TCP:  " + getSingleton().getExternalIpAddressTCP(null,0,v6));
        // System.out.println( "HTTP: " + getSingleton().getExternalIpAddressHTTP(v6));
      }

      Map data = constructVersionCheckMessage(VersionCheckClient.REASON_UPDATE_CHECK_START);
      System.out.println("Sending (pre-initialisation):");
      printDataMap(data);
      System.out.println("-----------");

      System.out.println("Receiving (pre-initialisation):");
      printDataMap(
          getSingleton().getVersionCheckInfo(VersionCheckClient.REASON_UPDATE_CHECK_START));
      System.out.println("-----------");

      System.out.println();
      System.out.print("Initialising core... ");

      /**
       * Suppress all of these errors being displayed in the output.
       *
       * <p>These things should be temporary...
       */
      AzureusCoreImpl.SUPPRESS_CLASSLOADER_ERRORS = true;
      DownloadManagerStateImpl.SUPPRESS_FIXUP_ERRORS = true;

      AzureusCore core = AzureusCoreFactory.create();
      core.start();
      System.out.println("done.");
      System.out.println();
      System.out.println("-----------");

      data = constructVersionCheckMessage(VersionCheckClient.REASON_UPDATE_CHECK_START);
      System.out.println("Sending (post-initialisation):");
      printDataMap(data);
      System.out.println("-----------");

      System.out.println("Receiving (post-initialisation):");
      printDataMap(
          getSingleton().getVersionCheckInfo(VersionCheckClient.REASON_UPDATE_CHECK_START));
      System.out.println("-----------");
      System.out.println();

      System.out.print("Shutting down core... ");
      core.stop();
      System.out.println("done.");

    } catch (Throwable e) {
      e.printStackTrace();
    }
  }
 boolean _error(Throwable t) throws MongoException {
   if (_allHosts != null) {
     System.out.println("paired mode, switching master b/c of: " + t);
     t.printStackTrace();
     _pickCurrent();
   }
   return true;
 }
Example #27
0
 /**
  * Utility method that returns a string which contains the stack trace of the given Exception
  * object.
  */
 public static String getStacktraceFromException(Throwable e) {
   ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
   PrintWriter writer = new PrintWriter(byteOut);
   e.printStackTrace(writer);
   writer.close();
   String message = new String(byteOut.toByteArray());
   return message;
 }
  /**
   * Creates an invite request using the Tested Implementation and then tests creating a cancel for
   * the same invite request.
   */
  public void testCreateCancel() {
    try {
      Request invite = createTiInviteRequest(null, null, null);
      ClientTransaction tran = null;
      try {
        tran = tiSipProvider.getNewClientTransaction(invite);
      } catch (TransactionUnavailableException exc) {
        throw new TiUnexpectedError(
            "A TransactionUnavailableException was thrown while trying to "
                + "create a new client transaction",
            exc);
      }
      Request cancel = null;
      try {
        cancel = tran.createCancel();
      } catch (SipException ex) {
        ex.printStackTrace();
        fail("Failed to create cancel request!");
      }
      assertEquals(
          "The created request did not have a CANCEL method.", cancel.getMethod(), Request.CANCEL);
      assertEquals(
          "Request-URIs of the original and the cancel request do not match",
          cancel.getRequestURI(),
          invite.getRequestURI());
      assertEquals(
          "Call-IDs of the original and the cancel request do not match",
          cancel.getHeader(CallIdHeader.NAME),
          invite.getHeader(CallIdHeader.NAME));
      assertEquals(
          "ToHeaders of the original and the cancel request do not match",
          cancel.getHeader(ToHeader.NAME),
          invite.getHeader(ToHeader.NAME));
      assertTrue(
          "The CSeqHeader's sequence number of the original and "
              + "the cancel request do not match",
          ((CSeqHeader) cancel.getHeader(CSeqHeader.NAME)).getSequenceNumber()
              == ((CSeqHeader) invite.getHeader(CSeqHeader.NAME)).getSequenceNumber());
      assertEquals(
          "The CSeqHeader's method of the cancel request was not CANCEL",
          ((CSeqHeader) cancel.getHeader(CSeqHeader.NAME)).getMethod(),
          Request.CANCEL);
      assertTrue(
          "There was no ViaHeader in the cancel request",
          cancel.getHeaders(ViaHeader.NAME).hasNext());
      Iterator cancelVias = cancel.getHeaders(ViaHeader.NAME);
      ViaHeader cancelVia = ((ViaHeader) cancelVias.next());
      ViaHeader inviteVia = ((ViaHeader) invite.getHeaders(ViaHeader.NAME).next());
      assertEquals(
          "ViaHeaders of the original and the cancel request do not match!", cancelVia, inviteVia);
      assertFalse("Cancel request had more than one ViaHeader.", cancelVias.hasNext());
    } catch (Throwable exc) {
      exc.printStackTrace();
      fail(exc.getClass().getName() + ": " + exc.getMessage());
    }

    assertTrue(new Exception().getStackTrace()[0].toString(), true);
  }
  @Override
  public boolean perform(
      AbstractBuild<?, ?> build, Launcher launcher, final BuildListener listener) {
    if (build.getResult().isWorseOrEqualTo(Result.FAILURE)) return false;

    listener.getLogger().println(Messages.TestflightRecorder_InfoUploading());

    try {
      EnvVars vars = build.getEnvironment(listener);

      String workspace = vars.expand("$WORKSPACE");

      List<TestflightUploader.UploadRequest> urList =
          new ArrayList<TestflightUploader.UploadRequest>();

      for (TestflightTeam team : createDefaultPlusAdditionalTeams()) {
        try {
          TestflightUploader.UploadRequest ur = createPartialUploadRequest(team, vars, build);
          urList.add(ur);
        } catch (MisconfiguredJobException mje) {
          listener.getLogger().println(mje.getConfigurationMessage());
          return false;
        }
      }

      for (TestflightUploader.UploadRequest ur : urList) {
        TestflightRemoteRecorder remoteRecorder =
            new TestflightRemoteRecorder(workspace, ur, listener);

        final List<Map> parsedMaps;

        try {
          Object result = launcher.getChannel().call(remoteRecorder);
          parsedMaps = (List<Map>) result;
        } catch (UploadException ue) {
          listener
              .getLogger()
              .println(Messages.TestflightRecorder_IncorrectResponseCode(ue.getStatusCode()));
          listener.getLogger().println(ue.getResponseBody());
          return false;
        }

        if (parsedMaps.size() == 0) {
          listener.getLogger().println(Messages.TestflightRecorder_NoUploadedFile(ur.filePaths));
          return false;
        }
        for (Map parsedMap : parsedMaps) {
          addTestflightLinks(build, listener, parsedMap);
        }
      }
    } catch (Throwable e) {
      listener.getLogger().println(e);
      e.printStackTrace(listener.getLogger());
      return false;
    }

    return true;
  }
Example #30
0
  /**
   * Sends a request from the TI, generates a response at the RI side, sends it back and checks
   * whether it arrives at the TI.
   */
  public void testReceiveResponse() {
    try {
      // 1. Create and send the original request

      Request invite = createTiInviteRequest(null, null, null);
      RequestEvent receivedRequestEvent = null;
      try {
        // Send using TI and collect using RI
        eventCollector.collectRequestEvent(riSipProvider);
        tiSipProvider.sendRequest(invite);
        waitForMessage();
        receivedRequestEvent = eventCollector.extractCollectedRequestEvent();
        if (receivedRequestEvent == null || receivedRequestEvent.getRequest() == null)
          throw new TckInternalError("The sent request was not received by the RI!");
      } catch (TooManyListenersException ex) {
        throw new TckInternalError(
            "A TooManyListenersException was thrown while trying to add "
                + "a SipListener to an RI SipProvider.",
            ex);
      } catch (SipException ex) {
        throw new TiUnexpectedError("The TI failed to send the request!", ex);
      }
      Request receivedRequest = receivedRequestEvent.getRequest();
      // 2. Create and send the response
      Response ok = null;
      try {
        ok = riMessageFactory.createResponse(Response.OK, receivedRequest);
        addStatus(receivedRequest, ok);
      } catch (ParseException ex) {
        throw new TckInternalError("Failed to create an OK response!", ex);
      }
      // Send the response using the RI and collect using TI
      try {
        eventCollector.collectResponseEvent(tiSipProvider);
      } catch (TooManyListenersException ex) {
        throw new TiUnexpectedError("Error while trying to add riSipProvider");
      }
      try {
        riSipProvider.sendResponse(ok);
      } catch (SipException ex) {
        throw new TckInternalError("Could not send back the response", ex);
      }
      waitForMessage();
      ResponseEvent responseEvent = eventCollector.extractCollectedResponseEvent();
      // 3. Now ... do we like what we got?
      assertNotNull("The TI failed to receive the response!", responseEvent);
      assertNotNull("The TI failed to receive the response!", responseEvent.getResponse());
      assertNull(
          "The TI had implicitly created a client transaction! "
              + "Transactions should only be created explicitly using "
              + "the SipProvider.getNewXxxTransaction() method.",
          responseEvent.getClientTransaction());
    } catch (Throwable exc) {
      exc.printStackTrace();
      fail(exc.getClass().getName() + ": " + exc.getMessage());
    }
    assertTrue(new Exception().getStackTrace()[0].toString(), true);
  }