Esempio n. 1
0
 /** utility function to dump stack trace and show a semi-meaningful error */
 public static void stacktrace(Throwable e) {
   e.printStackTrace();
   String msg;
   if (state != null) {
     System.out.println(state.currentThread.stackTrace);
     msg = e.toString() + "\n\nstack trace: " + state.currentThread.stackTrace;
   } else {
     msg = e.toString();
   }
   log(msg, LOG_ERROR);
   ui.showError(
       "you hit a bug! please report at openwig.googlecode.com and i'll fix it for you!\n" + msg);
 }
  /** 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);
      }
    }
  }
Esempio n. 3
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;
 }
Esempio n. 4
0
 private Class<?> makeClass(String className, JarFile file, JarEntry entry, URL jarLocation) {
   try {
     definePackage(className, file);
     byte[] jeBytes = getJarEntryBytes(file, entry);
     if (jeBytes == null) {
       System.out.println(
           "Could not get bytes for entry " + entry.getName() + " in jar" + file.getName());
       return null;
     } else {
       // System.out.println("Loading class " + className + " from " + entry.getName() + " in " +
       // file.getName());
       return defineClass(
           className,
           jeBytes,
           0,
           jeBytes.length,
           jarLocation != null ? getProtectionDomain(jarLocation) : pd);
     }
   } catch (Throwable t) {
     System.out.println(
         "Error reading class file "
             + entry.getName()
             + " in jar"
             + file.getName()
             + ": "
             + t.toString());
     return null;
   }
 }
Esempio n. 5
0
  /**
   * Generates a new error message based on the excpetion message.
   *
   * @param message the rror message
   */
  public void generateErrorMessage(MethodDescription mDesc, Throwable ex) {

    ObjectDescription oDesc = getObjectDescription(getObject(mDesc.getObjectID()));
    String methodName = oDesc.getName() + "." + mDesc.getMethodName() + "()";

    System.err.println("Method \"" + methodName + "\" can't be invoked:" + ex.toString());
  }
Esempio n. 6
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));
    }
  }
  /**
   * 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);
        }
      }
    }
  }
  /**
   * Handles a received {@link MBeanServerConnection} invocation
   *
   * @param channel The channel the request was received on
   * @param remoteAddress The remote address of the caller
   * @param buffer THe buffer received
   */
  public static void handleJMXRequest(
      Channel channel, SocketAddress remoteAddress, ChannelBuffer buffer) {
    buffer.resetReaderIndex();
    /* The request write */
    //		cb.writeByte(OpCode.JMX_REQUEST.op());  // 1
    //		cb.writeBytes(domainInfoData);   // domain data
    //		cb.writeInt(reqId);					// 4
    //		cb.writeByte(methodToKey.get(method)); // 1
    //		cb.writeInt(sargs.length);  			// 4
    //		cb.writeBytes(sargs);		           // sargs.length
    Object result = null;
    MBeanServerConnection server = null;
    buffer.skipBytes(1);
    byte domainIndicator = buffer.readByte();
    if (domainIndicator == 0) {
      server = JMXHelper.getHeliosMBeanServer();
    } else {
      byte[] domainBytes = new byte[domainIndicator];
      buffer.readBytes(domainBytes);
      String domain = new String(domainBytes);
      server = JMXHelper.getLocalMBeanServer(true, domain);
      if (server == null) {
        result = new SmallException("Failed to locate MBeanServer for domain [" + domain + "]");
      }
    }
    int reqId = buffer.readInt();
    byte methodId = buffer.readByte();
    if (result == null) {
      int payloadSize = buffer.readInt();
      byte[] payload = new byte[payloadSize];
      buffer.readBytes(payload);
      Object[] params = getInput(payload);
      Method targetMethod = null;
      try {
        targetMethod = keyToMethod.get(methodId);
        if (targetMethod == null) {
          result =
              new SmallException(
                  "Failed to handle MBeanServerConnection invocation because method Op Code ["
                      + methodId
                      + "] was not recognized");
        } else {
          if ("addNotificationListener".equals(targetMethod.getName())
              && !targetMethod.getParameterTypes()[1].equals(ObjectName.class)) {

          } else if ("removeNotificationListener".equals(targetMethod.getName())
              && !targetMethod.getParameterTypes()[1].equals(ObjectName.class)) {

          } else {
            result = targetMethod.invoke(server, params);
          }
        }
      } catch (Throwable t) {
        SimpleLogger.warn("Failed to invoke [", targetMethod, "]", t);
        result = new SmallException(t.toString());
      }
    }
    writeJMXResponse(reqId, methodId, channel, remoteAddress, result);
  }
 private ArithmeticException exception(int ofs, String txt, Throwable thr) {
   return new ArithmeticException(
       txt
           + " at offset "
           + ofs
           + " in expression \""
           + expression
           + "\""
           + " (Cause: "
           + (thr.getMessage() != null ? thr.getMessage() : thr.toString())
           + ")");
 }
Esempio n. 10
0
 private Class<?> makeClass(String className, File classFile) {
   try {
     byte[] jeBytes = getFileBytes(classFile);
     if (jeBytes == null) {
       System.out.println("Could not get bytes for " + classFile);
       return null;
     }
     return defineClass(className, jeBytes, 0, jeBytes.length, pd);
   } catch (Throwable t) {
     System.out.println("Error reading class file " + classFile + ": " + t.toString());
     return null;
   }
 }
Esempio n. 11
0
 /**
  * Returns a more user-friendly error message for the specified exception.
  *
  * @param ex throwable reference
  * @return error message
  */
 public static String message(final Throwable ex) {
   debug(ex);
   if (ex instanceof BindException) return SRV_RUNNING;
   if (ex instanceof LoginException) return ACCESS_DENIED;
   if (ex instanceof ConnectException) return CONNECTION_ERROR;
   if (ex instanceof SocketTimeoutException) return TIMEOUT_EXCEEDED;
   if (ex instanceof SocketException) return CONNECTION_ERROR;
   String msg = ex.getMessage();
   if (msg == null || msg.isEmpty()) msg = ex.toString();
   if (ex instanceof FileNotFoundException) return info(RES_NOT_FOUND_X, msg);
   if (ex instanceof UnknownHostException) return info(UNKNOWN_HOST_X, msg);
   return msg;
 }
Esempio n. 12
0
 static {
   try {
     newLine =
         (String)
             java.security.AccessController.doPrivileged(
                 new sun.security.action.GetPropertyAction("line.separator"));
   } catch (Throwable t) {
     // print an error
     // LogStdStreams initialized in the main application will redirect this to a file.
     System.err.println(
         "Error getting system line separator for Logging will use \\n\n" + t.toString());
   }
 }
Esempio n. 13
0
  public static String getCompressedStackTrace(
      Throwable t, int frames_to_skip, int iMaxLines, boolean showErrString) {
    StringBuffer sbStackTrace = new StringBuffer(showErrString ? (t.toString() + "; ") : "");
    StackTraceElement[] st = t.getStackTrace();

    if (iMaxLines < 0) {
      iMaxLines = st.length + iMaxLines;
      if (iMaxLines < 0) {
        iMaxLines = 1;
      }
    }
    int iMax = Math.min(st.length, iMaxLines + frames_to_skip);
    for (int i = frames_to_skip; i < iMax; i++) {

      if (i > frames_to_skip) {
        sbStackTrace.append(", ");
      }

      String classname = st[i].getClassName();
      String cnShort = classname.substring(classname.lastIndexOf(".") + 1);

      if (Constants.IS_CVS_VERSION) {
        if (STOP_AT_INITIALIZER
            && st[i].getClassName().equals("com.aelitis.azureus.ui.swt.Initializer")) {
          sbStackTrace.append("Initializer");
          break;
        }
        // Formatted so it's clickable in eclipse
        sbStackTrace.append(st[i].getMethodName());
        sbStackTrace.append(" (");
        sbStackTrace.append(classname);
        sbStackTrace.append(".java:");
        sbStackTrace.append(st[i].getLineNumber());
        sbStackTrace.append(')');
      } else {
        sbStackTrace.append("::");
        sbStackTrace.append(st[i].getMethodName());
        sbStackTrace.append("::");
        sbStackTrace.append(st[i].getLineNumber());
      }
    }

    Throwable cause = t.getCause();

    if (cause != null) {
      sbStackTrace.append("\n\tCaused By: ");
      sbStackTrace.append(getCompressedStackTrace(cause, 0));
    }

    return sbStackTrace.toString();
  }
  /** Initialize the connection manager. */
  public Object init(ManagedConnectionFactory mcf) throws ConfigException, ResourceException {
    if (!_lifecycle.toInit()) return null;

    _mcf = mcf;

    if (_name == null) {
      int v = _idGen.incrementAndGet();

      _name = mcf.getClass().getSimpleName() + "-" + v;
    }

    if (_tm == null)
      throw new ConfigException(L.l("the connection manager needs a transaction manager."));

    _idlePool = new IdlePoolSet(_maxIdleCount);

    _connectionTime = MeterService.createActiveTimeMeter("Resin|Database|Connection");
    _idleTime = MeterService.createActiveTimeMeter("Resin|Database|Idle");
    _queryTime = MeterService.createActiveTimeMeter("Resin|Database|Query");

    registerSelf();

    _alarm = new WeakAlarm(this);

    if (!(mcf instanceof ValidatingManagedConnectionFactory)) {
      // never check
      _lastValidCheckTime = Long.MAX_VALUE / 2;
    }

    // recover any resources on startup
    if (_isEnableXA) {
      Subject subject = null;
      ManagedConnection mConn = mcf.createManagedConnection(subject, null);

      try {
        XAResource xa = mConn.getXAResource();

        _tm.recover(xa);
      } catch (NotSupportedException e) {
        log.finer(e.toString());
      } catch (Throwable e) {
        log.log(Level.FINER, e.toString(), e);
      } finally {
        mConn.destroy();
      }
    }

    return mcf.createConnectionFactory(this);
  }
  @NonNls
  private static String message(Throwable e) {
    String message = e.getMessage();
    if (message != null) return message;
    message = e.getLocalizedMessage();
    if (message != null) return message;
    message = e.toString();
    Throwable cause = e.getCause();
    if (cause != null) {
      String causeMessage = message(cause);
      return message + " (cause: " + causeMessage + ")";
    }

    return message;
  }
Esempio n. 16
0
  /**
   * Invokes the constructor belonging to the class named by {@code name} having the given parameter
   * types on the given arguments. Returns {@code null} if the class cannot be found, or the
   * constructor does not exist or cannot be invoked on the given arguments.
   *
   * @param <T> the type to which the constructor belongs
   * @param name the name of the class to which the constructor belongs
   * @param paramTypes the types of the constructor's parameters
   * @param args the arguments on which to invoke the constructor
   * @return the result of the constructor invocation on {@code args}, or null if the constructor
   *     does not exist or could not be invoked
   */
  @SuppressWarnings("unchecked")
  public static <T> T invokeConstructorFor(String name, Class<?>[] paramTypes, Object[] args) {

    // Load the class.
    Class<T> cls = null;
    try {
      cls = (Class<T>) Class.forName(name);
    } catch (Exception e) {
      // no class is found, simply return null
      return null;
    }

    assert cls != null : "reflectively loading " + name + " failed";

    // Invoke the constructor.
    try {
      Constructor<T> ctor = cls.getConstructor(paramTypes);
      return ctor.newInstance(args);
    } catch (Throwable t) {
      if (t instanceof InvocationTargetException) {
        Throwable err = t.getCause();
        String msg;
        if (err instanceof CheckerError) {
          msg = err.getMessage();
        } else {
          msg = err.toString();
        }
        SourceChecker.errorAbort(
            "InvocationTargetException when invoking constructor for class "
                + name
                + "; Underlying cause: "
                + msg,
            t);
      } else {
        SourceChecker.errorAbort(
            "Unexpected "
                + t.getClass().getSimpleName()
                + " for "
                + "class "
                + name
                + " when invoking the constructor; parameter types: "
                + Arrays.toString(paramTypes),
            // + " and args: " + Arrays.toString(args),
            t);
      }
      return null; // dead code
    }
  }
Esempio n. 17
0
 private static void printThrowable(OutputStream stream, Throwable throwable) {
   printBytes(stream, ("Exception " + throwable.toString()).getBytes());
   printNewLine(stream);
   StackTraceElement[] stackTraceElements = throwable.getStackTrace();
   for (int i = stackTraceElements.length - 1; i >= 0; i--) {
     StackTraceElement element = stackTraceElements[i];
     printBytes(stream, element.getFileName().getBytes());
     printBytes(stream, ":".getBytes());
     printBytes(stream, String.valueOf(element.getLineNumber()).getBytes());
     printNewLine(stream);
   }
   if (throwable.getCause() != null) {
     printBytes(stream, "Caused by:\n".getBytes());
     printThrowable(stream, throwable.getCause());
   }
 }
Esempio n. 18
0
 /** Generate the XML report from all the test results */
 protected void generateReports() throws IOException {
   File root_dir = new File(output_dir);
   if (!root_dir.exists()) throw new IOException(root_dir + " not found");
   File[] subdirs =
       root_dir.listFiles(
           new FileFilter() {
             public boolean accept(File f) {
               return f.isDirectory();
             }
           });
   if (subdirs != null) {
     for (File dir : subdirs) {
       try {
         process(dir);
       } catch (Throwable e) {
         error(e.toString());
       }
     }
   }
 }
Esempio n. 19
0
  /**
   * Create mod instances from the enumerated classes
   *
   * @param modsToLoad List of mods to load
   */
  private void loadMods(HashMap<String, Class> modsToLoad) {
    if (modsToLoad == null) {
      logger.info("Mod class discovery failed. Not loading any mods!");
      return;
    }

    logger.info("Discovered " + modsToLoad.size() + " total mod(s)");

    for (Class mod : modsToLoad.values()) {
      try {
        logger.info("Loading mod from " + mod.getName());

        LiteMod newMod = (LiteMod) mod.newInstance();
        mods.add(newMod);

        logger.info(
            "Successfully added mod " + newMod.getName() + " version " + newMod.getVersion());
      } catch (Throwable th) {
        logger.warning(th.toString());
        th.printStackTrace();
      }
    }
  }
  /** Destroys the manager. */
  public void destroy() {
    stop();

    if (!_lifecycle.toDestroy()) return;

    ArrayList<ManagedPoolItem> pool;

    synchronized (_connectionPool) {
      pool = new ArrayList<ManagedPoolItem>(_connectionPool);
      _connectionPool.clear();

      if (_idlePool != null) _idlePool.clear();
    }

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

      try {
        poolItem.destroy();
      } catch (Throwable e) {
        log.log(Level.WARNING, e.toString(), e);
      }
    }
  }
Esempio n. 21
0
  /**
   * Creates a new aspect container.
   *
   * @param aspectClass the aspect class
   */
  private static AspectContainer createAspectContainer(final Class aspectClass) {
    AspectDefinition aspectDefinition = null;

    Set definitions =
        SystemDefinitionContainer.getRegularAndVirtualDefinitionsFor(aspectClass.getClassLoader());
    for (Iterator iterator = definitions.iterator();
        iterator.hasNext() && aspectDefinition == null; ) {
      SystemDefinition systemDefinition = (SystemDefinition) iterator.next();
      for (Iterator iterator1 = systemDefinition.getAspectDefinitions().iterator();
          iterator1.hasNext(); ) {
        AspectDefinition aspectDef = (AspectDefinition) iterator1.next();
        if (aspectClass.getName().replace('/', '.').equals(aspectDef.getClassName())) {
          aspectDefinition = aspectDef;
          break;
        }
      }
    }
    if (aspectDefinition == null) {
      throw new Error("Could not find AspectDefinition for " + aspectClass.getName());
    }

    String containerClassName = aspectDefinition.getContainerClassName();
    try {
      Class containerClass;
      if (containerClassName == null
          || aspectClass.getName().equals(CFlowSystemAspect.CLASS_NAME)) {
        containerClass =
            ContextClassLoader.loadClass(aspectClass.getClassLoader(), DEFAULT_ASPECT_CONTAINER);
      } else {
        containerClass =
            ContextClassLoader.loadClass(aspectClass.getClassLoader(), containerClassName);
      }
      Constructor constructor = containerClass.getConstructor(new Class[] {AspectContext.class});
      final AspectContext aspectContext =
          new AspectContext(
              aspectDefinition.getSystemDefinition().getUuid(),
              aspectClass,
              aspectDefinition.getName(),
              DeploymentModel.getDeploymentModelAsInt(aspectDefinition.getDeploymentModel()),
              aspectDefinition,
              aspectDefinition.getParameters());
      final AspectContainer container =
          (AspectContainer) constructor.newInstance(new Object[] {aspectContext});
      aspectContext.setContainer(container);
      return container;
    } catch (InvocationTargetException e) {
      throw new DefinitionException(e.getTargetException().toString());
    } catch (NoSuchMethodException e) {
      throw new DefinitionException(
          "aspect container does not have a valid constructor ["
              + containerClassName
              + "] need to take an AspectContext instance as its only parameter: "
              + e.toString());
    } catch (Throwable e) {
      StringBuffer cause = new StringBuffer();
      cause.append("could not create aspect container using the implementation specified [");
      cause.append(containerClassName);
      cause.append("] due to: ");
      cause.append(e.toString());
      e.printStackTrace();
      throw new DefinitionException(cause.toString());
    }
  }
Esempio n. 22
0
 /**
  * Format the given LogRecord. Don't allow any errors to be thrown here
  *
  * @param record the log record to be formatted.
  * @return a formatted log record
  */
 @Override
 public synchronized String format(LogRecord record) {
   try {
     StringBuilder sb = new StringBuilder();
     //      StringBuilder text = new StringBuilder();
     if (formatter == null) {
       formatter = new MessageFormat(format);
     }
     //      try {
     //        date.setTime(record.getMillis());
     //        args[0] = date;
     //        formatter.format(args, text, null);
     //      } catch (Throwable t1) {
     //        text.append("Error formatting record date and time" + newLineString() +
     // t1.toString());
     //      }
     //      sb.append(text);
     //      sb.append(" ");
     //      try {
     //        if (record.getSourceClassName() != null) {
     //          sb.append(record.getSourceClassName());
     //        } else {
     //          sb.append(record.getLoggerName());
     //        }
     //      } catch (Throwable t2) {
     //        sb.append("Error getting class name" + newLineString() + t2.toString());
     //      }
     //      try {
     //        if (record.getSourceMethodName() != null) {
     //          sb.append(" ");
     //          sb.append(record.getSourceMethodName());
     //        }
     //      } catch (Throwable t3) {
     //        sb.append("Error getting method name" + newLineString() + t3.toString());
     //      }
     //
     //      sb.append(newLineString());
     //      try {
     //        sb.append(record.getLevel().getLocalizedName());
     //      } catch (Throwable t4) {
     //        sb.append("Error getting localized level name" + newLineString() + t4.toString());
     //      }
     //      sb.append(": ");
     try {
       sb.append(formatMessage(record));
     } catch (Throwable t5) {
       sb.append("Error formatting record message").append(newLineString()).append(t5.toString());
     }
     sb.append(newLineString());
     //      try {
     //        Throwable t = record.getThrown();
     //        if (t != null) {
     //          sb.append(t.toString());
     //        }
     //      } catch (Throwable t6) {
     //        sb.append("Error getting record exception thrown" + newLineString() +
     // t6.toString());
     //      }
     //      sb.append(newLineString());
     return sb.toString();
   } catch (Throwable t) {
     return ("Unexpected error caught while trying to log a record"
         + newLineString()
         + t.toString());
   }
 }
  /**
   * Format the given message to XML.
   *
   * @param record the log record to be formatted.
   * @return a formatted log record
   */
  public String format(LogRecord record0) {
    if (!(record0 instanceof TopLinkLogRecord)) {
      return super.format(record0);
    } else {
      TopLinkLogRecord record = (TopLinkLogRecord) record0;

      StringBuffer sb = new StringBuffer(500);
      sb.append("<record>\n");

      if (record.shouldPrintDate()) {
        sb.append("  <date>");
        appendISO8601(sb, record.getMillis());
        sb.append("</date>\n");

        sb.append("  <millis>");
        sb.append(record.getMillis());
        sb.append("</millis>\n");
      }

      sb.append("  <sequence>");
      sb.append(record.getSequenceNumber());
      sb.append("</sequence>\n");

      String name = record.getLoggerName();
      if (name != null) {
        sb.append("  <logger>");
        escape(sb, name);
        sb.append("</logger>\n");
      }

      sb.append("  <level>");
      escape(sb, record.getLevel().toString());
      sb.append("</level>\n");

      if (record.getSourceClassName() != null) {
        sb.append("  <class>");
        escape(sb, record.getSourceClassName());
        sb.append("</class>\n");
      }

      if (record.getSourceMethodName() != null) {
        sb.append("  <method>");
        escape(sb, record.getSourceMethodName());
        sb.append("</method>\n");
      }

      if (record.getSessionString() != null) {
        sb.append("  <session>");
        sb.append(record.getSessionString());
        sb.append("</session>\n");
      }

      if (record.getConnection() != null) {
        sb.append("  <connection>");
        sb.append(String.valueOf(System.identityHashCode(record.getConnection())));
        sb.append("</connection>\n");
      }

      if (record.shouldPrintThread()) {
        sb.append("  <thread>");
        sb.append(record.getThreadID());
        sb.append("</thread>\n");
      }

      if (record.getMessage() != null) {
        // Format the message string and its accompanying parameters.
        String message = formatMessage(record);
        sb.append("  <message>");
        escape(sb, message);
        sb.append("</message>");
        sb.append("\n");
      }

      // If the message is being localized, output the key, resource
      // bundle name, and params.
      ResourceBundle bundle = record.getResourceBundle();
      try {
        if ((bundle != null) && (bundle.getString(record.getMessage()) != null)) {
          sb.append("  <key>");
          escape(sb, record.getMessage());
          sb.append("</key>\n");
          sb.append("  <catalog>");
          escape(sb, record.getResourceBundleName());
          sb.append("</catalog>\n");
          Object[] parameters = record.getParameters();
          for (int i = 0; i < parameters.length; i++) {
            sb.append("  <param>");
            try {
              escape(sb, parameters[i].toString());
            } catch (Exception ex) {
              sb.append("???");
            }
            sb.append("</param>\n");
          }
        }
      } catch (Exception ex) {
        // The message is not in the catalog.  Drop through.
      }

      if (record.getThrown() != null) {
        // Report on the state of the throwable.
        Throwable th = record.getThrown();
        sb.append("  <exception>\n");
        sb.append("    <message>");
        escape(sb, th.toString());
        sb.append("</message>\n");

        if ((record.getLevel().intValue() == Level.SEVERE.intValue())
            || ((record.getLevel().intValue() <= Level.WARNING.intValue())
                && record.shouldLogExceptionStackTrace())) {
          StackTraceElement[] trace = th.getStackTrace();
          for (int i = 0; i < trace.length; i++) {
            StackTraceElement frame = trace[i];
            sb.append("    <frame>\n");
            sb.append("      <class>");
            escape(sb, frame.getClassName());
            sb.append("</class>\n");
            sb.append("      <method>");
            escape(sb, frame.getMethodName());
            sb.append("</method>\n");
            // Check for a line number.
            if (frame.getLineNumber() >= 0) {
              sb.append("      <line>");
              sb.append(frame.getLineNumber());
              sb.append("</line>\n");
            }
            sb.append("    </frame>\n");
          }
        }

        sb.append("  </exception>\n");
      }

      sb.append("</record>\n");
      return sb.toString();
    }
  }
  public void runSupport() {
    byte[] input_buffer = new byte[request_dg.getLength()];

    System.arraycopy(request_dg.getData(), 0, input_buffer, 0, input_buffer.length);

    int packet_data_length = input_buffer.length;

    String auth_user = null;
    byte[] auth_user_bytes = null;
    byte[] auth_hash = null;

    if (server.isTrackerPasswordEnabled()) {

      // auth detail should be attached to the packet. Auth details are 16
      // bytes

      if (input_buffer.length < 17) {

        Logger.log(
            new LogEvent(
                LOGID,
                LogEvent.LT_WARNING,
                "TRTrackerServerProcessorUDP: " + "packet received but authorisation missing"));

        return;
      }

      packet_data_length -= 16;

      auth_user_bytes = new byte[8];

      auth_hash = new byte[8];

      System.arraycopy(input_buffer, packet_data_length, auth_user_bytes, 0, 8);

      int user_len = 0;

      while (user_len < 8 && auth_user_bytes[user_len] != 0) {

        user_len++;
      }

      auth_user = new String(auth_user_bytes, 0, user_len);

      System.arraycopy(input_buffer, packet_data_length + 8, auth_hash, 0, 8);
    }

    DataInputStream is =
        new DataInputStream(new ByteArrayInputStream(input_buffer, 0, packet_data_length));

    try {
      String client_ip_address = request_dg.getAddress().getHostAddress();

      PRUDPPacketRequest request = PRUDPPacketRequest.deserialiseRequest(null, is);

      Logger.log(
          new LogEvent(
              LOGID, "TRTrackerServerProcessorUDP: packet received: " + request.getString()));

      PRUDPPacket reply = null;
      TRTrackerServerTorrentImpl torrent = null;

      if (auth_user_bytes != null) {

        // user name is irrelevant as we only have one at the moment

        // <parg_home> so <new_packet> = <old_packet> + <user_padded_to_8_bytes> + <hash>
        // <parg_home> where <hash> = first 8 bytes of sha1(<old_packet> + <user_padded_to_8> +
        // sha1(pass))
        // <XTF> Yes

        byte[] sha1_pw = null;

        if (server.hasExternalAuthorisation()) {

          try {
            URL resource = new URL("udp://" + server.getHost() + ":" + server.getPort() + "/");

            sha1_pw = server.performExternalAuthorisation(resource, auth_user);

          } catch (MalformedURLException e) {

            Debug.printStackTrace(e);
          }

          if (sha1_pw == null) {

            Logger.log(
                new LogEvent(
                    LOGID,
                    LogEvent.LT_ERROR,
                    "TRTrackerServerProcessorUDP: auth fails for user '" + auth_user + "'"));

            reply = new PRUDPPacketReplyError(request.getTransactionId(), "Access Denied");
          }
        } else {

          sha1_pw = server.getPassword();
        }

        // if we haven't already failed then check the PW

        if (reply == null) {

          SHA1Hasher hasher = new SHA1Hasher();

          hasher.update(input_buffer, 0, packet_data_length);
          hasher.update(auth_user_bytes);
          hasher.update(sha1_pw);

          byte[] digest = hasher.getDigest();

          for (int i = 0; i < auth_hash.length; i++) {

            if (auth_hash[i] != digest[i]) {

              Logger.log(
                  new LogEvent(
                      LOGID,
                      LogEvent.LT_ERROR,
                      "TRTrackerServerProcessorUDP: auth fails for user '" + auth_user + "'"));

              reply = new PRUDPPacketReplyError(request.getTransactionId(), "Access Denied");

              break;
            }
          }
        }
      }

      int request_type = TRTrackerServerRequest.RT_UNKNOWN;

      if (reply == null) {

        if (server.isEnabled()) {

          try {
            int type = request.getAction();

            if (type == PRUDPPacketTracker.ACT_REQUEST_CONNECT) {

              reply = handleConnect(client_ip_address, request);

            } else if (type == PRUDPPacketTracker.ACT_REQUEST_ANNOUNCE) {

              Object[] x =
                  handleAnnounceAndScrape(
                      client_ip_address, request, TRTrackerServerRequest.RT_ANNOUNCE);

              if (x == null) {

                throw (new Exception("Connection ID mismatch"));
              }

              reply = (PRUDPPacket) x[0];
              torrent = (TRTrackerServerTorrentImpl) x[1];

              request_type = TRTrackerServerRequest.RT_ANNOUNCE;

            } else if (type == PRUDPPacketTracker.ACT_REQUEST_SCRAPE) {

              Object[] x =
                  handleAnnounceAndScrape(
                      client_ip_address, request, TRTrackerServerRequest.RT_SCRAPE);

              if (x == null) {

                throw (new Exception("Connection ID mismatch"));
              }

              reply = (PRUDPPacket) x[0];
              torrent = (TRTrackerServerTorrentImpl) x[1];

              request_type = TRTrackerServerRequest.RT_SCRAPE;

            } else {

              reply = new PRUDPPacketReplyError(request.getTransactionId(), "unsupported action");
            }
          } catch (Throwable e) {

            // e.printStackTrace();

            String error = e.getMessage();

            if (error == null) {

              error = e.toString();
            }

            reply = new PRUDPPacketReplyError(request.getTransactionId(), error);
          }
        } else {

          System.out.println("UDP Tracker: replying 'disabled' to " + client_ip_address);

          reply = new PRUDPPacketReplyError(request.getTransactionId(), "UDP Tracker disabled");
        }
      }

      if (reply != null) {

        InetAddress address = request_dg.getAddress();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        DataOutputStream os = new DataOutputStream(baos);

        reply.serialise(os);

        byte[] output_buffer = baos.toByteArray();

        DatagramPacket reply_packet =
            new DatagramPacket(output_buffer, output_buffer.length, address, request_dg.getPort());

        socket.send(reply_packet);

        server.updateStats(request_type, torrent, input_buffer.length, output_buffer.length);
      }

    } catch (Throwable e) {

      Logger.log(new LogEvent(LOGID, "TRTrackerServerProcessorUDP: processing fails", e));
    } finally {

      try {
        is.close();

      } catch (Throwable e) {

      }
    }
  }
Esempio n. 25
0
  public static MiningResult importFile(InputStream input) throws IOException {
    try {
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      Document doc;
      // NodeList netNodes;
      dbf.setValidating(false);
      dbf.setIgnoringComments(true);
      dbf.setIgnoringElementContentWhitespace(true);
      // dbf.setExpandEntityReferences(false);
      // dbf.setNamespaceAware(false);

      DocumentBuilder db = dbf.newDocumentBuilder();

      db.setEntityResolver(
          new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId) {
              if (systemId.indexOf("ARIS-Export") != -1) {
                return new InputSource("file:" + About.EXTLIBLOCATION() + "ARIS-Export101.dtd");
              } else {
                return null;
              }
            }
          });

      InputSource inpStream = new InputSource(input);
      inpStream.setSystemId("file:" + System.getProperty("user.dir", ""));
      doc = db.parse(inpStream);

      // check if root element is a aml tag
      Message.add("parsing done" + doc, Message.DEBUG);
      if (!(doc.getDocumentElement().getNodeName().equals("AML"))) {
        Message.add("aml tag not found", Message.ERROR);
        throw new Exception("aml tag not found");
      } else {
        Message.add("aml root element found");
      }

      EPCResult result = new EPCResult(null, (EPC) null);
      HashMap ObjDef_LinkId = new HashMap();
      HashMap modelid_net = new HashMap();
      HashMap ObjDef_Name = new HashMap();
      HashMap function_LinkId = new HashMap();
      HashMap ModelId_ModelType = new HashMap();
      traverseAMLforObjectNames(
          ObjDef_Name, doc.getDocumentElement(), ObjDef_LinkId, ModelId_ModelType);
      Iterator findLinkToEpc = ObjDef_LinkId.keySet().iterator();
      while (findLinkToEpc.hasNext()) {
        String currentObjDef = (String) findLinkToEpc.next();
        String Links = (String) ObjDef_LinkId.get(currentObjDef);
        StringTokenizer linkSet = new StringTokenizer(Links);
        String realEpcLink = "";
        while (linkSet.hasMoreTokens()) {
          String currentLink = linkSet.nextToken();
          if (ModelId_ModelType.get(currentLink).equals("MT_EEPC")) {
            realEpcLink = currentLink;
            break;
          }
        }
        if (realEpcLink.equals(" ")) {
          ObjDef_LinkId.remove(currentObjDef);
        } else {
          ObjDef_LinkId.put(currentObjDef, realEpcLink);
        }
      }
      result =
          traverseAML(
              result,
              doc.getDocumentElement(),
              null,
              ObjDef_Name,
              ObjDef_LinkId,
              modelid_net,
              function_LinkId);
      Iterator hierarchicalFunctions = function_LinkId.keySet().iterator();
      while (hierarchicalFunctions.hasNext()) {
        EPCSubstFunction f = (EPCSubstFunction) hierarchicalFunctions.next();
        f.setSubstitutedEPC((EPC) modelid_net.get(function_LinkId.get(f)));
        // Message.add(f.getSubstitutedEPC().getName());
      }

      return result;

    } catch (Throwable x) {
      Message.add(x.toString());
      throw new IOException(x.getMessage());
    }
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, java.io.IOException {
    System.out.println("called eventGroupUpload");
    response.setContentType("application/json");
    response.setHeader("Access-Control-Allow-Origin", "*");
    PrintWriter out = response.getWriter();
    JSONObject obj = new JSONObject();
    ArrayList<String> data = new ArrayList<String>();
    String appId = request.getParameter("appId");
    String name = request.getParameter("name");
    String imgUrl = request.getParameter("imgUrl");
    String about = request.getParameter("about");
    String rules = request.getParameter("rules");
    String contact = request.getParameter("contact");
    String callback = request.getParameter("callback");
    String responseType = request.getParameter("responseType");

    accessToken token = new accessToken();
    String accessToken = request.getParameter("accessToken");
    if ((accessToken != null) && token.get(accessToken)) {
      if (appId == null) {
        data.add("appId");
      }
      if (name == null) {
        data.add("name");
      }
      if (imgUrl == null) {
        data.add("imgUrl");
      }
      if (about == null) {
        data.add("about");
      }
      if (rules == null) {
        data.add("rules");
      }
      if (contact == null) {
        data.add("contact");
      }
      if (data.size() != 0) {
        obj.put("response", "error");
        obj.put("responseString", "Insufficient Data");
        obj.put("data", data);
      } else {

        try {
          beanEventGroupUpload bean = new beanEventGroupUpload();
          bean.setAppId(appId);
          bean.setName(name);
          bean.setImgUrl(imgUrl);
          bean.setAbout(about);
          bean.setRules(rules);
          bean.setContact(contact);
          daoEventGroupUpload dao = new daoEventGroupUpload();
          bean = dao.create(bean);
          if (bean.getValid()) {
            obj.put("response", "success");
            obj.put("responseString", "event uploaded successfully");
          } else {
            System.out.println("I am here");
            obj.put("response", "error");
            obj.put("responseString", bean.getException());
          }
        } catch (Throwable theException) {
          System.out.println("I am here1");
          obj.put("response", "error");
          obj.put("responseString", theException.toString());
        }
      }
    } else {
      obj.put("response", "error");
      obj.put("responseString", "Session expired");
    }
    if (responseType.equals("jsonp")) out.print(callback + "(" + obj + ")");
    else out.print(obj);
  }
Esempio n. 27
0
 protected void recordError(String msg, Throwable t) {
   log.error(msg, t);
   errors.add(msg + ": " + t.toString());
 }
Esempio n. 28
0
  // Information needed to get a single file:
  // BASE_PATH, FILE_ID, TIMESTAMP_START, TIMESTAMP_STOP, SOURCE, FILESYSTEM
  private static Vector<Path> getFile(
      FileSystem fs, Hashtable<String, String> config, dbutil db_util) throws Exception {
    Long latestVersion = latestVersion(config, db_util);

    try {
      config.put("timestamp_start", config.get("timestamp_start"));
      config.put("timestamp_real", latestVersion.toString());
      config.put("timestamp_stop", latestVersion.toString());
    } catch (Exception E) {
      logger.error("Tryign to get file that is impossible to generate: " + getFullPath(config));
      return null;
    }
    if (Integer.parseInt(config.get("timestamp_start"))
        > Integer.parseInt(config.get("timestamp_stop"))) {
      return null;
    }
    logger.debug(
        "Getting DB for timestamp "
            + config.get("timestamp_start")
            + " to "
            + config.get("timestamp_stop"));

    String final_result = getFullPath(config);

    String temp_path_base =
        config.get("local_temp_path")
            + "_"
            + config.get("task_id")
            + "_"
            + config.get("run_id")
            + "/";
    Path newPath = new Path(final_result + "*");
    Vector<Path> ret_path = new Vector<Path>();
    String lockName = lock(final_result.replaceAll("/", "_"));
    if (fs.globStatus(newPath).length != 0) {
      ret_path.add(newPath);
      unlock(lockName);
      config.put("full_file_name", final_result);
      return ret_path;
    } else {
      if (!config.get("source").equals("local")) {
        config.put("temp_path_base", temp_path_base);

        config.put("timestamp_start", config.get("timestamp_start"));
        config.put("timestamp_real", latestVersion.toString());
        config.put("timestamp_stop", latestVersion.toString());

        Class<?> sourceClass =
            Class.forName("org.gestore.plugin.source." + config.get("source") + "Source");
        Method process_data = sourceClass.getMethod("process", Hashtable.class, FileSystem.class);
        Object processor = sourceClass.newInstance();
        Object retVal;
        try {
          retVal = process_data.invoke(processor, config, fs);
        } catch (InvocationTargetException E) {
          Throwable exception = E.getTargetException();
          logger.error("Unable to call method in child class: " + exception.toString());
          exception.printStackTrace(System.out);
          unlock(lockName);
          return null;
        }
        FileStatus[] files = (FileStatus[]) retVal;
        if (files == null) {
          logger.error("Error getting files, no files returned");
          return null;
        }

        for (FileStatus file : files) {
          Path cur_file = file.getPath();
          Path cur_local_path = new Path(temp_path_base + config.get("file_id"));
          String suffix = getSuffix(config.get("file_id"), cur_file.getName());
          cur_local_path = cur_local_path.suffix(suffix);
          Path res_path = new Path(new String(final_result + suffix));
          logger.debug("Moving file" + cur_file.toString() + " to " + res_path.toString());
          if (config.get("copy").equals("true")) {
            fs.moveFromLocalFile(cur_file, res_path);
          } else {
            fs.rename(cur_file, res_path);
          }
        }

        config.put("full_file_name", final_result);
      }
    }
    unlock(lockName);
    return ret_path;
  }
  /** Interrupts script execution. */
  private void interrupted(Context cx, final StackFrame frame, Throwable scriptException) {
    ContextData contextData = frame.contextData();
    boolean eventThreadFlag = callback.isGuiEventThread();
    contextData.eventThreadFlag = eventThreadFlag;

    boolean recursiveEventThreadCall = false;

    interruptedCheck:
    synchronized (eventThreadMonitor) {
      if (eventThreadFlag) {
        if (interruptedContextData != null) {
          recursiveEventThreadCall = true;
          break interruptedCheck;
        }
      } else {
        while (interruptedContextData != null) {
          try {
            eventThreadMonitor.wait();
          } catch (InterruptedException exc) {
            return;
          }
        }
      }
      interruptedContextData = contextData;
    }

    if (recursiveEventThreadCall) {
      // XXX: For now the following is commented out as on Linux
      // too deep recursion of dispatchNextGuiEvent causes GUI lockout.
      // Note: it can make GUI unresponsive if long-running script
      // will be called on GUI thread while processing another interrupt
      if (false) {
        // Run event dispatch until gui sets a flag to exit the initial
        // call to interrupted.
        while (this.returnValue == -1) {
          try {
            callback.dispatchNextGuiEvent();
          } catch (InterruptedException exc) {
          }
        }
      }
      return;
    }

    if (interruptedContextData == null) Kit.codeBug();

    try {
      do {
        int frameCount = contextData.frameCount();
        this.frameIndex = frameCount - 1;

        final String threadTitle = Thread.currentThread().toString();
        final String alertMessage;
        if (scriptException == null) {
          alertMessage = null;
        } else {
          alertMessage = scriptException.toString();
        }

        int returnValue = -1;
        if (!eventThreadFlag) {
          synchronized (monitor) {
            if (insideInterruptLoop) Kit.codeBug();
            this.insideInterruptLoop = true;
            this.evalRequest = null;
            this.returnValue = -1;
            callback.enterInterrupt(frame, threadTitle, alertMessage);
            try {
              for (; ; ) {
                try {
                  monitor.wait();
                } catch (InterruptedException exc) {
                  Thread.currentThread().interrupt();
                  break;
                }
                if (evalRequest != null) {
                  this.evalResult = null;
                  try {
                    evalResult = do_eval(cx, evalFrame, evalRequest);
                  } finally {
                    evalRequest = null;
                    evalFrame = null;
                    monitor.notify();
                  }
                  continue;
                }
                if (this.returnValue != -1) {
                  returnValue = this.returnValue;
                  break;
                }
              }
            } finally {
              insideInterruptLoop = false;
            }
          }
        } else {
          this.returnValue = -1;
          callback.enterInterrupt(frame, threadTitle, alertMessage);
          while (this.returnValue == -1) {
            try {
              callback.dispatchNextGuiEvent();
            } catch (InterruptedException exc) {
            }
          }
          returnValue = this.returnValue;
        }
        switch (returnValue) {
          case STEP_OVER:
            contextData.breakNextLine = true;
            contextData.stopAtFrameDepth = contextData.frameCount();
            break;
          case STEP_INTO:
            contextData.breakNextLine = true;
            contextData.stopAtFrameDepth = -1;
            break;
          case STEP_OUT:
            if (contextData.frameCount() > 1) {
              contextData.breakNextLine = true;
              contextData.stopAtFrameDepth = contextData.frameCount() - 1;
            }
            break;
        }
      } while (false);
    } finally {
      synchronized (eventThreadMonitor) {
        interruptedContextData = null;
        eventThreadMonitor.notifyAll();
      }
    }
  }
Esempio n. 30
0
 private void handleException(Throwable ex) {
   ex.printStackTrace();
   JOptionPane.showMessageDialog(
       this, ex.toString(), ex.getClass().getName(), JOptionPane.ERROR_MESSAGE);
 }