Exemplo n.º 1
0
  /* Exception reporting policy method.
   * @param e the Throwable to report.
   */
  private void exception(Throwable e) {
    try {
      _persistent = false;
      int error_code = HttpResponse.__500_Internal_Server_Error;

      if (e instanceof HttpException) {
        error_code = ((HttpException) e).getCode();

        if (_request == null) log.warn(e.toString());
        else log.warn(_request.getRequestLine() + " " + e.toString());
        log.debug(LogSupport.EXCEPTION, e);
      } else if (e instanceof EOFException) {
        LogSupport.ignore(log, e);
        return;
      } else {
        _request.setAttribute("javax.servlet.error.exception_type", e.getClass());
        _request.setAttribute("javax.servlet.error.exception", e);

        if (_request == null) log.warn(LogSupport.EXCEPTION, e);
        else log.warn(_request.getRequestLine(), e);
      }

      if (_response != null && !_response.isCommitted()) {
        _response.reset();
        _response.removeField(HttpFields.__TransferEncoding);
        _response.setField(HttpFields.__Connection, HttpFields.__Close);
        _response.sendError(error_code);
      }
    } catch (Exception ex) {
      LogSupport.ignore(log, ex);
    }
  }
Exemplo n.º 2
0
    public Writable call(Class<?> protocol, Writable param, long receivedTime) throws IOException {
      try {
        Invocation call = (Invocation) param;
        if (verbose) log("Call: " + call);

        Method method = protocol.getMethod(call.getMethodName(), call.getParameterClasses());
        method.setAccessible(true);

        int qTime = (int) (System.currentTimeMillis() - receivedTime);
        long startNanoTime = System.nanoTime();
        Object value = method.invoke(instance, call.getParameters());
        long processingMicroTime = (System.nanoTime() - startNanoTime) / 1000;
        if (LOG.isDebugEnabled()) {
          LOG.debug(
              "Served: "
                  + call.getMethodName()
                  + " queueTime (millisec)= "
                  + qTime
                  + " procesingTime (microsec)= "
                  + processingMicroTime);
        }
        rpcMetrics.rpcQueueTime.inc(qTime);
        rpcMetrics.rpcProcessingTime.inc(processingMicroTime);

        MetricsTimeVaryingRate m =
            (MetricsTimeVaryingRate) rpcMetrics.registry.get(call.getMethodName());
        if (m == null) {
          try {
            m = new MetricsTimeVaryingRate(call.getMethodName(), rpcMetrics.registry);
          } catch (IllegalArgumentException iae) {
            // the metrics has been registered; re-fetch the handle
            LOG.debug("Error register " + call.getMethodName(), iae);
            m = (MetricsTimeVaryingRate) rpcMetrics.registry.get(call.getMethodName());
          }
        }
        // record call time in microseconds
        m.inc(processingMicroTime);

        if (verbose) log("Return: " + value);

        return new ObjectWritable(method.getReturnType(), value);

      } catch (InvocationTargetException e) {
        Throwable target = e.getTargetException();
        if (target instanceof IOException) {
          throw (IOException) target;
        } else {
          IOException ioe = new IOException(target.toString());
          ioe.setStackTrace(target.getStackTrace());
          throw ioe;
        }
      } catch (Throwable e) {
        if (!(e instanceof IOException)) {
          LOG.error("Unexpected throwable object ", e);
        }
        IOException ioe = new IOException(e.toString());
        ioe.setStackTrace(e.getStackTrace());
        throw ioe;
      }
    }
  private void reportException(Throwable re, int count, ExporterTask generatorTask) {
    log(
        "An exception occurred while running exporter #" + count + ":" + generatorTask.getName(),
        Project.MSG_ERR);
    log("To get the full stack trace run ant with -verbose", Project.MSG_ERR);

    log(re.toString(), Project.MSG_ERR);
    String ex = new String();
    Throwable cause = re.getCause();
    while (cause != null) {
      ex += cause.toString() + "\n";
      if (cause == cause.getCause()) {
        break; // we reached the top.
      } else {
        cause = cause.getCause();
      }
    }
    if (StringHelper.isNotEmpty(ex)) {
      log(ex, Project.MSG_ERR);
    }

    String newbieMessage = getProbableSolutionOrCause(re);
    if (newbieMessage != null) {
      log(newbieMessage);
    }

    if (re instanceof BuildException) {
      throw (BuildException) re;
    } else {
      throw new BuildException(re, getLocation());
    }
  }
Exemplo n.º 4
0
  /** Parses the services file, looking for PHP services. */
  private void parseServicesModule(ReadStream in)
      throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    String line;

    while ((line = in.readLine()) != null) {
      int p = line.indexOf('#');

      if (p >= 0) {
        line = line.substring(0, p);
      }

      line = line.trim();

      if (line.length() > 0) {
        String className = line;

        try {
          Class cl;
          try {
            cl = Class.forName(className, false, loader);
          } catch (ClassNotFoundException e) {
            throw new ClassNotFoundException(L.l("'{0}' not valid {1}", className, e.toString()));
          }

          introspectPhpModuleClass(cl);
        } catch (Throwable e) {
          log.log(Level.FINE, "Failed loading {0}\n{1}", new Object[] {className, e.toString()});
          log.log(Level.FINE, e.toString(), e);
        }
      }
    }
  }
    public IOReadableWritable call(Class<?> protocol, IOReadableWritable param, long receivedTime)
        throws IOException {

      try {

        final Invocation call = (Invocation) param;

        final Method method = protocol.getMethod(call.getMethodName(), call.getParameterClasses());
        method.setAccessible(true);

        final Object value = method.invoke((Object) instance, (Object[]) call.getParameters());

        return (IOReadableWritable) value;

      } catch (InvocationTargetException e) {

        final Throwable target = e.getTargetException();
        if (target instanceof IOException) {
          throw (IOException) target;
        } else {
          final IOException ioe = new IOException(target.toString());
          ioe.setStackTrace(target.getStackTrace());
          throw ioe;
        }
      } catch (Throwable e) {
        final IOException ioe = new IOException(e.toString());
        ioe.setStackTrace(e.getStackTrace());
        throw ioe;
      }
    }
Exemplo n.º 6
0
  protected void error(Throwable error) {
    LOG.warn("Got exception: " + error.toString(), error);

    if (error.toString().contains("Rescan")) {
      new ErrorDialog(activity, error.toString(), false);
    } else {
      new ErrorDialog(activity, error.toString(), true);
    }
  }
 /**
  * Test for <code>KeyStoreException(Throwable)</code> constructor Assertion: constructs
  * KeyStoreException when <code>cause</code> is not null
  */
 public void testKeyStoreException05() {
   KeyStoreException tE = new KeyStoreException(tCause);
   if (tE.getMessage() != null) {
     String toS = tCause.toString();
     String getM = tE.getMessage();
     assertTrue("getMessage() should contain ".concat(toS), (getM.indexOf(toS) != -1));
   }
   assertNotNull("getCause() must not return null", tE.getCause());
   assertEquals("getCause() must return ".concat(tCause.toString()), tE.getCause(), tCause);
 }
  @Override
  protected void executeInternal(JobExecutionContext context) throws JobExecutionException {

    logger.debug("Inicio del job para la comprobación del time-out en los envíos");

    try {

      ServicioEntidades servicio = LocalizadorServicios.getServicioEntidades();

      // Procesar los ficheros
      List<Entidad> listaEntidades = servicio.obtenerEntidades();

      logger.debug("Numero Entidades recuperadas:" + listaEntidades.size());

      for (Iterator iterator = listaEntidades.iterator(); iterator.hasNext(); ) {
        Entidad entidad = (Entidad) iterator.next();

        try {
          entidad.getCodigoINE();
          logger.debug("entdidad:" + entidad.getIdentificador());
          MultiEntityContextHolder.setEntity(entidad.getIdentificador());
          getServicioIntercambioRegistral().comprobarTimeOutEnvios();
          context.setResult("Ok");

        } catch (Throwable e) {
          logger.error(
              "Error al lanzar la comprobación del time-out en los envíos para la entidad:"
                  + entidad.getIdentificador(),
              e);
          context.setResult(
              "Error al lanzar la comprobación del time-out en los envíos para la entidad:"
                  + entidad.getIdentificador()
                  + e.toString());
          throw new JobExecutionException(
              "Error al lanzar la comprobación del time-out en los envíospara la entidad:"
                  + entidad.getIdentificador(),
              e);
        } finally {
          logger.info(
              "Fin del job para la comprobación del time-out en los envíos para la entidad:"
                  + entidad.getIdentificador());
        }
      }

    } catch (Throwable e) {
      logger.error("Error al lanzar la comprobación del time-out en los envíos", e);
      context.setResult(
          "Error al lanzar la comprobación del time-out en los envíos: " + e.toString());
      throw new JobExecutionException(
          "Error al lanzar la comprobación del time-out en los envíos", e);
    } finally {
      logger.info("Fin del job para la comprobación del time-out en los envíos");
    }
  }
  /**
   * The service method gets the JSP/XTP page and executes it. The request and response objects are
   * converted to Caucho objects so other servlet runners will produce the same results as the
   * Caucho servlet runner.
   */
  public void service(ServletRequest req, ServletResponse res)
      throws ServletException, IOException {
    CauchoRequest request;
    CauchoResponse response;
    ResponseAdapter resAdapt = null;

    if (req instanceof CauchoRequest) request = (CauchoRequest) req;
    else request = RequestAdapter.create((HttpServletRequest) req, _webApp);

    if (res instanceof CauchoResponse) response = (CauchoResponse) res;
    else {
      resAdapt = ResponseAdapter.create((HttpServletResponse) res);
      response = resAdapt;
    }

    Page page = null;

    try {
      page = getPage(request, response);

      if (page == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
      }

      page.service(request, response);
    } catch (JspParseException e) {
      if (e.getErrorPage() != null) forwardErrorPage(request, response, e, e.getErrorPage());
      else throw new ServletException(e);
    } catch (ClientDisconnectException e) {
      throw e;
    } catch (Throwable e) {
      if (page != null
          && page.getErrorPage() != null
          && forwardErrorPage(request, response, e, page.getErrorPage())) {
      } else if (e instanceof IOException) {
        log.log(Level.FINE, e.toString(), e);
        throw (IOException) e;
      } else if (e instanceof ServletException) {
        log.log(Level.FINE, e.toString(), e);
        throw (ServletException) e;
      } else {
        log.log(Level.FINE, e.toString(), e);
        throw new ServletException(e);
      }
    }

    if (resAdapt != null) {
      resAdapt.close();
      ResponseAdapter.free(resAdapt);
    }
  }
Exemplo n.º 10
0
 @Override
 public void e(Throwable throwable, String message, Object... args) {
   if (throwable != null && message != null) {
     message += " : " + throwable.toString();
   }
   if (throwable != null && message == null) {
     message = throwable.toString();
   }
   if (message == null) {
     message = "No message/exception is set";
   }
   log(ERROR, message, args);
 }
Exemplo n.º 11
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);
 }
  public static String getErrorLoadingProject(Throwable ex) {
    StringBuilder errorText = new StringBuilder(1024);
    errorText.append(ex.toString());

    Throwable currentError = ex.getCause();
    while (currentError != null) {
      errorText.append("<br>");
      errorText.append(currentError.toString());
      currentError = currentError.getCause();
    }

    return NbBundle.getMessage(NbStrings.class, "MSG_ErrorLoadingProject", errorText.toString());
  }
Exemplo n.º 13
0
 /**
  * ************************************************************************ Start Java Process
  * Class. instanciate the class implementing the interface ProcessCall. The class can be a
  * Server/Client class (when in Package org compiere.process or org.compiere.model) or a client
  * only class (e.g. in org.compiere.report)
  *
  * @return true if success
  */
 private boolean startProcess() {
   log.fine(m_pi.toString());
   boolean started = false;
   if (DB.isRemoteProcess()) {
     Server server = CConnection.get().getServer();
     try {
       if (server != null) { // 	See ServerBean
         m_pi = server.process(m_wscctx, m_pi);
         log.finest("server => " + m_pi);
         started = true;
       }
     } catch (UndeclaredThrowableException ex) {
       Throwable cause = ex.getCause();
       if (cause != null) {
         if (cause instanceof InvalidClassException)
           log.log(
               Level.SEVERE, "Version Server <> Client: " + cause.toString() + " - " + m_pi, ex);
         else
           log.log(Level.SEVERE, "AppsServer error(1b): " + cause.toString() + " - " + m_pi, ex);
       } else log.log(Level.SEVERE, " AppsServer error(1) - " + m_pi, ex);
       started = false;
     } catch (Exception ex) {
       Throwable cause = ex.getCause();
       if (cause == null) cause = ex;
       log.log(Level.SEVERE, "AppsServer error - " + m_pi, cause);
       started = false;
     }
   }
   //	Run locally
   if (!started && !m_IsServerProcess) {
     ProcessCall myObject = null;
     try {
       Class myClass = Class.forName(m_pi.getClassName());
       myObject = (ProcessCall) myClass.newInstance();
       if (myObject == null) m_pi.setSummary("No Instance for " + m_pi.getClassName(), true);
       else myObject.startProcess(m_wscctx, m_pi, m_trx);
       if (m_trx != null) {
         m_trx.commit();
         m_trx.close();
       }
     } catch (Exception e) {
       if (m_trx != null) {
         m_trx.rollback();
         m_trx.close();
       }
       m_pi.setSummary("Error starting Class " + m_pi.getClassName(), true);
       log.log(Level.SEVERE, m_pi.getClassName(), e);
     }
   }
   return !m_pi.isError();
 } //  startProcess
Exemplo n.º 14
0
 private static boolean isPrestoQueryInvalid(SQLException e) {
   for (Throwable t = e.getCause(); t != null; t = t.getCause()) {
     if (t.toString().contains(".SemanticException:")) {
       return true;
     }
     if (t.toString().contains(".ParsingException:")) {
       return true;
     }
     if (nullToEmpty(t.getMessage()).matches("Function .* not registered")) {
       return true;
     }
   }
   return false;
 }
  /*--------------------------------------------------------------------------*/
  private void extractFromJar(String name, String destination, NativeLibraryClient client)
      throws Exception {
    int bytesRead = 0;
    OutputStream output = null;

    // ----------------------------------------------------
    // open an input stream for the library file
    // ----------------------------------------------------
    InputStream input = openInputStream(name, client);

    // ----------------------------------------------------
    // open an output stream for the temporary file
    // ----------------------------------------------------
    try {
      output = new FileOutputStream(destination);
    } catch (FileNotFoundException exception) {
      input.close();
      throw (new Exception("can't create destination file"));
    } catch (SecurityException exception) {
      input.close();
      throw (new Exception("creation of destination file denied"));
    } catch (Throwable exception) {
      input.close();
      throw (new Exception("unknown problem creating destination file\n" + exception.toString()));
    }

    // ----------------------------------------------------
    // pump the data
    // ----------------------------------------------------
    byte[] buffer = new byte[BLOCK_SIZE];
    try {
      do {
        bytesRead = input.read(buffer);
        if (bytesRead > 0) {
          output.write(buffer, 0, bytesRead);
        }
      } while (bytesRead > 0);
    } catch (Throwable exception) {
      throw (new Exception("error writing to destination file\n" + exception.toString()));
    }

    // ----------------------------------------------------
    // flush the data and close both streams
    // ----------------------------------------------------
    finally {
      input.close();
      output.flush();
      output.close();
    }
  }
 /**
  * Test for <code>SSLException(Throwable)</code> constructor Assertion: constructs SSLException
  * when <code>cause</code> is not null
  */
 public void testSSLException04() {
   SSLException tE = new SSLException(tCause);
   if (tE.getMessage() != null) {
     String toS = tCause.toString();
     String getM = tE.getMessage();
     assertTrue("getMessage() should contain ".concat(toS), (getM.indexOf(toS) != -1));
   }
   // SSLException is subclass of IOException, but IOException has not
   // constructors with Throwable parameters
   if (tE.getCause() != null) {
     //	assertNotNull("getCause() must not return null", tE.getCause());
     assertEquals("getCause() must return ".concat(tCause.toString()), tE.getCause(), tCause);
   }
 }
 private void handleFailure(final Result<? extends MpsatSynthesisChainResult> result) {
   String errorMessage = "Error: MPSat synthesis failed.";
   Throwable genericCause = result.getCause();
   if (genericCause != null) {
     // Exception was thrown somewhere in the chain task run() method (not in any of the subtasks)
     errorMessage += ERROR_CAUSE_PREFIX + genericCause.toString();
   } else {
     MpsatSynthesisChainResult returnValue = result.getReturnValue();
     Result<? extends Object> exportResult =
         (returnValue == null) ? null : returnValue.getExportResult();
     Result<? extends ExternalProcessResult> punfResult =
         (returnValue == null) ? null : returnValue.getPunfResult();
     Result<? extends ExternalProcessResult> mpsatResult =
         (returnValue == null) ? null : returnValue.getMpsatResult();
     if ((exportResult != null) && (exportResult.getOutcome() == Outcome.FAILED)) {
       errorMessage += "\n\nCould not export the model as a .g file.";
       Throwable exportCause = exportResult.getCause();
       if (exportCause != null) {
         errorMessage += ERROR_CAUSE_PREFIX + exportCause.toString();
       }
     } else if ((punfResult != null) && (punfResult.getOutcome() == Outcome.FAILED)) {
       errorMessage += "\n\nPunf could not build the unfolding prefix.";
       Throwable punfCause = punfResult.getCause();
       if (punfCause != null) {
         errorMessage += ERROR_CAUSE_PREFIX + punfCause.toString();
       } else {
         ExternalProcessResult punfReturnValue = punfResult.getReturnValue();
         if (punfReturnValue != null) {
           errorMessage += ERROR_CAUSE_PREFIX + new String(punfReturnValue.getErrors());
         }
       }
     } else if ((mpsatResult != null) && (mpsatResult.getOutcome() == Outcome.FAILED)) {
       errorMessage += "\n\nMPSat did not execute as expected.";
       Throwable mpsatCause = mpsatResult.getCause();
       if (mpsatCause != null) {
         errorMessage += ERROR_CAUSE_PREFIX + mpsatCause.toString();
       } else {
         ExternalProcessResult mpsatReturnValue = mpsatResult.getReturnValue();
         if (mpsatReturnValue != null) {
           String mpsatError = new String(mpsatReturnValue.getErrors());
           errorMessage += ERROR_CAUSE_PREFIX + mpsatError;
         }
       }
     } else {
       errorMessage += "\n\nMPSat chain task returned failure status without further explanation.";
     }
   }
   MainWindow mainWindow = Framework.getInstance().getMainWindow();
   JOptionPane.showMessageDialog(mainWindow, errorMessage, TITLE, JOptionPane.ERROR_MESSAGE);
 }
Exemplo n.º 18
0
  @Override
  public void processMessage(WebSocketMessage webSocketData) {

    final App app = StructrApp.getInstance(getWebSocket().getSecurityContext());
    final String id = webSocketData.getId();
    final Map<String, Object> nodeData = webSocketData.getNodeData();
    final String source = (String) nodeData.get("source");
    final String name = (String) nodeData.get("name");

    // check for ID
    if (id == null) {

      getWebSocket()
          .send(
              MessageBuilder.status().code(422).message("Cannot create widget without id").build(),
              true);

      return;
    }

    // check if parent node with given ID exists
    DOMNode node = getDOMNode(id);

    if (node == null) {

      getWebSocket()
          .send(MessageBuilder.status().code(404).message("Node not found").build(), true);

      return;
    }

    try {

      // convertFromInput
      PropertyMap properties = new PropertyMap();

      properties.put(AbstractNode.type, Widget.class.getSimpleName());
      properties.put(AbstractNode.name, name);
      properties.put(Widget.source, source);

      app.create(Widget.class, properties);

    } catch (Throwable t) {

      logger.log(Level.WARNING, t.toString());

      // send exception
      getWebSocket().send(MessageBuilder.status().code(422).message(t.toString()).build(), true);
    }
  }
Exemplo n.º 19
0
 public void getAppDetails(
     final String appName, final ServiceResponseListener<GetAppDetails.Response> callback) {
   try {
     ServiceClient<GetAppDetails.Request, GetAppDetails.Response> startAppClient =
         node.newServiceClient(resolver.resolve("get_app_details"), "app_manager/GetAppDetails");
     Log.i("AppManager", "Start app service client created");
     GetAppDetails.Request request = new GetAppDetails.Request();
     request.name = appName;
     startAppClient.call(request, callback);
     Log.i("AppManager", "Done call");
   } catch (Throwable ex) {
     Log.i("AppManager", "Get app details failed: " + ex.toString());
     callback.onFailure(new RemoteException(ERROR_STATUS, ex.toString()));
   }
 }
Exemplo n.º 20
0
  public void testConfigure_CustomWrapupMissing() throws Exception {

    JavaActor actor = new JavaActor();
    actor.setName("MultiplyActor");
    MultiplyBean bean = new MultiplyBean();
    actor.setWrappedBean(bean);
    actor.setWrapupMethod("customWrapupMissing");
    actor.setApplicationContext(_context);
    actor.afterPropertiesSet();
    actor.elaborate();

    Exception exception = null;
    try {
      actor.configure();
    } catch (ActorDeclarationException e) {
      exception = e;
    }
    assertNotNull(exception);
    assertEquals(
        "org.restflow.exceptions.ActorDeclarationException: "
            + "Error finding declared method customWrapupMissing "
            + "on bean class org.restflow.actors.TestJavaActor$MultiplyBean "
            + "for actor MultiplyActor",
        exception.toString());
    Throwable cause = exception.getCause();
    assertNotNull(cause);
    assertEquals(
        "java.lang.NoSuchMethodException: "
            + "org.restflow.actors.TestJavaActor$MultiplyBean.customWrapupMissing()",
        cause.toString());
  }
Exemplo n.º 21
0
  protected Set<Class> processJarUrl(URL url, String basepath, Class clazz) throws IOException {
    Set<Class> set = new HashSet<Class>();
    String path = url.getFile().substring(5, url.getFile().indexOf("!"));
    JarFile jar = new JarFile(path);

    for (Enumeration entries = jar.entries(); entries.hasMoreElements(); ) {
      JarEntry entry = (JarEntry) entries.nextElement();
      if (entry.getName().startsWith(basepath) && entry.getName().endsWith(".class")) {
        try {
          String name = entry.getName();
          // Ignore anonymous
          // TODO RM what about the other anonymous classes like $2, $3 ?
          if (name.contains("$1")) {
            continue;
          }
          URL classURL = classLoader.getResource(name);
          ClassReader reader = new ClassReader(classURL.openStream());
          ClassScanner visitor = getScanner(clazz);
          reader.accept(visitor, 0);
          if (visitor.isMatch()) {
            Class c = loadClass(visitor.getClassName());
            if (c != null) {
              set.add(c);
            }
          }
        } catch (Exception e) {
          if (logger.isDebugEnabled()) {
            Throwable t = ExceptionHelper.getRootException(e);
            logger.debug(String.format("%s: caused by: %s", e.toString(), t.toString()));
          }
        }
      }
    }
    return set;
  }
  protected Object reifyCall(
      String className,
      String methodName,
      Class<?>[] parameterTypes,
      Object[] effectiveParameters,
      short priority) {
    try {
      return this.proxy.reify(
          MethodCall.getComponentMethodCall(
              Class.forName(className).getDeclaredMethod(methodName, parameterTypes),
              effectiveParameters,
              null,
              (String) null,
              null,
              priority));

      // functional interface name is null
    } catch (NoSuchMethodException e) {
      throw new ProActiveRuntimeException(e.toString());
    } catch (ClassNotFoundException e) {
      throw new ProActiveRuntimeException(e.toString());
    } catch (Throwable e) {
      throw new ProActiveRuntimeException(e.toString());
    }
  }
Exemplo n.º 23
0
  public static void load() {
    libraryNames = PlatformDependencies.currentLibraryNames;
    libraryExtensions = PlatformDependencies.currentLibraryExtension;
    String dir = "";
    try {
      dir = PropertiesBean.getProperty(PropertiesNames.RESOURCES_DIR /*"dirs.resources"*/);
    } catch (NoSuchPropertyException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      logger.warning(e.toString());
      dir = ".\\resources";
    }

    for (int i = 0; i < libraryNames.length; ++i) {
      String latestLib = getLatestFileName(dir, libraryNames[i], libraryExtensions);
      try {
        System.load(latestLib);
        logger.fine("loaded " + latestLib); // debug
      } catch (Throwable e1) {
        logger.warning("Error While loading library " + latestLib + ": " + e1.toString());
      }
    }

    //        // initialize ResourceManager with resources from resources directory
    //        ResourceManager.addResources(dir);

  }
  protected void activate(ComponentContext context) {
    try {
      bundleContext = context.getBundleContext();
      if (CommonUtil.getStratosConfig() == null) {
        StratosConfiguration stratosConfig = CommonUtil.loadStratosConfiguration();
        CommonUtil.setStratosConfig(stratosConfig);
      }

      // Loading the EULA
      if (CommonUtil.getEula() == null) {
        String eula = CommonUtil.loadTermsOfUsage();
        CommonUtil.setEula(eula);
      }

      // packageInfos = new PackageInfoHolder();
      // context.getBundleContext().registerService(
      //		PackageInfoHolder.class.getName(), packageInfos, null);

      // Register manager configuration OSGI service
      try {
        StratosConfiguration stratosConfiguration = CommonUtil.loadStratosConfiguration();
        bundleContext.registerService(
            StratosConfiguration.class.getName(), stratosConfiguration, null);
        if (log.isDebugEnabled()) {
          log.debug("******* Cloud Common Service bundle is activated ******* ");
        }
      } catch (Exception ex) {
        String msg = "An error occurred while initializing Cloud Common Service as an OSGi Service";
        log.error(msg, ex);
      }
    } catch (Throwable e) {
      log.error("Error in activating Cloud Common Service Component" + e.toString());
    }
  }
Exemplo n.º 25
0
  protected Set<Class> processFileUrl(URL url, String basepath, Class clazz) throws IOException {
    Set<Class> set = new HashSet<Class>();
    String urlBase = url.getFile();
    urlBase = URLDecoder.decode(urlBase);

    Collection<File> files = FileUtils.listFiles(new File(urlBase), new String[] {"class"}, true);
    for (File file : files) {
      try {
        ClassReader reader = new ClassReader(new FileInputStream(file));
        ClassScanner visitor = getScanner(clazz);
        reader.accept(visitor, 0);
        if (visitor.isMatch()) {
          Class c = loadClass(visitor.getClassName());
          if (c != null) {
            set.add(c);
          }
        }
      } catch (IOException e) {
        if (logger.isDebugEnabled()) {
          Throwable t = ExceptionHelper.getRootException(e);
          logger.debug(String.format("%s: caused by: %s", e.toString(), t.toString()));
        }
      }
    }
    return set;
  }
  /**
   * 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);
        }
      }
    }
  }
Exemplo n.º 27
0
 private static void resolve(Invocation ai, Throwable e) {
   if (WebTool.isAJAX(ai.getController().getRequest())) {
     ai.getController().renderJson(e.getMessage() == null ? e.toString() : e.getMessage());
   } else {
     ai.getController().render("/pages/exception");
   }
 }
Exemplo n.º 28
0
 public Results fetch(boolean fromBeginning) throws BeeswaxException {
   this.atime = System.currentTimeMillis();
   Results r = new Results();
   // Only one person can access a running query at a time.
   synchronized (this) {
     switch (state) {
       case RUNNING:
         r.ready = false;
         break;
       case FINISHED:
         bringUp();
         r.ready = true;
         try {
           materializeResults(r, fromBeginning);
         } catch (IOException e) {
           throw new BeeswaxException(e.toString(), logContext.getName(), handle);
         }
         break;
       case EXCEPTION:
         if (exception instanceof BeeswaxException) {
           throw (BeeswaxException) exception;
         } else {
           throw new BeeswaxException(exception.toString(), logContext.getName(), handle);
         }
     }
   }
   return r;
 }
Exemplo n.º 29
0
  private static void usage(Throwable t) throws Exception {
    System.out.println("Caught " + t.toString());
    System.out.println("This is most likely due to the following:");
    System.out.println(
        "Please make sure your standalone.xml includes the H2DS datasource in its <profile> element.");
    System.out.println("An example configuration is as follows:\n");

    System.out.println("<subsystem xmlns=\"urn:jboss:domain:datasources:1.0\">");
    System.out.println("    <datasources>");
    System.out.println(
        "        <datasource jndi-name=\"java:/H2DS\" enabled=\"true\" use-java-context=\"true\" pool-name=\"H2DS\">");
    System.out.println(
        "            <connection-url>jdbc:h2:mem:test;DB_CLOSE_DELAY=-1</connection-url>");
    System.out.println("            <driver-class>org.h2.Driver</driver-class>");
    System.out.println("            <module>com.h2database.h2</module>");
    System.out.println("            <pool></pool>");
    System.out.println("            <security>");
    System.out.println("                <user-name>sa</user-name>");
    System.out.println("                <password>sa</password>");
    System.out.println("            </security>");
    System.out.println("            <validation></validation>");
    System.out.println("            <time-out></time-out>");
    System.out.println("            <statement></statement>");
    System.out.println("        </datasource>");
    System.out.println("    </datasources>");
    System.out.println("</subsystem>");

    System.out.println(
        "\nIf your profile already includes other datasource configurations, just add the nested <datasource> element above next to them.");
  }
 public void testStringConstructor() throws Exception {
   try {
     jsonobject = new JSONObject(jsonstring);
   } catch (Throwable t) {
     fail(t.toString());
   }
 }