private void validate(
      File file,
      Collection<Exception> exceptions,
      Collection<MavenProjectProblem> problems,
      Collection<MavenId> unresolvedArtifacts)
      throws RemoteException {
    for (Exception each : exceptions) {
      Maven3ServerGlobals.getLogger().info(each);

      if (each instanceof InvalidProjectModelException) {
        ModelValidationResult modelValidationResult =
            ((InvalidProjectModelException) each).getValidationResult();
        if (modelValidationResult != null) {
          for (Object eachValidationProblem : modelValidationResult.getMessages()) {
            problems.add(
                MavenProjectProblem.createStructureProblem(
                    file.getPath(), (String) eachValidationProblem));
          }
        } else {
          problems.add(
              MavenProjectProblem.createStructureProblem(
                  file.getPath(), each.getCause().getMessage()));
        }
      } else if (each instanceof ProjectBuildingException) {
        String causeMessage =
            each.getCause() != null ? each.getCause().getMessage() : each.getMessage();
        problems.add(MavenProjectProblem.createStructureProblem(file.getPath(), causeMessage));
      } else {
        problems.add(MavenProjectProblem.createStructureProblem(file.getPath(), each.getMessage()));
      }
    }
    unresolvedArtifacts.addAll(retrieveUnresolvedArtifactIds());
  }
Пример #2
0
 private static String getStackTrace(int endNumToSkip) {
   String sStackTrace = "";
   try {
     throw new Exception();
   } catch (Exception e) {
     StackTraceElement st[] = e.getStackTrace();
     for (int i = 1; i < st.length - endNumToSkip; i++) {
       if (!st[i].getMethodName().endsWith("StackTrace")) sStackTrace += st[i].toString() + "\n";
     }
     if (e.getCause() != null) sStackTrace += "\tCaused By: " + getStackTrace(e.getCause()) + "\n";
   }
   return sStackTrace;
 }
Пример #3
0
  private void initServices() throws PwmUnrecoverableException {
    for (final Class<? extends PwmService> serviceClass : PWM_SERVICE_CLASSES) {
      final Date startTime = new Date();
      final PwmService newServiceInstance;
      try {
        final Object newInstance = serviceClass.newInstance();
        newServiceInstance = (PwmService) newInstance;
      } catch (Exception e) {
        final String errorMsg =
            "unexpected error instantiating service class '"
                + serviceClass.getName()
                + "', error: "
                + e.toString();
        LOGGER.fatal(errorMsg, e);
        throw new PwmUnrecoverableException(
            new ErrorInformation(PwmError.ERROR_STARTUP_ERROR, errorMsg));
      }

      try {
        LOGGER.debug("initializing service " + serviceClass.getName());
        newServiceInstance.init(this);
        LOGGER.debug(
            "completed initialization of service "
                + serviceClass.getName()
                + " in "
                + TimeDuration.fromCurrent(startTime).asCompactString()
                + ", status="
                + newServiceInstance.status());
      } catch (PwmException e) {
        LOGGER.warn(
            "error instantiating service class '"
                + serviceClass.getName()
                + "', service will remain unavailable, error: "
                + e.getMessage());
      } catch (Exception e) {
        String errorMsg =
            "unexpected error instantiating service class '"
                + serviceClass.getName()
                + "', cannot load, error: "
                + e.getMessage();
        if (e.getCause() != null) {
          errorMsg += ", cause: " + e.getCause();
        }
        LOGGER.fatal(errorMsg);
        throw new PwmUnrecoverableException(
            new ErrorInformation(PwmError.ERROR_STARTUP_ERROR, errorMsg));
      }
      pwmServices.put(serviceClass, newServiceInstance);
    }
  }
Пример #4
0
 private boolean workaroundBug356918(
     HttpServletRequest request, HttpServletResponse response, Exception e)
     throws ServletException, JSONException {
   if (e instanceof CheckoutConflictException) {
     JSONObject result = new JSONObject();
     result.put(GitConstants.KEY_RESULT, MergeStatus.FAILED.name());
     Map<String, MergeFailureReason> failingPaths = new HashMap<String, MergeFailureReason>();
     String[] files = e.getMessage().split("\n"); // $NON-NLS-1$
     for (int i = 1; i < files.length; i++) {
       // TODO: this is not always true, but it's a temporary workaround
       failingPaths.put(files[i], MergeFailureReason.DIRTY_WORKTREE);
     }
     result.put(GitConstants.KEY_FAILING_PATHS, failingPaths);
     try {
       OrionServlet.writeJSONResponse(
           request, response, result, JsonURIUnqualificationStrategy.ALL_NO_GIT);
       return true;
     } catch (IOException e1) {
       e = e1;
     }
   }
   return statusHandler.handleRequest(
       request,
       response,
       new ServerStatus(
           IStatus.ERROR,
           HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
           "An error occured when merging.",
           e.getCause()));
 }
Пример #5
0
 Object createGuiElement(Class cls, EntityPlayer player, World world, int x, int y, int z) {
   try {
     try {
       if (debugGui)
         System.out.printf(
             "BaseMod.createGuiElement: Invoking create method of %s for %s in %s\n",
             cls, player, world);
       return cls.getMethod(
               "create", EntityPlayer.class, World.class, int.class, int.class, int.class)
           .invoke(null, player, world, x, y, z);
     } catch (NoSuchMethodException e) {
       if (debugGui)
         System.out.printf("BaseMod.createGuiElement: Invoking constructor of %s\n", cls);
       return cls.getConstructor(EntityPlayer.class, World.class, int.class, int.class, int.class)
           .newInstance(player, world, x, y, z);
     }
   } catch (Exception e) {
     Throwable cause = e.getCause();
     System.out.printf("BaseMod.createGuiElement: %s: %s\n", e, cause);
     if (cause != null) cause.printStackTrace();
     else e.printStackTrace();
     // throw new RuntimeException(e);
     return null;
   }
 }
Пример #6
0
 /** 获取删除操作的异常提示信息 */
 protected String getDeleteExceptionMsg(Exception e) {
   if (e instanceof PermissionDeniedException) {
     return e.getMessage() == null ? getText("exception.delete.permissionDenied") : e.getMessage();
   } else if (e instanceof InnerLimitedException) {
     return e.getMessage() == null ? getText("exception.delete.innerLimited") : e.getMessage();
   } else if (e instanceof NotExistsException) {
     return e.getMessage() == null ? getText("exception.delete.notExists") : e.getMessage();
   } else if (e instanceof ConstraintViolationException // 数据约束
       || e.getClass().getName().contains("ConstraintViolationException")
       || (e.getCause() != null
           && e.getCause().getClass().getName().contains("ConstraintViolationException"))) {
     return e.getMessage() == null
         ? getText("exception.delete.constraintViolation")
         : e.getMessage();
   } else {
     return e.getMessage();
   }
 }
Пример #7
0
 /*
  * Getters and Setters
  */
 public void setRequest(ServletRequest request) {
   try {
     this.context = (Context) request.getServletContext().getAttribute("context");
   } catch (Exception e) {
     log.error(e);
     errors.add(e.getMessage() + " " + e.getCause());
   }
   this.request = request;
 }
Пример #8
0
  /**
   * A loop driver for applying operations to all primary ClassNodes in our AST. Automatically skips
   * units that have already been processed through the current phase.
   */
  public void applyToPrimaryClassNodes(PrimaryClassNodeOperation body)
      throws CompilationFailedException {
    // GRECLIPSE: start
    /*old{
    Iterator classNodes = getPrimaryClassNodes(body.needSortedInput()).iterator();
    }*/
    // newcode
    List primaryClassNodes = getPrimaryClassNodes(body.needSortedInput());
    Iterator classNodes = primaryClassNodes.iterator();
    // end
    while (classNodes.hasNext()) {
      SourceUnit context = null;
      try {
        ClassNode classNode = (ClassNode) classNodes.next();
        context = classNode.getModule().getContext();
        // GRECLIPSE get to the bottom of this - why are operations running multiple times that
        // should only run once?
        if (context == null
            || context.phase < phase
            || (context.phase == phase && !context.phaseComplete)) {

          int offset = 1;
          Iterator<InnerClassNode> iterator = classNode.getInnerClasses();
          while (iterator.hasNext()) {
            iterator.next();
            offset++;
          }
          body.call(context, new GeneratorContext(this.ast, offset), classNode);
        }
      } catch (CompilationFailedException e) {
        // fall through, getErrorReporter().failIfErrors() will trigger
      } catch (NullPointerException npe) {
        throw npe;
      } catch (GroovyBugError e) {
        changeBugText(e, context);
        throw e;
      } catch (Exception e) {
        // check the exception for a nested compilation exception
        ErrorCollector nestedCollector = null;
        for (Throwable next = e.getCause(); next != e && next != null; next = next.getCause()) {
          if (!(next instanceof MultipleCompilationErrorsException)) continue;
          MultipleCompilationErrorsException mcee = (MultipleCompilationErrorsException) next;
          nestedCollector = mcee.collector;
          break;
        }

        if (nestedCollector != null) {
          getErrorCollector().addCollectorContents(nestedCollector);
        } else {
          getErrorCollector().addError(new ExceptionMessage(e, configuration.getDebug(), this));
        }
      }
    }

    getErrorCollector().failIfErrors();
  }
  public static void main(String args[]) {
    Config.setClientMode(true);
    LoaderOptions options = LoaderOptions.parseArgs(args);
    OutputHandler handler = new OutputHandler.SystemOutput(options.verbose, options.debug);
    SSTableLoader loader =
        new SSTableLoader(
            options.directory,
            new ExternalClient(
                options.hosts,
                options.rpcPort,
                options.user,
                options.passwd,
                options.transportFactory,
                options.storagePort,
                options.sslStoragePort,
                options.serverEncOptions),
            handler);
    DatabaseDescriptor.setStreamThroughputOutboundMegabitsPerSec(options.throttle);
    StreamResultFuture future = null;
    try {
      if (options.noProgress) future = loader.stream(options.ignores);
      else future = loader.stream(options.ignores, new ProgressIndicator());
    } catch (Exception e) {
      System.err.println(e.getMessage());
      if (e.getCause() != null) System.err.println(e.getCause());
      if (options.debug) e.printStackTrace(System.err);
      else System.err.println("Run with --debug to get full stack trace or --help to get help.");
      System.exit(1);
    }

    handler.output(String.format("Streaming session ID: %s", future.planId));

    try {
      future.get();
      System.exit(0); // We need that to stop non daemonized threads
    } catch (Exception e) {
      System.err.println("Streaming to the following hosts failed:");
      System.err.println(loader.getFailedHosts());
      System.err.println(e);
      if (options.debug) e.printStackTrace(System.err);
      System.exit(1);
    }
  }
Пример #10
0
 public void testExecuteWithUnspecifiedTestResultsDir() {
   setUpMocks(test);
   test.setTestResultsDir(null);
   try {
     test.execute();
     fail();
   } catch (Exception e) {
     assertThat(e.getCause(), Matchers.instanceOf(InvalidUserDataException.class));
   }
 }
Пример #11
0
 /** 删除操作 平台没有处理的异常的默认处理 */
 protected void dealOtherDeleteException(Json json, Exception e) {
   if ((e.getCause() != null
           && e.getCause().getClass().getSimpleName().equals("ConstraintViolationException"))
       || (e.getCause() != null
           && e.getCause().getCause() != null
           && e.getCause()
               .getCause()
               .getClass()
               .getSimpleName()
               .equals("ConstraintViolationException"))) {
     // 违反约束关联引发的异常
     json.put("msg", getText("exception.delete.constraintViolation"));
     json.put("e", e.getClass().getSimpleName());
   } else {
     // 其他异常
     json.put("msg", e.getMessage() != null ? e.getMessage() : e.toString());
     json.put("e", e.getClass().getSimpleName());
   }
 }
Пример #12
0
 /** 获取保存操作的异常提示信息 */
 protected String getSaveExceptionMsg(Exception e) {
   if (e instanceof PermissionDeniedException) { // 没有权限
     return e.getMessage() == null ? getText("exception.save.permissionDenied") : e.getMessage();
   } else if (e instanceof InnerLimitedException) { // 修改内置对象
     return e.getMessage() == null ? getText("exception.save.innerLimited") : e.getMessage();
   } else if (e instanceof NotExistsException) { // 对象不存在
     return e.getMessage() == null ? getText("exception.save.notExists") : e.getMessage();
   } else if (e instanceof UniqueConstraintException) { // 唯一性检测失败
     return e.getMessage() == null ? getText("exception.save.uniqueConstraint") : e.getMessage();
   } else if (e instanceof ConstraintViolationException // 数据约束
       || e.getClass().getName().contains("ConstraintViolationException")
       || (e.getCause() != null
           && e.getCause().getClass().getName().contains("ConstraintViolationException"))) {
     return e.getMessage() == null
         ? getText("exception.save.constraintViolation")
         : e.getMessage();
   } else {
     return e.getMessage();
   }
 }
Пример #13
0
 /** Creates an AxisFault. */
 public static AxisFault createAxisFault(Exception e) {
   AxisFault fault;
   Throwable cause = e.getCause();
   if (cause != null) {
     fault = new AxisFault(e.getMessage(), cause);
   } else {
     fault = new AxisFault(e.getMessage());
   }
   fault.setDetail(DataServiceFault.extractFaultMessage(e));
   fault.setFaultCode(
       new QName(DBConstants.WSO2_DS_NAMESPACE, DataServiceFault.extractFaultCode(e)));
   return fault;
 }
Пример #14
0
  public void startFlush(boolean automatic_resume) throws Exception {
    if (!flushSupported())
      throw new IllegalStateException(
          "Flush is not supported, add pbcast.FLUSH protocol to your configuration");

    try {
      down(new Event(Event.SUSPEND));
    } catch (Exception e) {
      throw new Exception("Flush failed", e.getCause());
    } finally {
      if (automatic_resume) stopFlush();
    }
  }
Пример #15
0
    public GoConfigValidity saveXml(String xmlPartial, String expectedMd5) {
      GoConfigValidity hasValidRequest = checkValidity();
      if (!hasValidRequest.isValid()) {
        return hasValidRequest;
      }

      try {
        return GoConfigValidity.valid(updatePartial(xmlPartial, expectedMd5));
      } catch (JDOMParseException jsonException) {
        return GoConfigValidity.invalid(
                String.format("%s - %s", INVALID_CRUISE_CONFIG_XML, jsonException.getMessage()))
            .fromConflict();
      } catch (ConfigMergePreValidationException e) {
        return invalid(e).mergePreValidationError();
      } catch (Exception e) {
        if (e.getCause() instanceof ConfigMergePostValidationException) {
          return GoConfigValidity.invalid(e.getCause().getMessage()).mergePostValidationError();
        }
        if (e.getCause() instanceof ConfigMergeException) {
          return GoConfigValidity.invalid(e.getCause().getMessage()).mergeConflict();
        }
        return GoConfigValidity.invalid(e).fromConflict();
      }
    }
Пример #16
0
  public void restartApplication() {

    try {

      final String javaBin =
          System.getProperty("java.home") + File.separator + "bin" + File.separator + "javaw";
      final File currentJar =
          new File(network.class.getProtectionDomain().getCodeSource().getLocation().toURI());

      System.out.println("javaBin " + javaBin);
      System.out.println("currentJar " + currentJar);
      System.out.println("currentJar.getPath() " + currentJar.getPath());

      /* is it a jar file? */
      // if(!currentJar.getName().endsWith(".jar")){return;}

      try {

        // xmining = 0;
        // systemx.shutdown();

      } catch (Exception e) {
        e.printStackTrace();
      }

      /* Build command: java -jar application.jar */
      final ArrayList<String> command = new ArrayList<String>();
      command.add(javaBin);
      command.add("-jar");
      command.add("-Xms256m");
      command.add("-Xmx1024m");
      command.add(currentJar.getPath());

      final ProcessBuilder builder = new ProcessBuilder(command);
      builder.start();

      // try{Thread.sleep(10000);} catch (InterruptedException e){}

      // close and exit
      SystemTray.getSystemTray().remove(network.icon);
      System.exit(0);

    } // try
    catch (Exception e) {
      JOptionPane.showMessageDialog(null, e.getCause());
    }
  } // ******************************
Пример #17
0
 @SuppressWarnings("unchecked")
 private Tuple2<scala.collection.immutable.List<scala.collection.Map<String, Object>>, String>
     createTimedResults(PipeExecutionResult result) {
   try {
     return (Tuple2<scala.collection.immutable.List<scala.collection.Map<String, Object>>, String>)
         createTimedResults.invoke(result);
   } catch (Exception e) {
     Throwable root = e.getCause();
     while (root.getCause() != null) {
       root = root.getCause();
     }
     if (root != null) {
       throw new RuntimeException(root);
     } else {
       throw new RuntimeException("Unable to extract cypher results", e);
     }
   }
 }
Пример #18
0
 public void startFlush(List<Address> flushParticipants, boolean automatic_resume)
     throws Exception {
   if (!flushSupported())
     throw new IllegalStateException(
         "Flush is not supported, add pbcast.FLUSH protocol to your configuration");
   View v = getView();
   boolean validParticipants = v != null && v.getMembers().containsAll(flushParticipants);
   if (!validParticipants)
     throw new IllegalArgumentException(
         "Current view " + v + " does not contain all flush participants " + flushParticipants);
   try {
     down(new Event(Event.SUSPEND, flushParticipants));
   } catch (Exception e) {
     throw new Exception("Flush failed", e.getCause());
   } finally {
     if (automatic_resume) stopFlush(flushParticipants);
   }
 }
  /** @throws Exception If failed. */
  @SuppressWarnings({"AssignmentToCatchBlockParameter"})
  public void testCancel() throws Exception {
    Ignite ignite = G.ignite(getTestGridName());

    ignite
        .compute()
        .localDeployTask(GridCancelTestTask.class, GridCancelTestTask.class.getClassLoader());

    ComputeTaskFuture<?> res0 =
        executeAsync(
            ignite.compute().withTimeout(maxJobExecTime * 2),
            GridCancelTestTask.class.getName(),
            null);

    try {
      Object res = res0.get();

      info("Cancel test result: " + res);

      synchronized (mux) {
        // Every execute must be called.
        assert execCnt <= SPLIT_COUNT : "Invalid execute count: " + execCnt;

        // Job returns 1 if was cancelled.
        assert (Integer) res <= SPLIT_COUNT : "Invalid task result: " + res;

        // Should be exactly the same as Jobs number.
        assert cancelCnt <= SPLIT_COUNT : "Invalid cancel count: " + cancelCnt;

        // One per start and one per stop and some that come with heartbeats.
        assert colResolutionCnt > SPLIT_COUNT + 1
            : "Invalid collision resolution count: " + colResolutionCnt;
      }
    } catch (ComputeTaskTimeoutException e) {
      error("Task execution got timed out.", e);
    } catch (Exception e) {
      assert e.getCause() != null;

      if (e.getCause() instanceof IgniteCheckedException) e = (Exception) e.getCause();

      if (e.getCause() instanceof IOException) e = (Exception) e.getCause();

      assert e.getCause() instanceof InterruptedException
          : "Invalid exception cause: " + e.getCause();
    }
  }
  private void open() throws MavenIndexException {
    try {
      try {
        doOpen();
      } catch (Exception e1) {
        final boolean versionUpdated =
            e1.getCause() instanceof PersistentEnumeratorBase.VersionUpdatedException;
        if (!versionUpdated) MavenLog.LOG.warn(e1);

        try {
          doOpen();
        } catch (Exception e2) {
          throw new MavenIndexException("Cannot open index " + myDir.getPath(), e2);
        }
        markAsBroken();
      }
    } finally {
      save();
    }
  }
Пример #21
0
  void bar(List<String> list, HashMap<String, Integer> map) {
    char c = "a".charAt(0);
    byte b = new Integer(10).byteValue();
    int i = new Double(10.1).intValue();
    float f = new Double(10.1).floatValue();
    long l = new Double(10.1).longValue();
    short s = new Double(10.1).shortValue();

    try {
      String removed = list.remove(10);
      Boolean isRemoved = list.remove("a");
    } catch (Exception e) {
      System.err.println(e.getMessage());
      throw new RuntimeException(e.getCause());
    }

    for (Map.Entry<String, Integer> entry : map.entrySet()) {
      String key = entry.getKey();
      Integer value = entry.getValue();
      entry.setValue(value + 1);
    }
  }
Пример #22
0
  public void execute(JobExecutionContext jec) throws JobExecutionException {

    try {
      Stripersist.requestInit();
      EntityManager em = Stripersist.getEntityManager();

      StringBuilder monitoringFailures = new StringBuilder();

      int online = 0, offline = 0;

      // TODO: where monitoringEnabled = true...
      for (GeoService gs : (List<GeoService>) em.createQuery("from GeoService").getResultList()) {

        String debugMsg =
            String.format(
                "%s service %s (#%d) with URL: %s",
                gs.getProtocol(), gs.getName(), gs.getId(), gs.getUrl());
        try {

          if (isInterrupted()) {
            log.info("Interrupted, ending monitoring job");
            return;
          }

          gs.checkOnline();
          online++;
          gs.setMonitoringStatusOK(true);
          log.debug("ONLINE: " + debugMsg);
        } catch (Exception e) {
          gs.setMonitoringStatusOK(false);
          offline++;
          log.debug("OFFLINE: " + debugMsg);
          if (log.isTraceEnabled()) {
            log.trace("Exception", e);
          }
          String message = e.toString();
          Throwable cause = e.getCause();
          while (cause != null) {
            message += "; " + cause.toString();
            cause = cause.getCause();
          }
          monitoringFailures.append(
              String.format(
                  "%s service %s (#%d)\nURL: %s\nFout: %s\n\n",
                  gs.getProtocol(), gs.getName(), gs.getId(), gs.getUrl(), message));
        }
      }

      em.getTransaction().commit();

      log.info(
          String.format(
              "Total services %d, online: %d, offline: %d, runtime: %d s",
              online + offline, online, offline, jec.getJobRunTime() / 1000));

      if (offline > 0) {

        Set emails = new HashSet();
        for (User admin :
            (List<User>)
                em.createQuery(
                        "select u from User u "
                            + "join u.groups g "
                            + "where g.name = '"
                            + Group.SERVICE_ADMIN
                            + "' ")
                    .getResultList()) {
          emails.add(admin.getDetails().get(User.DETAIL_EMAIL));
        }
        emails.remove(null);

        if (!emails.isEmpty()) {
          StringBuilder mail = new StringBuilder();

          SimpleDateFormat f = new SimpleDateFormat("dd-MM-yyy HH:mm:ss");
          mail.append(
              String.format(
                  "Bij een controle op %s zijn in het gegevensregister %d services gevonden waarbij fouten zijn geconstateerd.\n"
                      + "\nDe volgende controle zal worden uitgevoerd op %s.\nHieronder staat de lijst met probleemservices:\n\n",
                  f.format(jec.getFireTime()), offline, f.format(jec.getNextFireTime())));
          mail.append(monitoringFailures);

          mail(jec, emails, offline + " services zijn offline bij controle", mail.toString());
        }
      }
    } catch (Exception e) {
      log.error("Error", e);
    } finally {
      Stripersist.requestComplete();
    }
  }
Пример #23
0
  private boolean sendError(FacesContext context, String lifecycle, Exception e) {
    for (Throwable cause = e; cause != null; cause = cause.getCause()) {
      if (cause instanceof DisplayableException) {
        if (e instanceof RuntimeException) throw (RuntimeException) e;
        else throw new FacesException(e);
      } else if (cause instanceof ServletException) throw new FacesException(e);
      else if (cause instanceof JspException) throw new FacesException(e);
    }

    ExternalContext extContext = context.getExternalContext();
    Object response = extContext.getResponse();

    if (!(response instanceof HttpServletResponse)) {
      context.renderResponse();

      if (e instanceof RuntimeException) throw (RuntimeException) e;
      else throw new RuntimeException(e);
    }

    log.log(Level.WARNING, e.toString(), e);

    HttpServletResponse res = (HttpServletResponse) response;

    try {
      context.renderResponse();
      context.responseComplete();

      res.setStatus(500, "JSF Exception");
      res.setContentType("text/html");

      PrintWriter out = res.getWriter();

      out.println("<body>");

      out.println("<h3>JSF exception detected in " + lifecycle + " phase</h3>");

      String msg = e.getMessage();
      out.println("<span style='color:red;font:bold'>" + Html.escapeHtml(msg) + "</span><br/>");

      out.println("<h3>Context: " + context.getViewRoot() + "</h3>");
      out.println("<code><pre>");

      String errorId = null;

      if (e instanceof FacesException && msg.startsWith("id=")) {
        int p = msg.indexOf(' ');
        errorId = msg.substring(3, p);
      }

      printComponentTree(out, errorId, context, context.getViewRoot(), 0);

      out.println("</pre></code>");

      if (!Alarm.isTest()) {
        out.println("<h3>Stack Trace</h3>");
        out.println("<pre>");
        if (e.getCause() != null) e.getCause().printStackTrace(out);
        else e.printStackTrace(out);
        out.println("</pre>");
      }

      out.println("</body>");

      // clear, so we don't just loop
      Application app = context.getApplication();

      ViewHandler view = app.getViewHandler();

      UIViewRoot viewRoot = context.getViewRoot();

      viewRoot = view.createView(context, viewRoot.getViewId());

      context.setViewRoot(viewRoot);

      // view.writeState(context); // XXX: no need to output state, but review.

      return true;
    } catch (IOException e1) {
      throw new RuntimeException(e);
    }
  }
Пример #24
0
  @Override
  public void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    Map<String, String> map = getURIParams();
    String cmd = map.get("cmd");
    Method dispatchMethod = null;

    User user = getUser();

    try {
      // Check permissions if the user has access to the CMS Maintenance Portlet
      if (user == null) {
        String userName =
            map.get("u") != null ? map.get("u") : map.get("user") != null ? map.get("user") : null;

        String password =
            map.get("p") != null
                ? map.get("p")
                : map.get("passwd") != null ? map.get("passwd") : null;

        LoginFactory.doLogin(userName, password, false, request, response);
        user = (User) request.getSession().getAttribute(WebKeys.CMS_USER);
        // Set the logged user in order to make it available from this action using the getUser()
        // method
        if (user != null) {
          setUser(user);
        }

        if (user == null) {
          setUser(request);
          user = getUser();
        }
        if (user == null) {
          response.sendError(401);
          return;
        }
      }
    } catch (Exception e) {
      Logger.error(this.getClass(), e.getMessage());
      response.sendError(401);
      return;
    }

    if (null != cmd) {
      try {
        dispatchMethod =
            this.getClass()
                .getMethod(cmd, new Class[] {HttpServletRequest.class, HttpServletResponse.class});
      } catch (Exception e) {
        try {
          dispatchMethod =
              this.getClass()
                  .getMethod(
                      "action", new Class[] {HttpServletRequest.class, HttpServletResponse.class});
        } catch (Exception e1) {
          Logger.error(this.getClass(), "Trying to get method:" + cmd);
          Logger.error(this.getClass(), e1.getMessage(), e1.getCause());
          throw new DotRuntimeException(e1.getMessage());
        }
      }
      try {
        dispatchMethod.invoke(this, new Object[] {request, response});
      } catch (Exception e) {
        Logger.error(this.getClass(), "Trying to invoke method:" + cmd);
        Logger.error(this.getClass(), e.getMessage(), e.getCause());
        throw new DotRuntimeException(e.getMessage());
      }
    }
  }
Пример #25
0
  // Use
  // query:http://finance.google.com/finance/historical?q=NASDAQ:LONG&startdate=Jun+1,2009&enddate=Jun+1,2010&output=csv
  // http://www.google.com/finance/historical?startdate=Jan+1%2C+2001&enddate=Nov+15%2C+2012&num=30&output=csv&q=
  // have a DB with different tables; each table represents a stock or index. then everyday, a cron
  // job
  // runs that updates the table with the day's stock quotes (via RESTful JSON API), then this java
  // file runs and parses the list of historical data
  // then it outputs the results to a file (or graphical/web output, if a GUI/web integration is
  // added).
  public static void main(String args[]) {
    try {

      // look through dir
      File directory = new File(DIRECTORY);
      String fileNames[] = directory.list();
      PriorityQueue<Double> returnsList = new PriorityQueue<Double>();
      PriorityQueue<Double> successList = new PriorityQueue<Double>();
      Map<String, Double> stockReturnsList = new HashMap<String, Double>();
      Map<String, Double> stockPreList = new HashMap<String, Double>();

      // init indices
      calculateIndices();

      for (int x = 0; x < fileNames.length; x++) {

        if (fileNames[x].endsWith(".csv")) {

          // Open the file that is the first
          // command line parameter
          FileInputStream fstream = new FileInputStream(DIRECTORY + "/" + fileNames[x]);

          // create analysis file - this is called [STOCK_SYMBOL]-analysis.txt by default
          // this implementation writes to a file in the analysis folder for each stock analysed,
          // but this could be replaced by console output or web output, etc
          FileWriter fstream_w =
              new FileWriter(DIRECTORY + "/analysis/" + fileNames[x] + "-analysis.txt");
          BufferedWriter out = new BufferedWriter(fstream_w);

          // Skip indices
          if (fileNames[x].equals("DJIA.csv")
              || fileNames[x].equals("NASDAQ.csv")
              || fileNames[x].equals("SP500.csv")
              || !fileNames[x].contains(".csv")) {
            continue;
          }

          // Get the object of DataInputStream
          DataInputStream in = new DataInputStream(fstream);
          BufferedReader br = new BufferedReader(new InputStreamReader(in));
          br.readLine();
          String strLine;
          String stock = fileNames[x].substring(0, fileNames[x].indexOf("."));
          out.write("-------------------------------------");
          out.newLine();
          out.write("Analyzing predictions for " + stock + ": ");
          out.newLine();
          out.write("-------------------------------------");
          out.newLine();
          ArrayList<String> priceList = new ArrayList<String>();
          ArrayList<String> dateList = new ArrayList<String>();
          // Read File Line By Line
          while ((strLine = br.readLine()) != null) {
            String[] str = strLine.split(",");
            String date = str[0];
            // Weird on Aug 9, 2011, stock prices were 0??
            if (!date.equals("9-Aug-11")) {
              dateList.add(date);
              // buy at the open
              priceList.add(str[1]);
            }
          }

          Collections.reverse(priceList);
          Collections.reverse(dateList);

          Double avg = 0.0;
          Double buyPrice = 0.0;
          Double support = Double.parseDouble(priceList.get(0));
          Double resistance = 0.00;
          Double sellLim = 0.0;
          Double stopLim = 0.0;
          Double profit = 0.0;
          Double total = 0.0;
          Integer numShares = 0;
          Boolean bought = false;
          Boolean sold = false;
          Boolean shortSell = false;
          Boolean enableShortSell = false;
          Double nextPrice = 0.0;
          Integer trades = 0;
          Integer success = 0;
          // this is a sample commission. Set it to whatever your brokerage uses.
          Double commission = 9.95;
          Double variance = 0.0;
          Double varAvg = 0.0;
          Double stdDev = 0.0;
          Double volatily = 0.0;
          Integer trendCount = 0;
          Double prevAvg = 0.0;
          Boolean downTrend = false;
          Boolean upTrend = false;
          ArrayQueue<Double> avgList = new ArrayQueue<Double>();

          // Calculate Support (lowest of 30 day avg)
          // Calculate Resistance (highest of 30 day avg)
          // Calculate 10-day moving average
          for (int i = 0; i < 30; i++) {
            Double tempInt = Double.parseDouble(priceList.get(i));
            varAvg += tempInt;

            if (i < 10) {
              support = Math.min(support, tempInt);
              resistance = Math.max(resistance, tempInt);
              avg += tempInt;
            }
          }

          avg = avg / 10;
          varAvg = varAvg / 30;

          // calc variance for 30 days
          for (int i = 0; i < 30; i++) {
            Double tempInt = Double.parseDouble(priceList.get(i));
            variance += Math.pow((tempInt - varAvg), 2);
          }

          stdDev = Math.sqrt(variance / 29);
          volatily = stdDev / avg;

          // populate avgList
          for (int i = 0; i < 5; i++) {
            avgList.enqueue(avg);
          }

          // Main loop
          for (int i = 10; i < priceList.size(); i++) {
            nextPrice = Double.parseDouble(priceList.get(i));

            // if it detects a downtrend
            if (downTrend) {
              // stock is bearish
              Boolean cond = !bought && nextPrice <= support;
              if (volatily > 0.2) {
                cond = !bought;
              }

              // if short sell is enabled
              // disabled this whole section for now. Short selling is complicated.
              if (cond && enableShortSell) {
                shortSell = true;
                buyPrice = nextPrice;
                bought = true;
                sold = false;
                sellLim = buyPrice * 1.1;
                stopLim = buyPrice * 0.95;
                out.write(dateList.get(i) + ": Shorting " + numShares + " Shares at: " + nextPrice);
                out.newLine();
                trades++;
              } else if (bought && !sold && enableShortSell) {
                if (shortSell) {
                  if (nextPrice >= sellLim) {
                    profit = (numShares * buyPrice - numShares * nextPrice);
                    total += profit;
                    sold = true;
                    bought = false;
                    shortSell = false;
                    out.write(
                        dateList.get(i) + ": Covered " + numShares + " Shares at: " + nextPrice);
                    out.newLine();
                    trades++;
                  } else if (nextPrice <= stopLim) {
                    profit = (numShares * buyPrice - numShares * nextPrice);
                    total += profit;
                    sold = true;
                    bought = false;
                    shortSell = false;
                    out.write(
                        dateList.get(i) + ": Covered " + numShares + " Shares at: " + nextPrice);
                    out.newLine();
                    trades++;
                    success++;
                  }
                } else {
                  // if stock is above the sell limit
                  if (nextPrice >= sellLim) {
                    profit = (numShares * nextPrice - numShares * buyPrice);
                    total += profit;
                    sold = true;
                    bought = false;
                    out.write(dateList.get(i) + ": Sold " + numShares + " Shares at: " + nextPrice);
                    out.newLine();
                    trades++;
                    success++;
                  }
                  // if stock falls below the stop limit, sell.
                  else if (nextPrice <= stopLim) {
                    profit = (numShares * nextPrice - numShares * buyPrice);
                    total += profit;
                    sold = true;
                    bought = false;
                    out.write(dateList.get(i) + ": Sold " + numShares + " Shares at: " + nextPrice);
                    out.newLine();
                    trades++;
                  }
                }
              }
            } else {
              // this is when it buys
              // change to 0.95 to whatever your buy point is
              if (!bought) {
                String date = dateList.get(i);
                Double index1 = SPPer.get(date);
                Double index2 = dowJonesPer.get(date);
                Double index3 = nasdaqPer.get(date);
                Boolean bearDay = false;
                if (index1 != null && index2 != null && index3 != null) {
                  bearDay = index1 <= -0.8 && index2 <= -0.8 && index3 <= -0.8;
                }
                Boolean buyCond = upTrend && nextPrice <= avg;
                if (volatily > 0.2) {
                  buyCond = upTrend;
                }
                // stock is bullish
                if (buyCond && bearDay) {
                  buyPrice = nextPrice;
                  Double num = BUYING_POWER / nextPrice;
                  numShares = new Integer(num.intValue());
                  bought = true;
                  sold = false;
                  if (volatily >= 0.3) {
                    sellLim = buyPrice * 1.1;
                  } else {
                    sellLim = buyPrice * SELL_LIMIT;
                  }
                  stopLim = buyPrice * STOP_LIMIT;
                  out.write(dateList.get(i) + ": Bought " + numShares + " Shares at: " + buyPrice);
                  out.newLine();
                  trades++;
                  // stock is neutral
                } else if (nextPrice <= avg * 0.95 && bearDay) {
                  buyPrice = nextPrice;
                  Double num = BUYING_POWER / nextPrice;
                  numShares = new Integer(num.intValue());
                  bought = true;
                  sold = false;
                  sellLim = buyPrice * SELL_LIMIT;
                  stopLim = buyPrice * STOP_LIMIT;
                  out.write(dateList.get(i) + ": Bought " + numShares + " Shares at: " + buyPrice);
                  out.newLine();
                  trades++;
                }
              } else if (bought && !sold) {
                if (shortSell) {
                  if (nextPrice >= sellLim) {
                    profit = (numShares * buyPrice - numShares * nextPrice);
                    total += profit;
                    sold = true;
                    bought = false;
                    shortSell = false;
                    out.write(
                        dateList.get(i) + ": Covered " + numShares + " Shares at: " + nextPrice);
                    out.newLine();
                    trades++;
                  } else if (nextPrice <= stopLim) {
                    profit = (numShares * buyPrice - numShares * nextPrice);
                    total += profit;
                    sold = true;
                    bought = false;
                    shortSell = false;
                    out.write(
                        dateList.get(i) + ": Covered " + numShares + " Shares at: " + nextPrice);
                    out.newLine();
                    trades++;
                    success++;
                  }
                } else {
                  String date = dateList.get(i);
                  Double index1 = SPPer.get(date);
                  Double index2 = dowJonesPer.get(date);
                  Double index3 = nasdaqPer.get(date);
                  // use this variable for higher returns but less success rate
                  Boolean bullDay = false;
                  if (index1 != null && index2 != null && index3 != null) {
                    bullDay = index1 > 0.4 && index2 > 0.4 && index3 > 0.4;
                  }

                  // if stock is above the sell limit
                  if (nextPrice >= sellLim && bullDay) {
                    profit = (numShares * nextPrice - numShares * buyPrice);
                    total += profit;
                    sold = true;
                    bought = false;
                    out.write(dateList.get(i) + ": Sold " + numShares + " Shares at: " + nextPrice);
                    out.newLine();
                    trades++;
                    success++;
                  }

                  // if stock falls below the stop limit and its a bull day (very likely something
                  // bad about the stock), sell.
                  else if (nextPrice <= stopLim && bullDay) {
                    profit = (numShares * nextPrice - numShares * buyPrice);
                    total += profit;
                    sold = true;
                    bought = false;
                    out.write(dateList.get(i) + ": Sold " + numShares + " Shares at: " + nextPrice);
                    out.newLine();
                    trades++;
                  }
                }
              }
            }

            // recompute 10-day rolling average
            prevAvg = avg;
            avg = avg * 10;
            avg -= Double.parseDouble(priceList.get(i - 10));
            avg += nextPrice;
            avg = avg / 10;
            avgList.dequeue();
            avgList.enqueue(avg);

            // Detect trends
            if (avg < prevAvg) {
              upTrend = false;
              if (trendCount < 10) {
                trendCount++;
              }
            } else if (avg > prevAvg) {
              downTrend = false;
              if (trendCount > 0) {
                trendCount--;
              }
            }

            Integer isDown = 0;
            Integer isUp = 0;
            for (int j = 0; j < avgList.size() - 1; j++) {
              if (avgList.peek(j) <= avgList.peek(j + 1)) {
                isUp++;
              } else if (avgList.peek(j) >= avgList.peek(j + 1)) {
                isDown++;
              }
            }

            // if stock goes down for 5 days consecutively, its on a downtrend
            if (isDown > 3) {
              downTrend = true;
              //    System.out.println("Downtrend. ");
            }

            // if a stock goes up for 5 days consecutively, its on an uptrend
            else if (isUp > 3) {
              upTrend = true;
              //    System.out.println("Uptrend. ");
            }

            // recalculate support + resistance + variance for 30-day
            support = Double.parseDouble(priceList.get(i - 10));
            resistance = Double.parseDouble(priceList.get(i - 10));

            if (i > 30) {
              variance -= Math.pow((Double.parseDouble(priceList.get(i - 1 - 30)) - varAvg), 2);
              varAvg = 0.0;
              for (int j = 0; j < 30; j++) {
                Double tempInt = Double.parseDouble(priceList.get(i - (30 - j)));
                varAvg += tempInt;
              }

              varAvg = varAvg / 30;
              variance += Math.pow(nextPrice - varAvg, 2);
              stdDev = Math.sqrt(variance / 29);
              volatily = stdDev / avg;
            }

            for (int j = 0; j < 10; j++) {
              Double tempInt = Double.parseDouble(priceList.get(i - (10 - j)));
              support = Math.min(support, tempInt);
              resistance = Math.max(resistance, tempInt);
            }
          }

          if (downTrend) {
            out.write("Stock is on a downtrend. Do not buy it. Expect to short it/sell it. ");
            out.newLine();
          } else if (upTrend) {
            out.write("Stock is on an uptrend. Expect to buy it around $" + avg);
            out.newLine();
            out.write(
                " when S&P 500 index <= "
                    + (Double.parseDouble(SPList.get(dateList.get(dateList.size() - 1))) * 0.992)
                    + ",");
            out.newLine();
            /*                        out.write(" when DJIA index <= " +
                (Double.parseDouble(dowJonesList.get(dateList.get(dateList.size() - 2))) * 0.992) + ",");
            out.newLine();*/
            /*                        out.write(" when NASDAQ index <= " +
                (Double.parseDouble(nasdaqList.get(dateList.get(dateList.size() - 2))) * 0.992) + ".");
            out.newLine();*/
          } else {
            out.write("Stock is neutral. Buy in around $" + avg * 0.95);
            out.newLine();
            out.write(
                " when S&P 500 index <= "
                    + (Double.parseDouble(SPList.get(dateList.get(dateList.size() - 1))) * 0.992)
                    + ",");
            out.newLine();
            /*                        out.write(" when DJIA index <= " +
                (Double.parseDouble(dowJonesList.get(dateList.get(dateList.size() - 2))) * 0.992) + ",");
            out.newLine();*/
            /*                        out.write(" when NASDAQ index <= " +
                (Double.parseDouble(nasdaqList.get(dateList.get(dateList.size() - 2))) * 0.992) + ".");
            out.newLine();*/
          }

          if (!sold && bought) {
            if (shortSell) {
              out.write("Next cover price is " + stopLim);
              out.newLine();
            } else {
              out.write("Sell it at $" + stopLim + " or below, or $" + sellLim + " or above ");
              out.newLine();
              out.write(
                  " when S&P 500 index >= "
                      + (Double.parseDouble(SPList.get(dateList.get(dateList.size() - 1))) * 0.992)
                      + ",");
              out.newLine();
              /*                            out.write(" when DJIA index >= " +
                  (Double.parseDouble(dowJonesList.get(dateList.get(dateList.size() - 2))) * 0.992) + ",");
              out.newLine();*/
              /*  out.write(" when NASDAQ index >= " +
                  (Double.parseDouble(nasdaqList.get(dateList.get(dateList.size() - 2))) * 0.992) + ".");
              out.newLine();*/
            }
          }
          out.write("Support price is " + support);
          out.newLine();
          out.write("Resistance price is " + resistance);
          out.newLine();
          out.write("Std Dev = " + stdDev + ".");
          out.newLine();
          if (volatily <= 0.1) {
            out.write("The stock is not volatile.");
            out.newLine();
          } else if (volatily > 0.1 && volatily < 0.2) {
            out.write("The stock is moderately volatile.");
            out.newLine();
          } else {
            out.write("The stock  is highly volatile.");
            out.newLine();
          }

          out.write("Total P&L for this stock is $" + total + ".");
          out.newLine();
          out.write("Return on Investment is " + total / 100.00 + "%");
          out.newLine();
          returnsList.add(total / 100.00);
          stockReturnsList.put(stock, total / 100.00);

          if (trades > 0) {
            Double num = (double) success.intValue() / ((double) trades.intValue() / 2);
            numShares = new Integer(num.intValue());
            successList.add(num * 100);
            stockPreList.put(stock, num * 100);
            out.write("Success rate was " + num * 100 + "%.");
            out.newLine();
          }
          out.write("Commission was $" + commission * trades + " for " + trades + " trades.");
          out.newLine();
          br.close();
          out.close();
        }
      }

      // This part writes the summary to a file called SUMMARY.txt
      FileWriter fstream_w = new FileWriter(DIRECTORY + "/analysis/" + "SUMMARY.txt");
      BufferedWriter out = new BufferedWriter(fstream_w);
      out.write("----------------------------------------------");
      out.newLine();
      out.write("Top stocks in order of returns were: ");
      out.newLine();
      Double avgReturns = 0.0;
      Double avgPredict = 0.0;
      for (Double ret : returnsList) {
        // gets the first stock that has this return
        String stockName = getKeyByValue(stockReturnsList, ret);
        out.write(stockName + " " + ret + "%.");
        out.newLine();
        avgReturns += ret;
        stockReturnsList.remove(stockName);
      }
      out.write("----------------------------------------------");
      out.newLine();
      out.write("Top stocks in order of predicting success were: ");
      out.newLine();
      for (Double pre : successList) {
        // gets the first stock that has this prediction
        String stockName = getKeyByValue(stockPreList, pre);
        out.write(stockName + " " + pre + "%.");
        out.newLine();
        avgPredict += pre;
        stockPreList.remove(stockName);
      }

      out.write("----------------------------------------------");
      out.newLine();
      avgReturns = avgReturns / (returnsList.size());
      avgPredict = avgPredict / (successList.size());

      out.write("Average returns across all stocks is " + avgReturns + "%.");
      out.newLine();
      out.write("Average prediction rate across all stocks is " + avgPredict + "%.");
      out.newLine();
      out.close();
    } catch (Exception e) { // Catch exception if any
      e.printStackTrace();
      System.err.println("Error: " + e.getStackTrace() + e.getCause());
    }
  }