org.perf4j.StopWatch Java Examples

The following examples show how to use org.perf4j.StopWatch. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractViewRepository.java    From cuba with Apache License 2.0 6 votes vote down vote up
protected void init() {
    StopWatch initTiming = new Slf4JStopWatch("ViewRepository.init." + getClass().getSimpleName());

    storage.clear();
    readFileNames.clear();

    String configName = AppContext.getProperty("cuba.viewsConfig");
    if (!StringUtils.isBlank(configName)) {
        Element rootElem = DocumentHelper.createDocument().addElement("views");

        StringTokenizer tokenizer = new StringTokenizer(configName);
        for (String fileName : tokenizer.getTokenArray()) {
            addFile(rootElem, fileName);
        }

        viewLoader.checkDuplicates(rootElem);

        for (Element viewElem : Dom4j.elements(rootElem, "view")) {
            deployView(rootElem, viewElem, new HashSet<>());
        }
    }

    initTiming.stop();
}
 
Example #2
Source File: WindowLoader.java    From cuba with Apache License 2.0 6 votes vote down vote up
@Deprecated
protected void loadCompanions(Window resultComponent, Element element) {
    Screen controller = resultComponent.getFrameOwner();
    if (controller instanceof AbstractWindow) {
        Element companionsElem = element.element("companions");
        if (companionsElem != null) {
            StopWatch companionStopWatch = createStopWatch(ScreenLifeCycle.COMPANION, controller.getId());

            Object companion = initCompanion(companionsElem, (AbstractWindow) controller);

            companionStopWatch.stop();

            if (companion != null) {
                getComponentContext().addInjectTask((c, w) -> {
                    CompanionDependencyInjector cdi =
                            new CompanionDependencyInjector((LegacyFrame) controller, companion);
                    cdi.setBeanLocator(beanLocator);
                    cdi.inject();
                });
            }
        }
    }
}
 
Example #3
Source File: FragmentLoader.java    From cuba with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(ComponentContext context, Frame frame) {
    String loggingId = context.getFullFrameId();
    try {
        if (fragment.getFrameOwner() instanceof AbstractFrame) {
            Element companionsElem = element.element("companions");
            if (companionsElem != null) {
                StopWatch companionStopWatch = createStopWatch(ScreenLifeCycle.COMPANION, loggingId);

                initCompanion(companionsElem, (AbstractFrame) fragment.getFrameOwner());

                companionStopWatch.stop();
            }
        }
    } catch (Throwable e) {
        throw new RuntimeException("Unable to init frame companion", e);
    }
}
 
Example #4
Source File: CollectionDatasourceImpl.java    From cuba with Apache License 2.0 6 votes vote down vote up
/**
 * Load data from middleware into {@link #data} field.
 * <p>In case of error sets {@link #dataLoadError} field to the exception object.</p>
 * @param params    datasource parameters, as described in {@link CollectionDatasource#refresh(java.util.Map)}
 */
protected void loadData(Map<String, Object> params) {
    Security security = AppBeans.get(Security.NAME);
    if (!security.isEntityOpPermitted(metaClass, EntityOp.READ)) {
        return;
    }

    String tag = getLoggingTag("CDS");
    StopWatch sw = new Slf4JStopWatch(tag, LoggerFactory.getLogger(UIPerformanceLogger.class));

    if (needLoading()) {
        LoadContext context = beforeLoadData(params);
        if (context == null) {
            return;
        }
        try {
            Collection<T> entities = dataSupplier.loadList(context);

            afterLoadData(params, context, entities);
        } catch (Throwable e) {
            dataLoadError = e;
        }
    }

    sw.stop();
}
 
Example #5
Source File: AbstractTreeDatasource.java    From cuba with Apache License 2.0 6 votes vote down vote up
@Override
protected void loadData(Map<String, Object> params) {
    String tag = getLoggingTag("TDS");
    StopWatch sw = new Slf4JStopWatch(tag, LoggerFactory.getLogger(UIPerformanceLogger.class));

    clear();

    this.tree = loadTree(params);

    Map<K, Node<T>> targetNodes = new HashMap<>();
    if (tree != null) {
        for (Node<T> node : tree.toList()) {
            final T entity = node.getData();
            final K id = entity.getId();

            data.put(id, entity);
            attachListener(entity);

            targetNodes.put(id, node);
        }
    }

    this.nodes = targetNodes;

    sw.stop();
}
 
Example #6
Source File: WebJarResourceResolver.java    From cuba with Apache License 2.0 6 votes vote down vote up
@EventListener
@Order(Events.HIGHEST_PLATFORM_PRECEDENCE + 200)
protected void init(AppContextInitializedEvent event) {
    StopWatch stopWatch = new Slf4JStopWatch("WebJARs");
    try {
        ApplicationContext applicationContext = event.getApplicationContext();

        ClassLoader classLoader = applicationContext.getClassLoader();

        log.debug("Scanning WebJAR resources in {}", classLoader);

        scanResources(applicationContext);

        log.debug("Loaded {} WebJAR paths", mapping.size());
    } catch (IOException e) {
        throw new RuntimeException("Unable to load WebJAR resources", e);
    } finally {
        stopWatch.stop();
    }
}
 
Example #7
Source File: ClusterManager.java    From cuba with Apache License 2.0 6 votes vote down vote up
@Override
public String printSharedStateStat() {
    StringBuilder clusterStateStat = new StringBuilder();
    for (Map.Entry<String, ClusterListener> entry : listeners.entrySet()) {
        byte[] data;
        StopWatch sw = new StopWatch();
        try {
            data = entry.getValue().getState();
        } finally {
            sw.stop();
        }
        clusterStateStat
                .append(String.format("State: %s, size: %s bytes, serialize time: %s ms\n",
                        entry.getKey(), data != null ? data.length : -1, sw.getElapsedTime()));
    }
    return clusterStateStat.toString();
}
 
Example #8
Source File: GenericAsyncCoalescingStatisticsAppender.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public StopWatch next() {
   if (this.timeSliceOver) {
      this.timeSliceOver = false;
      return null;
   } else {
      if (this.nextStopWatch == null) {
         this.nextStopWatch = this.getNext();
         if (this.nextStopWatch == null) {
            throw new NoSuchElementException();
         }
      }

      StopWatch retVal = this.nextStopWatch;
      this.nextStopWatch = null;
      return retVal;
   }
}
 
Example #9
Source File: CommonJobBean.java    From dubai with MIT License 6 votes vote down vote up
@Override
protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
    StopWatch stopWatch = new LoggingStopWatch();

    ApplicationContext applicationContext = getApplicationContext(jobExecutionContext);
    String realJobBeanName = getRealJobBeanName(jobExecutionContext);
    Job realJob = (Job) applicationContext.getBean(realJobBeanName);

    try {
        realJob.execute(jobExecutionContext);
    } catch (Exception e) {
        logger.error(String.format("Error happened when execute job, realJobBeanName: %s, jobDataMap:[%s]", realJobBeanName, buildJobDataMap(jobExecutionContext)), e);
    }

    stopWatch.stop(String.format("Job executed, realJobBeanName: %s, jobDataMap:[%s]", realJobBeanName, buildJobDataMap(jobExecutionContext)));
}
 
Example #10
Source File: StopWatchLogIterator.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public StopWatch next() {
   if (Boolean.FALSE.equals(this.hasNext)) {
      throw new NoSuchElementException();
   } else {
      if (this.nextStopWatch == null) {
         this.nextStopWatch = this.getNext();
         if (this.nextStopWatch == null) {
            this.hasNext = false;
            throw new NoSuchElementException();
         }
      }

      StopWatch retVal = this.nextStopWatch;
      this.hasNext = null;
      this.nextStopWatch = null;
      return retVal;
   }
}
 
Example #11
Source File: JavaClassLoader.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public Class loadClass(final String fullClassName, boolean resolve) throws ClassNotFoundException {
    String containerClassName = StringUtils.substringBefore(fullClassName, "$");

    StopWatch loadingWatch = new Slf4JStopWatch("LoadClass");
    try {
        lock(containerClassName);
        Class clazz;

        //first check if there is a ".class" file in the "conf" directory
        File classFile = classFilesProvider.getClassFile(containerClassName);
        if (classFile.exists()) {
            return loadClassFromClassFile(fullClassName, containerClassName, classFile);
        }

        //then check if a ".java" source file is deployed to the "conf" directory
        if (sourceProvider.getSourceFile(containerClassName).exists()) {
            return loadClassFromJavaSources(fullClassName, containerClassName);
        }

        //default class loading
        clazz = super.loadClass(fullClassName, resolve);
        return clazz;
    } finally {
        unlock(containerClassName);
        loadingWatch.stop();
    }
}
 
Example #12
Source File: ScreenXmlLoader.java    From cuba with Apache License 2.0 5 votes vote down vote up
/**
 * Loads a descriptor.
 *
 * @param resourcePath path to the resource containing the XML
 * @param id           screen ID
 * @param params       screen parameters
 * @return root XML element
 */
public Element load(String resourcePath, String id, Map<String, Object> params) {
    StopWatch xmlLoadWatch = UIPerformanceLogger.createStopWatch(ScreenLifeCycle.XML, id);

    String template = loadTemplate(resourcePath);
    Document document = getDocument(template, params);

    xmlLoadWatch.stop();
    return document.getRootElement();
}
 
Example #13
Source File: DataImporterEmployeeTest.java    From neo4j-rdbms-import with GNU General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    FileUtils.deleteRecursively(new File(STORE_DIR));
    StopWatch watch = new StopWatch();
    Rules rules = new Rules(); // asList("titles")
    new DatabaseImporter("jdbc:mysql://localhost:3306/employees?user=root", "employees", STORE_DIR, rules).run();

    watch.lap("import");
    System.err.println(watch.stop("import", importInfo()));
}
 
Example #14
Source File: FragmentHelper.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(ComponentLoader.ComponentContext windowContext, Frame window) {
    String loggingId = getFullFrameId(this.fragment);

    StopWatch injectStopWatch = createStopWatch(ScreenLifeCycle.INJECTION, loggingId);

    FrameOwner controller = fragment.getFrameOwner();
    beanLocator.getAll(ControllerDependencyInjector.class).values()
            .forEach(uiControllerDependencyInjector ->
                    uiControllerDependencyInjector.inject(new ControllerDependencyInjector.InjectionContext(controller, options))
            );
    injectStopWatch.stop();
}
 
Example #15
Source File: ValueCollectionDatasourceImpl.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
protected void loadData(Map<String, Object> params) {
    String tag = getLoggingTag("VDS");
    StopWatch sw = new Slf4JStopWatch(tag, LoggerFactory.getLogger(UIPerformanceLogger.class));

    delegate.loadData(params);

    sw.stop();
}
 
Example #16
Source File: ValueGroupDatasourceImpl.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
protected void loadData(Map<String, Object> params) {
    String tag = getLoggingTag("VGDS");
    StopWatch sw = new Slf4JStopWatch(tag, LoggerFactory.getLogger(UIPerformanceLogger.class));

    delegate.loadData(params);

    sw.stop();
}
 
Example #17
Source File: GroupingStatisticsIterator.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public GroupingStatisticsIterator(Iterator<StopWatch> stopWatchIterator, long timeSlice, boolean createRollupStatistics) {
   this.hasNext = null;
   this.nextGroupedTimingStatistics = null;
   this.currentGroupedTimingStatistics = new GroupedTimingStatistics();
   this.nextTimeSliceEndTime = 0L;
   this.stopWatchIterator = stopWatchIterator;
   this.timeSlice = timeSlice;
   this.createRollupStatistics = createRollupStatistics;
   this.currentGroupedTimingStatistics.setCreateRollupStatistics(createRollupStatistics);
}
 
Example #18
Source File: PerformanceLogInterceptor.java    From cuba with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"UnusedDeclaration", "UnnecessaryLocalVariable"})
protected Object aroundInvoke(ProceedingJoinPoint ctx) throws Throwable {
    StopWatch stopWatch = new Slf4JStopWatch(ctx.getSignature().toShortString());
    try {
        stopWatch.start();
        Object res = ctx.proceed();
        return res;
    } finally {
        stopWatch.stop();
    }
}
 
Example #19
Source File: ValueHierarchicalDatasourceImpl.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
protected void loadData(Map<String, Object> params) {
    String tag = getLoggingTag("VHDS");
    StopWatch sw = new Slf4JStopWatch(tag, LoggerFactory.getLogger(UIPerformanceLogger.class));

    delegate.loadData(params);

    sw.stop();
}
 
Example #20
Source File: MenuItemCommands.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    userActionsLog.trace("Menu item {} triggered", item.getId());

    StopWatch sw = createStopWatch(item);

    Object beanInstance = beanLocator.get(bean);
    try {
        Method methodWithParams = MethodUtils.getAccessibleMethod(beanInstance.getClass(), beanMethod, Map.class);
        if (methodWithParams != null) {
            methodWithParams.invoke(beanInstance, params);
            return;
        }

        Method methodWithScreen = MethodUtils.getAccessibleMethod(beanInstance.getClass(), beanMethod, FrameOwner.class);
        if (methodWithScreen != null) {
            methodWithScreen.invoke(beanInstance, origin);
            return;
        }

        MethodUtils.invokeMethod(beanInstance, beanMethod, (Object[]) null);
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
        throw new RuntimeException("Unable to execute bean method", e);
    }

    sw.stop();
}
 
Example #21
Source File: DesktopTableCellEditor.java    From cuba with Apache License 2.0 5 votes vote down vote up
protected Component getCellComponent(int row) {
    Entity item = desktopAbstractTable.getTableModel().getItem(row);

    StopWatch sw = new Slf4JStopWatch("TableColumnGenerator." + desktopAbstractTable.getId());
    @SuppressWarnings("unchecked")
    com.haulmont.cuba.gui.components.Component component = columnGenerator.generateCell(item);
    sw.stop();

    Component comp;
    if (component == null) {
        comp = new JLabel("");
    } else if (component instanceof Table.PlainTextCell) {
        comp = new JLabel(((Table.PlainTextCell) component).getText());
    } else {
        if (component instanceof BelongToFrame) {
            BelongToFrame belongToFrame = (BelongToFrame) component;
            if (belongToFrame.getFrame() == null) {
                belongToFrame.setFrame(desktopAbstractTable.getFrame());
            }
        }
        component.setParent(desktopAbstractTable);

        JComponent jComposition = DesktopComponentsHelper.getComposition(component);
        jComposition.putClientProperty(CELL_EDITOR_TABLE, desktopAbstractTable.getComponent());
        jComposition.putClientProperty(CELL_COMPONENT, component);

        comp = jComposition;
    }

    cache.put(row, comp);
    return comp;
}
 
Example #22
Source File: MessagesClientImpl.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
@Nullable
protected String searchRemotely(String pack, String key, Locale locale) {
    if (!remoteSearch || !AppContext.isStarted())
        return null;

    if (log.isTraceEnabled())
        log.trace("searchRemotely: " + pack + "/" +  LocaleResolver.localeToString(locale) + "/" + key);

    StopWatch stopWatch = new Slf4JStopWatch("Messages.searchRemotely");
    try {
        String message = localizedMessageService.getMessage(pack, key, locale);
        if (key.equals(message))
            return null;
        else
            return message;
    } catch (Exception e) {
        List list = ExceptionUtils.getThrowableList(e);
        for (Object throwable : list) {
            if (throwable instanceof SocketException) {
                log.trace("searchRemotely: {}", throwable);
                return null; // silently ignore network errors
            }
        }
        throw (RuntimeException) e;
    } finally {
        stopWatch.stop();
    }
}
 
Example #23
Source File: StopWatchLogIterator.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
private StopWatch getNext() {
   String line;
   while((line = this.inputScanner.findInLine(this.stopWatchParser.getPattern())) == null && this.inputScanner.hasNextLine()) {
      this.inputScanner.nextLine();
   }

   return line != null ? this.stopWatchParser.parseStopWatchFromLogMatch(this.inputScanner.match()) : null;
}
 
Example #24
Source File: AbstractMessages.java    From cuba with Apache License 2.0 5 votes vote down vote up
protected String searchClasspath(String pack, String key, Locale locale, Locale truncatedLocale, Set<String> passedPacks) {
    StopWatch stopWatch = new Slf4JStopWatch("Messages.searchClasspath");
    try {
        String cacheKey = makeCacheKey(pack, key, locale, truncatedLocale);

        String msg = strCache.get(cacheKey);
        if (msg != null)
            return msg;

        log.trace("searchClasspath: {}", cacheKey);

        String packPath = "/" + pack.replaceAll("\\.", "/");
        while (packPath != null) {
            Properties properties = loadPropertiesFromResource(packPath, locale, truncatedLocale);
            if (properties != PROPERTIES_NOT_FOUND) {
                msg = getMessageFromProperties(pack, key, locale, truncatedLocale, properties, passedPacks);
                if (msg != null)
                    return msg;
            }
            // not found, keep searching
            int pos = packPath.lastIndexOf("/");
            if (pos < 0)
                packPath = null;
            else
                packPath = packPath.substring(0, pos);
        }
        return null;
    } finally {
        stopWatch.stop();
    }
}
 
Example #25
Source File: AbstractMessages.java    From cuba with Apache License 2.0 5 votes vote down vote up
protected String searchFiles(String pack, String key, Locale locale, Locale truncatedLocale, Set<String> passedPacks) {
    StopWatch stopWatch = new Slf4JStopWatch("Messages.searchFiles");
    try {
        String cacheKey = makeCacheKey(pack, key, locale, truncatedLocale);

        String msg = strCache.get(cacheKey);
        if (msg != null)
            return msg;

        log.trace("searchFiles: {}", cacheKey);

        String packPath = confDir + "/" + pack.replaceAll("\\.", "/");
        while (packPath != null && !packPath.equals(confDir)) {
            Properties properties = loadPropertiesFromFile(packPath, locale, truncatedLocale);
            if (properties != PROPERTIES_NOT_FOUND) {
                msg = getMessageFromProperties(pack, key, locale, truncatedLocale, properties, passedPacks);
                if (msg != null)
                    return msg;
            }
            // not found, keep searching
            int pos = packPath.lastIndexOf("/");
            if (pos < 0)
                packPath = null;
            else
                packPath = packPath.substring(0, pos);
        }
        return null;
    } finally {
        stopWatch.stop();
    }
}
 
Example #26
Source File: AbstractViewRepository.java    From cuba with Apache License 2.0 5 votes vote down vote up
protected void replaceOverridden(View replacementView) {
    StopWatch replaceTiming = new Slf4JStopWatch("ViewRepository.replaceOverridden");

    HashSet<View> checked = new HashSet<>();

    for (View view : getAllInitialized()) {
        if (!checked.contains(view)) {
            replaceOverridden(view, replacementView, checked);
        }
    }

    replaceTiming.stop();
}
 
Example #27
Source File: FoldersServiceBean.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public List<AppFolder> reloadAppFolders(List<AppFolder> folders) {
    log.debug("Reloading AppFolders {}", folders);

    StopWatch stopWatch = new Slf4JStopWatch("AppFolders");
    stopWatch.start();

    try {
        if (!folders.isEmpty()) {
            Binding binding = new Binding();
            binding.setVariable("persistence", persistence);
            binding.setVariable("metadata", metadata);
            binding.setProperty("userSession", userSessionSource.getUserSession());

            for (AppFolder folder : folders) {
                Transaction tx = persistence.createTransaction();
                try {
                    if (loadFolderQuantity(binding, folder)) {
                        tx.commit();
                    }
                } finally {
                    tx.end();
                }
            }
        }

        return folders;
    } finally {
        stopWatch.stop();
    }
}
 
Example #28
Source File: FoldersServiceBean.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public List<SearchFolder> loadSearchFolders() {
    log.debug("Loading SearchFolders");

    StopWatch stopWatch = new Slf4JStopWatch("SearchFolders");
    stopWatch.start();

    Transaction tx = persistence.createTransaction();
    try {
        EntityManager em = persistence.getEntityManager();
        MetaClass effectiveMetaClass = metadata.getExtendedEntities().getEffectiveMetaClass(SearchFolder.class);
        TypedQuery<SearchFolder> q = em.createQuery("select f from "+ effectiveMetaClass.getName() +" f " +
                "left join f.user u on u.id = ?1 " +
                "where (u.id = ?1 or u is null) " +
                "order by f.sortOrder, f.name",
                SearchFolder.class);
        q.setViewName("searchFolders");
        q.setParameter(1, userSessionSource.currentOrSubstitutedUserId());
        List<SearchFolder> list = q.getResultList();
        tx.commit();
        return list;
    } finally {
        tx.end();

        stopWatch.stop();
    }
}
 
Example #29
Source File: EmailSender.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public void sendEmail(SendingMessage sendingMessage) throws MessagingException {
    MimeMessage msg = createMimeMessage(sendingMessage);

    StopWatch sw = new Slf4JStopWatch("EmailSender.send");
    mailSender.send(msg);
    sw.stop();

    log.info("Email '{}' to '{}' has been sent successfully", msg.getSubject(), sendingMessage.getAddress());
}
 
Example #30
Source File: Scheduling.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public void processScheduledTasks(boolean onlyIfActive) {
    if (onlyIfActive && !isActive())
        return;

    log.debug("Processing scheduled tasks");
    if (schedulingStartTime == 0)
        schedulingStartTime = timeSource.currentTimeMillis();

    authentication.begin();
    try {
        StopWatch sw = new Slf4JStopWatch("Scheduling.processTasks");
        Coordinator.Context context;
        try {
            context = coordinator.begin();
        } catch (SchedulingLockException e) {
            return;
        }
        try {
            for (ScheduledTask task : context.getTasks()) {
                processTask(task);
            }
        } finally {
            coordinator.end(context);
        }
        sw.stop();
    } finally {
        authentication.end();
    }
}