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

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

    return this.connection;
  }
Example #2
0
 /**
  * This method is called when 'Finish' button is pressed in the wizard. We will create an
  * operation and run it using wizard as execution context.
  */
 public boolean performFinish() {
   final String containerName = page.getContainerName();
   final String fileName = page.getFileName();
   IRunnableWithProgress op =
       new IRunnableWithProgress() {
         public void run(IProgressMonitor monitor) throws InvocationTargetException {
           try {
             doFinish(containerName, fileName, monitor);
           } catch (CoreException e) {
             throw new InvocationTargetException(e);
           } finally {
             monitor.done();
           }
         }
       };
   try {
     getContainer().run(true, false, op);
   } catch (InterruptedException e) {
     return false;
   } catch (InvocationTargetException e) {
     Throwable realException = e.getTargetException();
     MessageDialog.openError(getShell(), "Error", realException.getMessage());
     return false;
   }
   return true;
 }
Example #3
0
  /**
   * This creates a new <code>{@link Document}</code> from an existing <code>InputStream</code> by
   * letting a DOM parser handle parsing using the supplied stream.
   *
   * @param in <code>InputStream</code> to parse.
   * @param validate <code>boolean</code> to indicate if validation should occur.
   * @return <code>Document</code> - instance ready for use.
   * @throws IOException when I/O error occurs.
   * @throws JDOMException when errors occur in parsing.
   */
  public Document getDocument(InputStream in, boolean validate) throws IOException, JDOMException {

    try {
      // Load the parser class
      Class parserClass = Class.forName("org.apache.xerces.parsers.DOMParser");
      Object parser = parserClass.newInstance();

      // Set validation
      Method setFeature =
          parserClass.getMethod("setFeature", new Class[] {java.lang.String.class, boolean.class});
      setFeature.invoke(
          parser, new Object[] {"http://xml.org/sax/features/validation", new Boolean(validate)});

      // Set namespaces true
      setFeature.invoke(
          parser, new Object[] {"http://xml.org/sax/features/namespaces", new Boolean(true)});

      // Set the error handler
      if (validate) {
        Method setErrorHandler =
            parserClass.getMethod("setErrorHandler", new Class[] {ErrorHandler.class});
        setErrorHandler.invoke(parser, new Object[] {new BuilderErrorHandler()});
      }

      // Parse the document
      Method parse = parserClass.getMethod("parse", new Class[] {org.xml.sax.InputSource.class});
      parse.invoke(parser, new Object[] {new InputSource(in)});

      // Get the Document object
      Method getDocument = parserClass.getMethod("getDocument", null);
      Document doc = (Document) getDocument.invoke(parser, null);

      return doc;
    } catch (InvocationTargetException e) {
      Throwable targetException = e.getTargetException();
      if (targetException instanceof org.xml.sax.SAXParseException) {
        SAXParseException parseException = (SAXParseException) targetException;
        throw new JDOMException(
            "Error on line "
                + parseException.getLineNumber()
                + " of XML document: "
                + parseException.getMessage(),
            e);
      } else if (targetException instanceof IOException) {
        IOException ioException = (IOException) targetException;
        throw ioException;
      } else {
        throw new JDOMException(targetException.getMessage(), e);
      }
    } catch (Exception e) {
      throw new JDOMException(e.getClass().getName() + ": " + e.getMessage(), e);
    }
  }
  /**
   * Indicates a user request to answer an incoming call from this <tt>CallPeer</tt>.
   *
   * <p>Sends an OK response to <tt>callPeer</tt>. Make sure that the call peer contains an SDP
   * description when you call this method.
   *
   * @throws OperationFailedException if we fail to create or send the response.
   */
  public synchronized void answer() throws OperationFailedException {
    RtpDescriptionPacketExtension answer = null;

    try {
      getMediaHandler().getTransportManager().wrapupConnectivityEstablishment();
      answer = getMediaHandler().generateSessionAccept(true);
    } catch (IllegalArgumentException e) {
      sessAcceptedWithNoCands = new SessionIQ();

      // HACK apparently FreeSwitch need to have accept before
      answer = getMediaHandler().generateSessionAccept(false);

      SessionIQ response =
          GTalkPacketFactory.createSessionAccept(
              sessionInitIQ.getTo(), sessionInitIQ.getFrom(), getSID(), answer);

      getProtocolProvider().getConnection().sendPacket(response);
      return;
    } catch (Exception exc) {
      logger.info("Failed to answer an incoming call", exc);

      // send an error response
      String reasonText = "Error: " + exc.getMessage();
      SessionIQ errResp =
          GTalkPacketFactory.createSessionTerminate(
              sessionInitIQ.getTo(),
              sessionInitIQ.getFrom(),
              sessionInitIQ.getID(),
              Reason.FAILED_APPLICATION,
              reasonText);

      setState(CallPeerState.FAILED, reasonText);
      getProtocolProvider().getConnection().sendPacket(errResp);
      return;
    }

    SessionIQ response =
        GTalkPacketFactory.createSessionAccept(
            sessionInitIQ.getTo(), sessionInitIQ.getFrom(), getSID(), answer);

    // send the packet first and start the stream later  in case the media
    // relay needs to see it before letting hole punching techniques through.
    if (sessAcceptedWithNoCands == null) getProtocolProvider().getConnection().sendPacket(response);

    try {
      getMediaHandler().start();
    } catch (UndeclaredThrowableException e) {
      Throwable exc = e.getUndeclaredThrowable();

      logger.info("Failed to establish a connection", exc);

      // send an error response
      String reasonText = "Error: " + exc.getMessage();
      SessionIQ errResp =
          GTalkPacketFactory.createSessionTerminate(
              sessionInitIQ.getTo(),
              sessionInitIQ.getFrom(),
              sessionInitIQ.getID(),
              Reason.GENERAL_ERROR,
              reasonText);

      getMediaHandler().getTransportManager().close();
      setState(CallPeerState.FAILED, reasonText);
      getProtocolProvider().getConnection().sendPacket(errResp);
      return;
    }

    // tell everyone we are connecting so that the audio notifications would
    // stop
    setState(CallPeerState.CONNECTED);
  }
Example #5
0
  public void run() {
    resetManager.registerMe();

    try {
      // Create a thread context object.
      IThreadContext threadContext = ThreadContextFactory.make();
      IJobManager jobManager = JobManagerFactory.make(threadContext);
      IRepositoryConnectionManager connectionMgr =
          RepositoryConnectionManagerFactory.make(threadContext);

      IDBInterface database =
          DBInterfaceFactory.make(
              threadContext,
              ManifoldCF.getMasterDatabaseName(),
              ManifoldCF.getMasterDatabaseUsername(),
              ManifoldCF.getMasterDatabasePassword());

      // Loop
      while (true) {
        // Do another try/catch around everything in the loop
        try {
          // Before we begin, conditionally reset
          resetManager.waitForReset(threadContext);

          // Accumulate the wait before doing the next check.
          // We start with 10 seconds, which is the maximum.  If there's a service request
          // that's faster than that, we'll adjust the time downward.
          long waitTime = 10000L;

          if (Logging.threads.isDebugEnabled()) Logging.threads.debug("Checking for deleting jobs");

          // See if there are any starting jobs.
          // Note: Since this following call changes the job state, we must be careful to reset it
          // on any kind of failure.
          JobDeleteRecord[] deleteJobs = jobManager.getJobsReadyForDelete(processID);
          try {

            if (deleteJobs.length == 0) {
              ManifoldCF.sleep(waitTime);
              continue;
            }

            if (Logging.threads.isDebugEnabled())
              Logging.threads.debug(
                  "Found " + Integer.toString(deleteJobs.length) + " jobs ready to be deleted");

            long currentTime = System.currentTimeMillis();

            // Loop through jobs
            int i = 0;
            while (i < deleteJobs.length) {
              JobDeleteRecord jsr = deleteJobs[i++];
              Long jobID = jsr.getJobID();
              try {
                jobManager.prepareDeleteScan(jobID);
                // Start deleting this job!
                jobManager.noteJobDeleteStarted(jobID, currentTime);
                jsr.noteStarted();
              } catch (ManifoldCFException e) {
                if (e.getErrorCode() == ManifoldCFException.INTERRUPTED)
                  throw new InterruptedException();
                if (e.getErrorCode() == ManifoldCFException.DATABASE_CONNECTION_ERROR) throw e;
                // We cannot abort the delete startup, but if we fall through, we'll put the job
                // back into
                // the state whence it came.  So, fall through.
                Logging.threads.error("Exception tossed: " + e.getMessage(), e);
              }
            }
          } finally {
            // Clean up all jobs that did not start
            ManifoldCFException exception = null;
            int i = 0;
            while (i < deleteJobs.length) {
              JobDeleteRecord jsr = deleteJobs[i++];
              if (!jsr.wasStarted()) {
                // Clean up from failed start.
                try {
                  jobManager.resetStartDeleteJob(jsr.getJobID());
                } catch (ManifoldCFException e) {
                  exception = e;
                }
              }
            }
            if (exception != null) throw exception;
          }

          // Sleep for the retry interval.
          ManifoldCF.sleep(waitTime);
        } catch (ManifoldCFException e) {
          if (e.getErrorCode() == ManifoldCFException.INTERRUPTED) break;

          if (e.getErrorCode() == ManifoldCFException.DATABASE_CONNECTION_ERROR) {
            resetManager.noteEvent();

            Logging.threads.error(
                "Start delete thread aborting and restarting due to database connection reset: "
                    + e.getMessage(),
                e);
            try {
              // Give the database a chance to catch up/wake up
              ManifoldCF.sleep(10000L);
            } catch (InterruptedException se) {
              break;
            }
            continue;
          }

          // Log it, but keep the thread alive
          Logging.threads.error("Exception tossed: " + e.getMessage(), e);

          if (e.getErrorCode() == ManifoldCFException.SETUP_ERROR) {
            // Shut the whole system down!
            System.exit(1);
          }

        } catch (InterruptedException e) {
          // We're supposed to quit
          break;
        } catch (OutOfMemoryError e) {
          System.err.println("agents process ran out of memory - shutting down");
          e.printStackTrace(System.err);
          System.exit(-200);
        } catch (Throwable e) {
          // A more severe error - but stay alive
          Logging.threads.fatal("Error tossed: " + e.getMessage(), e);
        }
      }
    } catch (Throwable e) {
      // Severe error on initialization
      System.err.println("agents process could not start - shutting down");
      Logging.threads.fatal("StartDeleteThread initialization error tossed: " + e.getMessage(), e);
      System.exit(-300);
    }
  }
Example #6
0
 private static String invocationErrMsg(InvocationTargetException ex) {
   Throwable targetEx = ex.getTargetException();
   String msg = ClassUtil.classname(targetEx.getClass()) + ": " + targetEx.getMessage();
   return msg;
 }
Example #7
0
  /**
   * Aspect implementation which executes grid-enabled methods on remote nodes.
   *
   * @param invoc Method invocation instance provided by JBoss AOP framework.
   * @return Method execution result.
   * @throws Throwable If method execution failed.
   */
  @SuppressWarnings({
    "ProhibitedExceptionDeclared",
    "ProhibitedExceptionThrown",
    "CatchGenericClass",
    "unchecked"
  })
  @Bind(
      pointcut = "execution(* *->@org.gridgain.grid.gridify.Gridify(..))",
      cflow = "org.gridgain.grid.gridify.aop.jboss.GridifyJbossAspect.CFLOW_STACK")
  public Object gridify(MethodInvocation invoc) throws Throwable {
    Method mtd = invoc.getMethod();

    Gridify ann = mtd.getAnnotation(Gridify.class);

    assert ann != null : "Intercepted method does not have gridify annotation.";

    // Since annotations in Java don't allow 'null' as default value
    // we have accept an empty string and convert it here.
    // NOTE: there's unintended behavior when user specifies an empty
    // string as intended grid name.
    // NOTE: the 'ann.gridName() == null' check is added to mitigate
    // annotation bugs in some scripting languages (e.g. Groovy).
    String gridName = F.isEmpty(ann.gridName()) ? null : ann.gridName();

    if (G.state(gridName) != STARTED) {
      throw new GridException("Grid is not locally started: " + gridName);
    }

    // Initialize defaults.
    GridifyArgument arg =
        new GridifyArgumentAdapter(
            mtd.getDeclaringClass(),
            mtd.getName(),
            mtd.getParameterTypes(),
            invoc.getArguments(),
            invoc.getTargetObject());

    if (!ann.interceptor().equals(GridifyInterceptor.class)) {
      // Check interceptor first.
      if (!ann.interceptor().newInstance().isGridify(ann, arg)) {
        return invoc.invokeNext();
      }
    }

    if (!ann.taskClass().equals(GridifyDefaultTask.class) && ann.taskName().length() > 0) {
      throw new GridException(
          "Gridify annotation must specify either Gridify.taskName() or "
              + "Gridify.taskClass(), but not both: "
              + ann);
    }

    try {
      Grid grid = G.grid(gridName);

      // If task class was specified.
      if (!ann.taskClass().equals(GridifyDefaultTask.class)) {
        return grid.execute(
                (Class<? extends GridTask<GridifyArgument, Object>>) ann.taskClass(),
                arg,
                ann.timeout())
            .get();
      }

      // If task name was not specified.
      if (ann.taskName().length() == 0) {
        return grid.execute(
                new GridifyDefaultTask(invoc.getActualMethod().getDeclaringClass()),
                arg,
                ann.timeout())
            .get();
      }

      // If task name was specified.
      return grid.execute(ann.taskName(), arg, ann.timeout()).get();
    } catch (Throwable e) {
      for (Class<?> ex : invoc.getMethod().getExceptionTypes()) {
        // Descend all levels down.
        Throwable cause = e.getCause();

        while (cause != null) {
          if (ex.isAssignableFrom(cause.getClass())) {
            throw cause;
          }

          cause = cause.getCause();
        }

        if (ex.isAssignableFrom(e.getClass())) {
          throw e;
        }
      }

      throw new GridifyRuntimeException("Undeclared exception thrown: " + e.getMessage(), e);
    }
  }
Example #8
0
 /**
  * Method that will wrap 't' as an {@link IllegalArgumentException} if it is a checked exception;
  * otherwise (runtime exception or error) throw as is
  */
 public static void throwAsIAE(Throwable t) {
   throwAsIAE(t, t.getMessage());
 }