Search in sources :

Example 66 with APIException

use of org.openmrs.api.APIException in project openmrs-core by openmrs.

the class TimerSchedulerServiceImpl method deleteTask.

/**
 * Delete the task with the given identifier.
 *
 * @param id the identifier of the task
 */
@Override
public void deleteTask(Integer id) {
    TaskDefinition task = getTask(id);
    if (task.getStarted()) {
        throw new APIException("Scheduler.timer.task.delete", (Object[]) null);
    }
    // delete the task
    getSchedulerDAO().deleteTask(id);
}
Also used : TaskDefinition(org.openmrs.scheduler.TaskDefinition) APIException(org.openmrs.api.APIException)

Example 67 with APIException

use of org.openmrs.api.APIException in project openmrs-core by openmrs.

the class StartupFilter method renderTemplate.

/**
 * All private attributes on this class are returned to the template via the velocity context
 * and reflection
 *
 * @param templateName the name of the velocity file to render. This name is prepended with
 *            {@link #getTemplatePrefix()}
 * @param referenceMap
 * @param httpResponse
 */
protected void renderTemplate(String templateName, Map<String, Object> referenceMap, HttpServletResponse httpResponse) throws IOException {
    // his http session) and merge that tools context with basic velocity context
    if (referenceMap == null) {
        return;
    }
    Object locale = referenceMap.get(FilterUtil.LOCALE_ATTRIBUTE);
    ToolContext velocityToolContext = getToolContext(locale != null ? locale.toString() : Context.getLocale().toString());
    VelocityContext velocityContext = new VelocityContext(velocityToolContext);
    for (Map.Entry<String, Object> entry : referenceMap.entrySet()) {
        velocityContext.put(entry.getKey(), entry.getValue());
    }
    Object model = getModel();
    // put each of the private varibles into the template for convenience
    for (Field field : model.getClass().getDeclaredFields()) {
        try {
            field.setAccessible(true);
            velocityContext.put(field.getName(), field.get(model));
        } catch (IllegalArgumentException | IllegalAccessException e) {
            log.error("Error generated while getting field value: " + field.getName(), e);
        }
    }
    String fullTemplatePath = getTemplatePrefix() + templateName;
    InputStream templateInputStream = getClass().getClassLoader().getResourceAsStream(fullTemplatePath);
    if (templateInputStream == null) {
        throw new IOException("Unable to find " + fullTemplatePath);
    }
    velocityContext.put("errors", errors);
    velocityContext.put("msgs", msgs);
    // explicitly set the content type for the response because some servlet containers are assuming text/plain
    httpResponse.setContentType("text/html");
    try {
        velocityEngine.evaluate(velocityContext, httpResponse.getWriter(), this.getClass().getName(), new InputStreamReader(templateInputStream, StandardCharsets.UTF_8));
    } catch (Exception e) {
        throw new APIException("Unable to process template: " + fullTemplatePath, e);
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) VelocityContext(org.apache.velocity.VelocityContext) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ToolContext(org.apache.velocity.tools.ToolContext) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) APIException(org.openmrs.api.APIException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) Field(java.lang.reflect.Field) APIException(org.openmrs.api.APIException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 68 with APIException

use of org.openmrs.api.APIException in project openmrs-core by openmrs.

the class StartupFilter method toJSONString.

/**
 * Convenience method to convert the given object to a JSON string. Supports Maps, Lists,
 * Strings, Boolean, Double
 *
 * @param object object to convert to json
 * @return JSON string to be eval'd in javascript
 */
protected String toJSONString(Object object) {
    ObjectMapper mapper = new ObjectMapper();
    mapper.getJsonFactory().setCharacterEscapes(new OpenmrsCharacterEscapes());
    try {
        return mapper.writeValueAsString(object);
    } catch (IOException e) {
        log.error("Failed to convert object to JSON");
        throw new APIException(e);
    }
}
Also used : APIException(org.openmrs.api.APIException) IOException(java.io.IOException) OpenmrsCharacterEscapes(org.openmrs.OpenmrsCharacterEscapes) ObjectMapper(org.codehaus.jackson.map.ObjectMapper)

Example 69 with APIException

use of org.openmrs.api.APIException in project openmrs-core by openmrs.

the class Daemon method executeScheduledTask.

/**
 * Executes the given task in a new thread that is authenticated as the daemon user. <br>
 * <br>
 * This can only be called from {@link TimerSchedulerTask} during actual task execution
 *
 * @param task the task to run
 * @should not be called from other methods other than TimerSchedulerTask
 * @should not throw error if called from a TimerSchedulerTask class
 */
public static void executeScheduledTask(final Task task) throws Exception {
    // quick check to make sure we're only being called by ourselves
    Class<?> callerClass = new OpenmrsSecurityManager().getCallerClass(0);
    if (!TimerSchedulerTask.class.isAssignableFrom(callerClass)) {
        throw new APIException("Scheduler.timer.task.only", new Object[] { callerClass.getName() });
    }
    // now create a new thread and execute that task in it
    DaemonThread executeTaskThread = new DaemonThread() {

        @Override
        public void run() {
            isDaemonThread.set(true);
            try {
                Context.openSession();
                TimerSchedulerTask.execute(task);
            } catch (Exception e) {
                exceptionThrown = e;
            } finally {
                Context.closeSession();
            }
        }
    };
    executeTaskThread.start();
    // wait for the "executeTaskThread" thread to finish
    try {
        executeTaskThread.join();
    } catch (InterruptedException e) {
    // ignore
    }
    if (executeTaskThread.exceptionThrown != null) {
        throw executeTaskThread.exceptionThrown;
    }
}
Also used : TimerSchedulerTask(org.openmrs.scheduler.timer.TimerSchedulerTask) APIException(org.openmrs.api.APIException) OpenmrsSecurityManager(org.openmrs.util.OpenmrsSecurityManager) APIException(org.openmrs.api.APIException) ModuleException(org.openmrs.module.ModuleException) APIAuthenticationException(org.openmrs.api.APIAuthenticationException)

Example 70 with APIException

use of org.openmrs.api.APIException in project openmrs-core by openmrs.

the class ServiceContext method setModuleService.

/**
 * Allow other services to be added to our service layer <br>
 * <br>
 * Classes will be found/loaded with the ModuleClassLoader <br>
 * <br>
 * <code>params</code>[0] = string representing the service interface<br>
 * <code>params</code>[1] = service instance
 *
 * @param params list of parameters
 */
public void setModuleService(List<Object> params) {
    String classString = (String) params.get(0);
    Object classInstance = params.get(1);
    if (classString == null || classInstance == null) {
        throw new APIException("service.unable.find", (Object[]) null);
    }
    Class cls = null;
    // environment or not (system == testing, openmrs == normal)
    try {
        if (!useSystemClassLoader) {
            cls = OpenmrsClassLoader.getInstance().loadClass(classString);
            if (cls != null && log.isDebugEnabled()) {
                try {
                    log.debug("cls classloader: " + cls.getClass().getClassLoader() + " uid: " + cls.getClass().getClassLoader().hashCode());
                } catch (Exception e) {
                /*pass*/
                }
            }
        } else if (useSystemClassLoader) {
            try {
                cls = Class.forName(classString);
                if (log.isDebugEnabled()) {
                    log.debug("cls2 classloader: " + cls.getClass().getClassLoader() + " uid: " + cls.getClass().getClassLoader().hashCode());
                    // pay attention that here, cls = Class.forName(classString), the system class loader and
                    // cls2 is the openmrs class loader, like above.
                    log.debug("cls==cls2: " + String.valueOf(cls == OpenmrsClassLoader.getInstance().loadClass(classString)));
                }
            } catch (Exception e) {
            /*pass*/
            }
        }
    } catch (ClassNotFoundException e) {
        throw new APIException("service.unable.set", new Object[] { classString }, e);
    }
    // add this module service to the normal list of services
    setService(cls, classInstance);
    // Run onStartup for all services implementing the OpenmrsService interface.
    if (OpenmrsService.class.isAssignableFrom(classInstance.getClass())) {
        moduleOpenmrsServices.put(classString, (OpenmrsService) classInstance);
        runOpenmrsServiceOnStartup((OpenmrsService) classInstance, classString);
    }
}
Also used : APIException(org.openmrs.api.APIException) APIException(org.openmrs.api.APIException) BeansException(org.springframework.beans.BeansException)

Aggregations

APIException (org.openmrs.api.APIException)86 Date (java.util.Date)11 IOException (java.io.IOException)10 ArrayList (java.util.ArrayList)10 File (java.io.File)9 Obs (org.openmrs.Obs)7 List (java.util.List)6 Map (java.util.Map)6 User (org.openmrs.User)6 FileInputStream (java.io.FileInputStream)5 FileOutputStream (java.io.FileOutputStream)5 Concept (org.openmrs.Concept)5 OpenmrsObject (org.openmrs.OpenmrsObject)5 InputStream (java.io.InputStream)4 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)4 Order (org.openmrs.Order)4 FileNotFoundException (java.io.FileNotFoundException)3 OutputStreamWriter (java.io.OutputStreamWriter)3 MessageDigest (java.security.MessageDigest)3 HashMap (java.util.HashMap)3