public int callMethod(int method, String resultVar, boolean ignoreSoapFault) {
   String user = DnUtil.getFirstDnPart(getOrganizationalUser());
   traceInfo("sending request: ", method);
   MethodCache caller = getBaseConnector().responseCache;
   Monitor mon1 = MonitorFactory.start("OutgoingCall:" + NomUtil.getUniversalName(method));
   Monitor mon2 = MonitorFactory.start("AllOutgoingCalls");
   Monitor monu1 =
       MonitorFactory.start(
           "OutgoingCallForUser:"******":" + NomUtil.getUniversalName(method));
   Monitor monu2 = MonitorFactory.start("AllOutgoingCallsForUser:"******"CALL", this, startTime, method, succes);
     mon1.stop();
     mon2.stop();
     monu1.stop();
     monu2.stop();
   }
 }
Esempio n. 2
0
  /**
   * task method comment.
   *
   * @param request javax.servlet.http.HttpServletRequest
   * @param response javax.servlet.http.HttpServletResponse
   * @param session javax.servlet.http.HttpSession
   * @param rtbUser RtbUser
   * @throws Exception
   */
  public void task(
      HttpServletRequest request,
      HttpServletResponse response,
      HttpSession session,
      RtbUser rtbUser)
      throws Exception {
    String jsp = "";
    Monitor jspMon = null;
    Monitor taskMon = MonitorFactory.start(NoteEditServlet.class.getName() + ".sharedUpdateTask");

    try {
      JspAttributeContainer.put(request, "whichtab", "");
      // update a note
      jsp = NoteEditShared.sharedUpdateTask(request, response, rtbUser, session);
      jspMon = MonitorFactory.start(NoteEditServlet.class.getName() + ".call" + jsp);
      JamonSessionUtil.monitorSession(
          request.getRequestURI(),
          RTB_SUMMARY_OBJECT,
          "NoteEditServlet",
          (RtbSummary) session.getAttribute(RTB_SUMMARY_OBJECT));
      JamonSessionUtil.monitorSession(
          request.getRequestURI(),
          RTB_SPEC_TOPICS_EXCLUSIONS_OBJECT,
          "NoteEditServlet",
          (RtbSpecialTopicsExclusions) session.getAttribute(RTB_SPEC_TOPICS_EXCLUSIONS_OBJECT));
      JamonSessionUtil.monitorSession(
          request.getRequestURI(),
          RTB_SPEC_TOPICS_NO_EXCLUSIONS_OBJECT,
          "NoteEditServlet",
          (RtbSpecialTopicsNoExclusions)
              session.getAttribute(RTB_SPEC_TOPICS_NO_EXCLUSIONS_OBJECT));
      JamonSessionUtil.monitorSession(
          request.getRequestURI(),
          RTB_SPEC_TOPICS_RPO_PROVIDERS_OBJECT,
          "NoteEditServlet",
          (RtbSpecialTopicsRpoProviders)
              session.getAttribute(RTB_SPEC_TOPICS_RPO_PROVIDERS_OBJECT));
      JamonSessionUtil.monitorSession(
          request.getRequestURI(),
          RTB_SPEC_TOPICS_SELECTED_OBJECT,
          "NoteEditServlet",
          (RtbSpecialTopicsSelected) session.getAttribute(RTB_SPEC_TOPICS_SELECTED_OBJECT));
      callJsp(jsp, request, response);
    } finally {
      taskMon.stop();
      jspMon.stop();
    }
  }
  @Override
  public boolean execute(Context context) throws Exception {
    boolean result = ERROR;

    Monitor monitor = MonitorFactory.start(COMMAND);

    try {
      super.execute(context);
      GtfsImporter importer = (GtfsImporter) context.get(PARSER);
      if (importer != null) {
        importer.dispose();
      }
      GtfsValidationReporter gtfsValidationReporter =
          (GtfsValidationReporter) context.get(GTFS_REPORTER);
      if (gtfsValidationReporter != null) {
        gtfsValidationReporter.dispose();
      }

      result = SUCCESS;

    } catch (Exception e) {
      log.error(e, e);
      throw e;
    } finally {
      log.info(Color.MAGENTA + monitor.stop() + Color.NORMAL);
    }

    return result;
  }
  @Override
  public void process(Exchange exchange) throws Exception {
    LOG.info(
        "* " + message + " counter=" + (counter++) + ", exchangeId=" + exchange.getExchangeId());
    MonitorFactory.add("camel." + message + ": " + getClass().getCanonicalName(), "count", 1);
    // List<MessageHistory> history = exchange.getProperty(Exchange.MESSAGE_HISTORY, List.class);
    // LOG.info("* "+history);

    // useful methods
    //  exchange.getProperties();
    //  exchange.getIn() - message
  }
// TODO-01: Annotate class with JMX annotation to export the bean with name
// "statistics:name=monitorFactory" as well as methods and attributes
public class JamonMonitorFactory implements MonitorFactory, GlobalMonitorStatistics {

  private com.jamonapi.MonitorFactoryInterface monitorFactory =
      com.jamonapi.MonitorFactory.getFactory();

  public Monitor start(String name) {
    JamonMonitor monitor = new JamonMonitor(monitorFactory.start(name));
    return monitor;
  }

  public long getCallsCount() {
    return (long) getMonitors().getHits();
  }

  public long getTotalCallTime() {
    return (long) getMonitors().getTotal();
  }

  public Date getLastAccessTime() {
    return getMonitors().getLastAccess();
  }

  public MonitorComposite getMonitors() {
    return monitorFactory.getRootMonitor();
  }

  public long averageCallTime(String methodName) {
    return (long) monitorFactory.getMonitor(methodName, "ms.").getAvg();
  }

  public long callCount(String methodName) {
    return (long) monitorFactory.getMonitor(methodName, "ms.").getHits();
  }

  public long lastCallTime(String methodName) {
    return (long) monitorFactory.getMonitor(methodName, "ms.").getLastValue();
  }

  public long maximumCallTime(String methodName) {
    return (long) monitorFactory.getMonitor(methodName, "ms.").getMax();
  }

  public long minimumCallTime(String methodName) {
    return (long) monitorFactory.getMonitor(methodName, "ms.").getMin();
  }

  public long totalCallTime(String methodName) {
    return (long) monitorFactory.getMonitor(methodName, "ms.").getTotal();
  }
}
Esempio n. 6
0
 public String createQuery(Set<String> individuals, String aboxfilter) {
   Monitor monABoxQueryGeneration = MonitorFactory.getTimeMonitor("ABox query generator").start();
   StringBuilder builder = new StringBuilder();
   builder.append("PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n");
   builder.append("CONSTRUCT {?s ?p ?o  } ");
   builder.append("{ ?s ?p ?o . ");
   builder.append(makeInFilter("?s", individuals));
   if (aboxfilter != null) {
     builder.append(aboxfilter);
   }
   builder.append("FILTER ( (?p!=rdf:type))");
   builder.append("}");
   monABoxQueryGeneration.stop();
   return builder.toString();
 }
  /**
   * Returns an url for the test of the EXTERNAL engine.
   *
   * @param objLabel the logical label of the document (gets from the template file)
   * @param sessionContainer session object
   * @param requestSB request object
   * @return String the complete url. It use this format: <code_error>|<url>. If there is an error
   *     during the execution <code_error> is valorized and url is null, else it is null and the url
   *     is complete.
   */
  public static String getEngineTestUrl(
      String objLabel, SessionContainer sessionContainer, SourceBean requestSB) {
    logger.debug("IN");

    Monitor monitor =
        MonitorFactory.start("spagobi.engines.DocumentCompositionUtils.getEngineTestUrl");

    String baseUrlReturn = "";
    String urlReturn = "";

    if (objLabel == null || objLabel.equals("")) {
      logger.error("Object Label is null: cannot get engine's url.");
      return "1008|";
    }

    try {
      // get the user profile from session
      SessionContainer permSession = sessionContainer.getPermanentContainer();
      BIObject obj = DAOFactory.getBIObjectDAO().loadBIObjectByLabel(objLabel);
      if (obj == null) {
        logger.error(
            "Cannot obtain engine url. Document with label "
                + objLabel
                + " doesn't exist into database.");
        List l = new ArrayList();
        l.add(objLabel);
        throw new EMFUserError(EMFErrorSeverity.ERROR, "1005", l, messageBundle);
      }

      String className = obj.getEngine().getClassName();
      if (className == null || className.trim().equals("")) {
        // external engine
        baseUrlReturn = obj.getEngine().getUrl() + "Test?";
        urlReturn = baseUrlReturn;
        logger.debug("urlReturn: " + "|" + urlReturn);
      }
    } catch (Exception ex) {
      logger.error("Error while getting execution url: " + ex);
      return null;
    } finally {
      monitor.stop();
    }

    logger.debug("OUT");

    return "|" + urlReturn;
  }
 public String getDocumentAnalyticalDriversJSON(
     String token, String user, Integer id, String language, String country) {
   logger.debug("IN");
   Monitor monitor = MonitorFactory.start("spagobi.service.sbidocument.getDocumentParametersJSON");
   try {
     validateTicket(token, user);
     this.setTenantByUserId(user);
     return supplier.getDocumentAnalyticalDriversJSON(id, language, country);
   } catch (SecurityException e) {
     logger.error("SecurityException", e);
     return null;
   } finally {
     this.unsetTenant();
     monitor.stop();
     logger.debug("OUT");
   }
 }
  /**
   * Monitors method calls using Jamon.
   *
   * @param pjp
   * @return
   * @throws Throwable
   */
  public Object monitor(ProceedingJoinPoint pjp) throws Throwable {
    if (!isEnabled()) {
      return pjp.proceed();
    }

    String methodSignature = createInvocationTraceName(pjp);
    Monitor monitor = MonitorFactory.start(methodSignature);
    try {
      return pjp.proceed();
    } finally {
      monitor.stop();
      if (monitor.getLastValue() > getLogThresholdMilliseconds()) {
        LOGGER.warn(monitor.getLastValue() + " ms. " + monitor);
      } else if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(monitor.getLastValue() + " ms. " + monitor);
      }
    }
  }
  @Override
  public boolean execute(Context context) throws Exception {
    boolean result = ERROR;

    Monitor monitor = MonitorFactory.start(COMMAND);

    try {
      context.put(REFERENTIAL, new Referential());
      if (context.get(VALIDATION) != null) context.put(VALIDATION_DATA, new ValidationData());
      result = SUCCESS;

    } catch (Exception e) {
      log.error(e, e);
      throw e;
    } finally {
      log.info(Color.MAGENTA + monitor.stop() + Color.NORMAL);
    }

    return result;
  }
  protected GTRenderingResult renderGTTemplate(Map<String, Object> args) {

    try {

      GTJavaBase gtTemplate = getGTTemplateInstance();
      Monitor monitor = MonitorFactory.start(this.name);
      try {
        gtTemplate.renderTemplate(args);
      } finally {
        monitor.stop();
      }
      return gtTemplate;

    } catch (GTTemplateNotFoundWithSourceInfo e) {
      GTTemplate t = new GTTemplate(e.templateLocation);
      t.loadSource();
      throw new TemplateNotFoundException(e.queryPath, t, e.lineNo);
    } catch (GTCompilationExceptionWithSourceInfo e) {
      GTTemplate t = new GTTemplate(e.templateLocation);
      t.loadSource();
      throw new TemplateCompilationException(t, e.oneBasedLineNo, e.specialMessage);
    } catch (GTRuntimeExceptionWithSourceInfo e) {
      GTTemplate t = new GTTemplate(e.templateLocation);
      t.loadSource();
      Throwable cause = e.getCause();
      throw new TemplateExecutionException(t, e.lineNo, cause.getMessage(), cause);
    } catch (GTRuntimeException e) {
      Throwable cause = e.getCause();
      this.loadSource();
      if (cause != null) {
        throw new TemplateExecutionException(this, 0, cause.getMessage(), cause);
      } else {
        throw new TemplateExecutionException(this, 0, e.getMessage(), e);
      }
    } catch (GTAppClassException e) {
      throw new JavaExecutionException(
          Play.classes.getApplicationClass(e.className), e.lineNo, e.getCause());
    }
  }
  @Override
  @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
  public boolean execute(Context context) throws Exception {

    boolean result = ERROR;
    Monitor monitor = MonitorFactory.start(COMMAND);

    try {
      lineDAO.truncate();
      companyDAO.truncate();
      networkDAO.truncate();
      routeSectionDAO.truncate();
      stopAreaDAO.truncate();
      timetableDAO.truncate();
      groupOfLineDAO.truncate();

      result = SUCCESS;
    } catch (Exception e) {
      log.error(e);
      throw e;
    }
    log.info(Color.MAGENTA + monitor.stop() + Color.NORMAL);
    return result;
  }
Esempio n. 13
0
  public static void invoke(Http.Request request, Http.Response response) {
    Monitor monitor = null;

    try {

      resolve(request, response);
      Method actionMethod = request.invokedMethod;

      // 1. Prepare request params
      Scope.Params.current().__mergeWith(request.routeArgs);

      // add parameters from the URI query string
      String encoding = Http.Request.current().encoding;
      Scope.Params.current()
          ._mergeWith(
              UrlEncodedParser.parseQueryString(
                  new ByteArrayInputStream(request.querystring.getBytes(encoding))));

      // 2. Easy debugging ...
      if (Play.mode == Play.Mode.DEV) {
        Class<Controller> cclass = Controller.class;
        cclass.getDeclaredField("params").set(null, Scope.Params.current());
        cclass.getDeclaredField("request").set(null, Http.Request.current());
        cclass.getDeclaredField("response").set(null, Http.Response.current());
        cclass.getDeclaredField("session").set(null, Scope.Session.current());
        cclass.getDeclaredField("flash").set(null, Scope.Flash.current());
        cclass.getDeclaredField("renderArgs").set(null, Scope.RenderArgs.current());
        cclass.getDeclaredField("routeArgs").set(null, Scope.RouteArgs.current());
        cclass.getDeclaredField("validation").set(null, Validation.current());
      }

      ControllerInstrumentation.stopActionCall();
      Play.pluginCollection.beforeActionInvocation(actionMethod);

      // Monitoring
      monitor = MonitorFactory.start(request.action + "()");

      // 3. Invoke the action
      try {
        // @Before
        handleBefores(request);

        // Action

        Result actionResult = null;
        String cacheKey = null;

        // Check the cache (only for GET or HEAD)
        if ((request.method.equals("GET") || request.method.equals("HEAD"))
            && actionMethod.isAnnotationPresent(CacheFor.class)) {
          cacheKey = actionMethod.getAnnotation(CacheFor.class).id();
          if ("".equals(cacheKey)) {
            cacheKey = "urlcache:" + request.url + request.querystring;
          }
          actionResult = (Result) play.cache.Cache.get(cacheKey);
        }

        if (actionResult == null) {
          ControllerInstrumentation.initActionCall();
          try {
            inferResult(invokeControllerMethod(actionMethod));
          } catch (Result result) {
            actionResult = result;
            // Cache it if needed
            if (cacheKey != null) {
              play.cache.Cache.set(
                  cacheKey, actionResult, actionMethod.getAnnotation(CacheFor.class).value());
            }
          } catch (InvocationTargetException ex) {
            // It's a Result ? (expected)
            if (ex.getTargetException() instanceof Result) {
              actionResult = (Result) ex.getTargetException();
              // Cache it if needed
              if (cacheKey != null) {
                play.cache.Cache.set(
                    cacheKey, actionResult, actionMethod.getAnnotation(CacheFor.class).value());
              }

            } else {
              // @Catch
              Object[] args = new Object[] {ex.getTargetException()};
              List<Method> catches =
                  Java.findAllAnnotatedMethods(Controller.getControllerClass(), Catch.class);
              ControllerInstrumentation.stopActionCall();
              for (Method mCatch : catches) {
                Class[] exceptions = mCatch.getAnnotation(Catch.class).value();
                if (exceptions.length == 0) {
                  exceptions = new Class[] {Exception.class};
                }
                for (Class exception : exceptions) {
                  if (exception.isInstance(args[0])) {
                    mCatch.setAccessible(true);
                    inferResult(invokeControllerMethod(mCatch, args));
                    break;
                  }
                }
              }

              throw ex;
            }
          }
        }

        // @After
        handleAfters(request);

        monitor.stop();
        monitor = null;

        // OK, re-throw the original action result
        if (actionResult != null) {
          throw actionResult;
        }

        throw new NoResult();

      } catch (IllegalAccessException ex) {
        throw ex;
      } catch (IllegalArgumentException ex) {
        throw ex;
      } catch (InvocationTargetException ex) {
        // It's a Result ? (expected)
        if (ex.getTargetException() instanceof Result) {
          throw (Result) ex.getTargetException();
        }
        // Re-throw the enclosed exception
        if (ex.getTargetException() instanceof PlayException) {
          throw (PlayException) ex.getTargetException();
        }
        StackTraceElement element =
            PlayException.getInterestingStackTraceElement(ex.getTargetException());
        if (element != null) {
          throw new JavaExecutionException(
              Play.classes.getApplicationClass(element.getClassName()),
              element.getLineNumber(),
              ex.getTargetException());
        }
        throw new JavaExecutionException(Http.Request.current().action, ex);
      }

    } catch (Result result) {

      Play.pluginCollection.onActionInvocationResult(result);

      // OK there is a result to apply
      // Save session & flash scope now

      Scope.Session.current().save();
      Scope.Flash.current().save();

      result.apply(request, response);

      Play.pluginCollection.afterActionInvocation();

      // @Finally
      handleFinallies(request, null);

    } catch (PlayException e) {
      handleFinallies(request, e);
      throw e;
    } catch (Throwable e) {
      handleFinallies(request, e);
      throw new UnexpectedException(e);
    } finally {
      Play.pluginCollection.onActionInvocationFinally();

      if (monitor != null) {
        monitor.stop();
      }
    }
  }
Esempio n. 14
0
 /**
  * Run the code in a new thread after a delay
  *
  * @param invocation The code to run
  * @param millis The time to wait before, in milliseconds
  * @return The future object, to know when the task is completed
  */
 public static Future<?> invoke(final Invocation invocation, long millis) {
   Monitor monitor = MonitorFactory.getMonitor("Invocation queue", "elmts.");
   monitor.add(executor.getQueue().size());
   return executor.schedule(invocation, millis, TimeUnit.MILLISECONDS);
 }
Esempio n. 15
0
 /**
  * Run the code in a new thread took from a thread pool.
  *
  * @param invocation The code to run
  * @return The future object, to know when the task is completed
  */
 public static Future<?> invoke(final Invocation invocation) {
   Monitor monitor = MonitorFactory.getMonitor("Invoker queue size", "elmts.");
   monitor.add(executor.getQueue().size());
   invocation.waitInQueue = MonitorFactory.start("Waiting for execution");
   return executor.submit(invocation);
 }
Esempio n. 16
0
 public String render(Map<String, Object> args) {
     compile();
     Binding binding = new Binding(args);
     binding.setVariable("play", new Play());
     binding.setVariable("messages", new Messages());
     binding.setVariable("lang", Lang.get());
     StringWriter writer = null;
     Boolean applyLayouts = false;
     if (!args.containsKey("out")) {
         applyLayouts = true;
         layout.set(null);
         writer = new StringWriter();
         binding.setProperty("out", new PrintWriter(writer));
         currentTemplate.set(this);
     }
     if (!args.containsKey("_body") && !args.containsKey("_isLayout") && !args.containsKey("_isInclude")) {
         layoutData.set(new HashMap<Object, Object>());
         TagContext.init();
     }
     ExecutableTemplate t = (ExecutableTemplate) InvokerHelper.createScript(compiledTemplate, binding);
     t.template = this;
     Monitor monitor = null;
     try {
         monitor = MonitorFactory.start(name);
         long start = System.currentTimeMillis();
         t.run();
         monitor.stop();
         monitor = null;
         Logger.trace("%sms to render template %s", System.currentTimeMillis() - start, name);
     } catch (NoRouteFoundException e) {
         if (e.isSourceAvailable()) {
             throw e;
         }
         throwException(e);
     } catch (PlayException e) {
         throw (PlayException) cleanStackTrace(e);
     } catch (DoBodyException e) {
         if (Play.mode == Mode.DEV) {
             compiledTemplate = null;
             BytecodeCache.deleteBytecode(name);
         }
         Exception ex = (Exception) e.getCause();
         throwException(ex);
     } catch (Throwable e) {
         if (Play.mode == Mode.DEV) {
             compiledTemplate = null;
             BytecodeCache.deleteBytecode(name);
         }
         throwException(e);
     } finally {
         if (monitor != null) {
             monitor.stop();
         }
     }
     if (applyLayouts && layout.get() != null) {
         Map<String, Object> layoutArgs = new HashMap<String, Object>(args);
         layoutArgs.remove("out");
         layoutArgs.put("_isLayout", true);
         String layoutR = layout.get().render(layoutArgs);
         return layoutR.replace("____%LAYOUT%____", writer.toString().trim());
     }
     if (writer != null) {
         return writer.toString();
     }
     return null;
 }
  /**
   * Returns an url for execute the document with the engine associated. It calls relative driver.
   *
   * @param objLabel the logical label of the document (gets from the template file)
   * @param sessionContainer session object
   * @param requestSB request object
   * @return String the complete url. It use this format: <code_error>|<url>. If there is an error
   *     during the execution <code_error> is valorized and url is null, else it is null and the url
   *     is complete.
   */
  public static String getExecutionUrl(
      String objLabel, SessionContainer sessionContainer, SourceBean requestSB) {
    logger.debug("IN");

    Monitor monitor =
        MonitorFactory.start("spagobi.engines.DocumentCompositionUtils.getExecutionUrl");

    String baseUrlReturn = "";
    String urlReturn = "";

    if (objLabel == null || objLabel.equals("")) {
      logger.error("Object Label is null: cannot get engine's url.");
      return "1008|";
    }

    try {
      // get the user profile from session
      SessionContainer permSession = sessionContainer.getPermanentContainer();
      IEngUserProfile profile =
          (IEngUserProfile) permSession.getAttribute(IEngUserProfile.ENG_USER_PROFILE);
      // get the execution role
      CoreContextManager contextManager =
          new CoreContextManager(
              new SpagoBISessionContainer(sessionContainer),
              new LightNavigatorContextRetrieverStrategy(requestSB));
      ExecutionInstance instance =
          contextManager.getExecutionInstance(ExecutionInstance.class.getName());
      String executionRole = instance.getExecutionRole();
      Integer objId = DAOFactory.getBIObjectDAO().loadBIObjectByLabel(objLabel).getId();
      BIObject obj =
          DAOFactory.getBIObjectDAO().loadBIObjectForExecutionByIdAndRole(objId, executionRole);
      //			BIObject obj =
      // DAOFactory.getBIObjectDAO().loadBIObjectForExecutionByLabelAndRole(objLabel,
      // executionRole);
      //			BIObject obj = DAOFactory.getBIObjectDAO().loadBIObjectByLabel(objLabel);
      if (obj == null) {
        logger.error(
            "Cannot obtain engine url. Document with label "
                + objLabel
                + " doesn't exist into database.");
        List l = new ArrayList();
        l.add(objLabel);
        throw new EMFUserError(EMFErrorSeverity.ERROR, "1005", l, messageBundle);
      }
      //			Engine engine = obj.getEngine();

      /*ALL CONTROLS OF COMPATIBILITY ARE REMANDED TO THE SINGLE ENGINE CALLED
      // GET THE TYPE OF ENGINE (INTERNAL / EXTERNAL) AND THE SUITABLE BIOBJECT TYPES
      Domain engineType = null;
      Domain compatibleBiobjType = null;
      try {
      	engineType = DAOFactory.getDomainDAO().loadDomainById(engine.getEngineTypeId());
      	compatibleBiobjType = DAOFactory.getDomainDAO().loadDomainById(engine.getBiobjTypeId());
      } catch (EMFUserError error) {
      	logger.error("Error retrieving document's engine information", error);
      	return "1009|";
      } catch (Exception error) {
      	logger.error("Error retrieving document's engine information", error);
      	return "1009|";
      }

      String compatibleBiobjTypeCd = compatibleBiobjType.getValueCd();
      String biobjTypeCd = obj.getBiObjectTypeCode();

      // CHECK IF THE BIOBJECT IS COMPATIBLE WITH THE TYPES SUITABLE FOR THE ENGINE

      if (!compatibleBiobjTypeCd.equalsIgnoreCase(biobjTypeCd)) {
      	// the engine document type and the biobject type are not compatible
      	logger.error("Engine cannot execute input document type: " +
      			"the engine " + engine.getName() + " can execute '" + compatibleBiobjTypeCd + "' type documents " +
      			"while the input document is a '" + biobjTypeCd + "'.");
      	Vector params = new Vector();
      	params.add(engine.getName());
      	params.add(compatibleBiobjTypeCd);
      	params.add(biobjTypeCd);
      	//errorHandler.addError(new EMFUserError(EMFErrorSeverity.ERROR, 2002, params));
      	return "2002|";
      }
       */
      // IF USER CAN'T EXECUTE THE OBJECT RETURN
      // if (!ObjectsAccessVerifier.canSee(obj, profile)) return "1010|";

      // get object configuration
      DocumentCompositionConfiguration docConfig = null;
      docConfig = (DocumentCompositionConfiguration) contextManager.get("docConfig");

      Document document = null;
      // get correct document configuration
      List lstDoc = docConfig.getLabelsArray();
      boolean foundDoc = false;
      for (int i = 0; i < lstDoc.size(); i++) {
        document = (Document) docConfig.getDocument((String) lstDoc.get(i));
        if (document != null) {
          if (!obj.getLabel().equalsIgnoreCase(document.getSbiObjLabel())) continue;
          else {
            foundDoc = true;
            break;
          }
        }
      }
      if (!foundDoc) {
        List l = new ArrayList();
        l.add(obj.getLabel());
        EMFUserError userError = new EMFUserError(EMFErrorSeverity.ERROR, 1079, l);
        logger.error(
            "The object with label " + obj.getLabel() + " hasn't got a document into template");
        return "1002|";
      }

      String className = obj.getEngine().getClassName();
      if ((className == null || className.trim().equals(""))
          && (document.getSnapshot() == null || !document.getSnapshot())) {
        // external engine
        // baseUrlReturn = obj.getEngine().getUrl() + "?";
        baseUrlReturn = obj.getEngine().getUrl();
        if (baseUrlReturn.indexOf("?") < 0) baseUrlReturn += "?";
        String driverClassName = obj.getEngine().getDriverName();
        IEngineDriver aEngineDriver = (IEngineDriver) Class.forName(driverClassName).newInstance();
        Map mapPars = aEngineDriver.getParameterMap(obj, profile, executionRole);
        String id = (String) requestSB.getAttribute("vpId");
        if (id != null) {
          IViewpointDAO VPDAO = DAOFactory.getViewpointDAO();
          Viewpoint vp = VPDAO.loadViewpointByID(new Integer(id));
          String[] vpParameters = vp.getVpValueParams().split("%26");
          if (vpParameters != null) {
            for (int i = 0; i < vpParameters.length; i++) {
              String param = (String) vpParameters[i];
              String name = param.substring(0, param.indexOf("%3D"));
              String value = param.substring(param.indexOf("%3D") + 3);
              if (mapPars.get(name) != null) {
                mapPars.remove(name);
                mapPars.put(name, value);
              } else mapPars.put(name, value);
            }
          }
        }
        mapPars.put(SpagoBIConstants.SBI_CONTEXT, GeneralUtilities.getSpagoBiContext());
        mapPars.put(SpagoBIConstants.SBI_HOST, GeneralUtilities.getSpagoBiHost());
        UUIDGenerator uuidGen = UUIDGenerator.getInstance();
        UUID uuidObj = uuidGen.generateRandomBasedUUID();
        String executionId = uuidObj.toString();
        executionId = executionId.replaceAll("-", "");
        mapPars.put("SBI_EXECUTION_ID", executionId);
        mapPars.put("EXECUTION_CONTEXT", "DOCUMENT_COMPOSITION");
        // Auditing
        AuditManager auditManager = AuditManager.getInstance();
        Integer executionAuditId =
            auditManager.insertAudit(
                instance.getBIObject(),
                null,
                profile,
                executionRole,
                instance.getExecutionModality());

        // adding parameters for AUDIT updating
        if (executionAuditId != null) {
          mapPars.put(AuditManager.AUDIT_ID, executionAuditId.toString());
        }

        Set parKeys = mapPars.keySet();
        Iterator parKeysIter = parKeys.iterator();
        do {
          if (!parKeysIter.hasNext()) {
            break;
          }
          String parkey = parKeysIter.next().toString();
          String parvalue = mapPars.get(parkey).toString();
          urlReturn =
              (new StringBuilder())
                  .append(urlReturn)
                  .append("&")
                  .append(parkey)
                  .append("=")
                  .append(parvalue)
                  .toString();
        } while (true);

      } else {

        // internal engine
        baseUrlReturn =
            GeneralUtilities.getSpagoBIProfileBaseUrl(profile.getUserUniqueIdentifier().toString());
        urlReturn = "&" + ObjectsTreeConstants.OBJECT_LABEL + "=" + objLabel;
        // identity string for context
        UUIDGenerator uuidGen = UUIDGenerator.getInstance();
        UUID uuid = uuidGen.generateRandomBasedUUID();
        urlReturn += "&" + LightNavigationManager.LIGHT_NAVIGATOR_ID + "=" + uuid.toString();
        if (document.getSnapshot() != null && document.getSnapshot()) {
          Snapshot snap = DAOFactory.getSnapshotDAO().getLastSnapshot(objId);
          if (snap != null) {
            urlReturn += "&SNAPSHOT_ID=" + snap.getId();
          }
          urlReturn += "&OBJECT_ID=" + objId;
          urlReturn += "&ACTION_NAME=GET_SNAPSHOT_CONTENT";
        } else {
          urlReturn +=
              "&PAGE=ExecuteBIObjectPage&"
                  + SpagoBIConstants.IGNORE_SUBOBJECTS_VIEWPOINTS_SNAPSHOTS
                  + "=true";
          urlReturn +=
              "&" + ObjectsTreeConstants.MODALITY + "=" + SpagoBIConstants.DOCUMENT_COMPOSITION;
        }
      }

      // I add passing of SBI_LANGUAGE and SBI_COUNTRY
      // on session container they are called AF_COUNTRY and AF_LANGUAGE
      SessionContainer sContainer = sessionContainer.getPermanentContainer();
      if (sContainer != null) {
        Object language = sContainer.getAttribute("AF_LANGUAGE");
        Object country = sContainer.getAttribute("AF_COUNTRY");
        if (language == null) {
          language = sContainer.getAttribute("SBI_LANGUAGE");
        }
        if (country == null) {
          country = sContainer.getAttribute("SBI_COUNTRY");
        }
        if (language != null && country != null) {
          urlReturn +=
              "&"
                  + SpagoBIConstants.SBI_LANGUAGE
                  + "="
                  + language
                  + "&"
                  + SpagoBIConstants.SBI_COUNTRY
                  + "="
                  + country;
        }
      }

      urlReturn += "&" + SpagoBIConstants.ROLE + "=" + executionRole;
      urlReturn += getParametersUrl(obj, document, requestSB, instance);
      // adds '|' char for management error into jsp if is necessary.

      urlReturn = baseUrlReturn + urlReturn;

      logger.debug("urlReturn: " + "|" + urlReturn);
    } catch (Exception ex) {
      logger.error("Error while getting execution url: " + ex);
      return null;
    } finally {
      monitor.stop();
    }

    logger.debug("OUT");

    return "|" + urlReturn;
  }
Esempio n. 18
0
  @SuppressWarnings({"unchecked", "rawtypes"})
  @Override
  public void service(SourceBean request, SourceBean response) {

    String dataSetLabel;
    String callback;
    String locale;
    Integer start;
    Integer limit;
    Integer limitSS; // for pagination server side
    Integer rowsLimit;
    Boolean memoryPagination;

    IDataSet dataSet;
    IDataStore dataStore;

    logger.debug("IN");
    Monitor monitor = MonitorFactory.start("SpagoBI_Console.GetConsoleDataAction.service");

    try {
      super.service(request, response);
      ConsoleEngineInstance consoleEngineInstance = getConsoleEngineInstance();

      dataSetLabel = getAttributeAsString(DATASET_LABEL);
      logger.debug("Parameter [" + DATASET_LABEL + "] is equals to [" + dataSetLabel + "]");
      Assert.assertTrue(
          !StringUtilities.isEmpty(dataSetLabel),
          "Parameter [" + DATASET_LABEL + "] cannot be null or empty");

      callback = getAttributeAsString(CALLBACK);
      logger.debug("Parameter [" + CALLBACK + "] is equals to [" + callback + "]");

      locale = getAttributeAsString(LOCALE);
      logger.debug("Parameter [" + LOCALE + "] is equals to [" + locale + "]");

      memoryPagination = getAttributeAsBoolean(MEMORY_PAGINATION);
      logger.debug("Parameter [" + MEMORY_PAGINATION + "] is equals to [" + memoryPagination + "]");

      limitSS = (getAttributeAsInteger(LIMIT_SS) == null) ? -1 : getAttributeAsInteger(LIMIT_SS);
      logger.debug("Parameter [" + LIMIT_SS + "] is equals to [" + LIMIT_SS + "]");

      rowsLimit =
          (getAttributeAsInteger(ROWS_LIMIT) == null) ? -1 : getAttributeAsInteger(ROWS_LIMIT);
      logger.debug("Parameter [" + ROWS_LIMIT + "] is equals to [" + rowsLimit + "]");

      start = (getAttributeAsInteger(START) == null) ? 0 : getAttributeAsInteger(START);
      logger.debug("Parameter [" + START + "] is equals to [" + start + "]");

      limit = (getAttributeAsInteger(LIMIT) == null) ? -1 : getAttributeAsInteger(LIMIT);
      logger.debug("Parameter [" + LIMIT + "] is equals to [" + limit + "]");

      dataSet = null;
      try {
        dataSet = getDataSet(dataSetLabel);
      } catch (Throwable t) {
        throw new SpagoBIServiceException(
            "Impossible to find a dataset whose label is [" + dataSetLabel + "]", t);
      }
      Assert.assertNotNull(
          dataSet, "Impossible to find a dataset whose label is [" + dataSetLabel + "]");
      Map params = consoleEngineInstance.getAnalyticalDrivers();
      params.put(LOCALE, locale);
      dataSet.setParamsMap(params);

      UserProfile userProfile = (UserProfile) this.getEnv().get(EngineConstants.ENV_USER_PROFILE);
      dataSet.setUserProfileAttributes(UserProfileUtils.getProfileAttributes(userProfile));
      if (dataSet instanceof AbstractDataSet) {
        AbstractDataSet ads = (AbstractDataSet) dataSet;
        ads.setUserProfile(userProfile);
      }

      // gets the max number of rows for the table
      // String strRowLimit =
      // ConsoleEngineConfig.getInstance().getProperty("CONSOLE-TABLE-ROWS-LIMIT");
      // rowsLimit = (strRowLimit == null)? -1 : Integer.parseInt(strRowLimit);
      Monitor monitorLD =
          MonitorFactory.start("SpagoBI_Console.GetConsoleDataAction.service.LoadData");
      if (!memoryPagination) {
        rowsLimit = -1; // serverSide
        limit = limitSS;
      }
      int totalResults = this.getDataSetTotalResult(dataSet);
      if (totalResults != -1) {
        // total results was already loaded, no need to recalculate it
        dataSet.setCalculateResultNumberOnLoad(false);
      }

      dataSet.loadData(start, limit, rowsLimit);

      monitorLD.stop();
      dataStore = dataSet.getDataStore();
      Assert.assertNotNull(
          dataStore,
          "The dataStore returned by loadData method of the class ["
              + dataSet.getClass().getName()
              + "] cannot be null");

      Object resultNumber = dataStore.getMetaData().getProperty("resultNumber");
      if (resultNumber != null) {
        this.setDataSetTotalResult(dataSet, (Integer) resultNumber);
      }

      JSONObject results = new JSONObject();
      try {
        JSONDataWriter writer = new JSONDataWriter();
        // write id property only if is a NGSI rest dataset, to not broke previous logic
        if (dataSet instanceof RESTDataSet && ((RESTDataSet) dataSet).isNgsi()) {
          writer.setUseIdProperty(true);
          // writer.setAdjust(true);
        }

        if (totalResults != -1) {
          // if total result was previously loaded, set this information into dataStore
          dataStore.getMetaData().setProperty("resultNumber", totalResults);
        }

        resultNumber = dataStore.getMetaData().getProperty("resultNumber");
        if (resultNumber == null) {
          dataStore
              .getMetaData()
              .setProperty("resultNumber", new Integer((int) dataStore.getRecordsCount()));
        }
        JSONObject dataSetJSON = (JSONObject) writer.write(dataStore);
        results = dataSetJSON;
      } catch (Throwable e) {
        throw new SpagoBIServiceException("Impossible to serialize datastore", e);
      }

      try {
        writeBackToClient(new JSONSuccess(results, callback));
      } catch (IOException e) {
        throw new SpagoBIServiceException("Impossible to write back the responce to the client", e);
      }
    } catch (Throwable t) {
      throw SpagoBIEngineServiceExceptionHandler.getInstance()
          .getWrappedException(getActionName(), getEngineInstance(), t);
    } finally {
      monitor.stop();
      logger.debug("OUT");
    }
  }
  //    @Test(enabled = true, description = "this should only be executed manually in IDE")
  @Ignore
  @Test
  @PerformanceProfiling
  public void pushTranslation() {
    EntityMaker entityMaker =
        EntityMakerBuilder.builder()
            .addFieldOrPropertyMaker(
                HProject.class, "sourceViewURL", FixedValueMaker.EMPTY_STRING_MAKER)
            .build();
    HProjectIteration iteration = entityMaker.makeAndPersist(getEm(), HProjectIteration.class);
    HLocale srcLocale = createAndPersistLocale(LocaleId.EN_US, getEm());
    HLocale transLocale = createAndPersistLocale(LocaleId.DE, getEm());

    String versionSlug = iteration.getSlug();
    String projectSlug = iteration.getProject().getSlug();

    HDocument document = new HDocument("message", ContentType.PO, srcLocale);
    document.setProjectIteration(iteration);
    getEm().persist(document);
    getEm().flush();

    // adjust this number to suit testing purpose
    int numOfTextFlows = 50;
    int numOfTextFlowsHavingTarget =
        createSourceAndSomeTargets(document, transLocale, numOfTextFlows);
    getEm().getTransaction().commit();
    getEm().getTransaction().begin();

    Long targetsCountBefore =
        getEm()
            .createQuery("select count(*) from HTextFlowTarget where locale = :locale", Long.class)
            .setParameter("locale", transLocale)
            .getSingleResult();
    Assertions.assertThat(targetsCountBefore).isEqualTo(numOfTextFlowsHavingTarget);

    // ============ add targets =========
    TranslationsResource translations = new TranslationsResource();
    translations.setRevision(1);
    for (int i = 0; i < numOfTextFlows; i++) {
      addSampleTranslation(translations, "res" + i);
    }
    Monitor mon = MonitorFactory.start("");
    log.info("==== start translateAllInDoc");
    service.translateAllInDoc(
        projectSlug,
        versionSlug,
        document.getDocId(),
        transLocale.getLocaleId(),
        translations,
        extensions,
        MergeType.AUTO,
        false,
        TranslationSourceType.API_UPLOAD);
    log.info("==== stop translateAllInDoc: {}", mon.stop());
    getEm().getTransaction().commit();
    getEm().getTransaction().begin();

    Long targetsCount =
        getEm()
            .createQuery("select count(*) from HTextFlowTarget where locale = :locale", Long.class)
            .setParameter("locale", transLocale)
            .getSingleResult();
    Assertions.assertThat(targetsCount).isEqualTo(numOfTextFlows);

    List<HTextFlowTargetHistory> histories =
        getEm()
            .createQuery("from HTextFlowTargetHistory", HTextFlowTargetHistory.class)
            .getResultList();
    Assertions.assertThat(histories).hasSize(numOfTextFlowsHavingTarget);
  }
Esempio n. 20
0
  public static void main(String[] args) {

    Monitor timer = MonitorFactory.start("totaltime");
    for (int i = 1; i <= 10; i++) {
      System.out.println(MonitorFactory.add("NIC.bytes.sent", "bytes", i * 1000));
      System.out.println(MonitorFactory.add("negativetest", "neg", -1000.0 * i));
    }

    System.out.println("");
    Monitor m = null;
    m = MonitorFactory.start("purchasesTimeTestNoRange");

    for (int i = 1; i <= 1000000; i++) MonitorFactory.add("purchasesNoRange", "dollars", 1000.0);

    System.out.println("purchasesTimeTestNoRange=" + m.stop().getTotal());

    m = MonitorFactory.start("testTimerTimeTest");
    for (int i = 1; i <= 1000000; i++) MonitorFactory.start("testTimer").stop();

    System.out.println("testTimerTimeTest=" + m.stop().getTotal());
    for (int i = -5; i <= 20; i++) {
      MonitorFactory.add("purchases", "dollars", i * 50);
    }

    System.out.println("");

    System.out.println(MonitorFactory.add("NIC.bytes.received", "bytes", 250.0));
    System.out.println(MonitorFactory.add("NIC.bytes.received", "bytes", 250.0));

    timer.stop();

    for (int i = -5; i < 25; i++) MonitorFactory.add("timetest", "ms.", i * 5);

    System.out.println(MonitorFactory.getMonitor("purchases", "dollars").getHits());
    System.out.println(MonitorFactory.getTimeMonitor("testTimer").getHits());
    // case sensitive so won't print
    System.out.println(MonitorFactory.getTimeMonitor("testtimer").getHits());
    System.out.println("Total time=" + timer.getTotal());

    MonitorFactory.reset();
    MonitorFactory.setRangeDefault("dollars", getTestHolder());
    m = MonitorFactory.start("purchasesTimeTestRange");
    for (int i = 1; i <= 1000000; i++) MonitorFactory.add("purchasesRange", "dollars", 1000.0);

    System.out.println("purchasesTimeTestRange=" + m.stop().getTotal());
    Object[][] data = null;
    MonitorFactory.setRangeDefault("bytes", getTestHolder());
    MonitorFactory.setRangeDefault("cents", getTestHolder());
    MonitorFactory.setRangeDefault("minutes", getTestHolder());
    MonitorFactory.setRangeDefault("MB", getTestHolder());
    MonitorFactory.setRangeDefault("KB", getTestHolder());
    MonitorFactory.setRangeDefault("points", getTestHolder());

    String[] header = MonitorFactory.getComposite("ms.").getHeader();

    data = MonitorFactory.getComposite("ms.").getData();
    header = MonitorFactory.getComposite("ms.").getBasicHeader();

    data = MonitorFactory.getComposite("ms.").getBasicData();
    header = MonitorFactory.getComposite("ms.").getDisplayHeader();

    data = MonitorFactory.getComposite("ms.").getDisplayData();
    MonitorFactory.getComposite("ms.").disable();

    header = MonitorFactory.getComposite("ms.").getHeader();
    data = MonitorFactory.getComposite("ms.").getData();

    System.out.println("header length=" + header.length + ", data length=" + data.length);
    System.out.println("JAMon Version=" + MonitorFactory.getVersion());
  }